/**
 * @namespace MS public namespace for Metservice widget
 */
METS = window.METS || {};


(function() {

    if (METS && METS.Widget) {
        // this is most likely to happen when people try to embed multiple
        // widgets on the same page and include this script again
        return;
    }
    

    /**
     * @constructor Widget Base for new instances of the Metservice widget
     * @param {Object} opts the configuration options for the widget
     */
   METS.Widget = function(opts) {
     this.init(opts);
   };
   
   METS.Widget.TypeOne = "one";
   METS.Widget.TypeTwo = "two";


   METS.Widget.widgetElements = {};
   METS.Widget.prototype = function() {
       return {
           init: function(opts) {
               if (opts != undefined && opts) {
                   METS.Widget.widgetElements[opts.id] = {type:opts.type, host:opts.host, city:opts.city};
               }
           }
       };
   }();
   
   
   
   METS.Widget.WarningMap= new Array();
   METS.Widget.WarningMap["ashburton"] = {"location": "Ashburton", "warnings": "CANTERBURY", "tsWarnings": "ASHBURTON", "tsWatch": "CANTERBURY PLAINS"};
   METS.Widget.WarningMap["auckland"] = {"location": "Auckland", "warnings": "AUCKLAND", "tsWarnings": "RODNEY, NORTH SHORE CITY, AUCKLAND CITY, WAITAKERE CITY, MANUKAU CITY, PAPAKURA, FRANKLIN", "tsWatch": "AUCKLAND"};
   METS.Widget.WarningMap["blenheim"] = {"location": "Blenheim", "warnings": "MARLBOROUGH", "tsWarnings": "MARLBOROUGH, TASMAN", "tsWatch": "MARLBOROUGH"};
   METS.Widget.WarningMap["christchurch"] = {"location": "Christchurch", "warnings": "CANTERBURY", "tsWarnings": "CHRISTCHURCH CITY, BANKS PENINSULA", "tsWatch": "CHRISTCHURCH"};
   METS.Widget.WarningMap["dannevirke"] = {"location": "Dannevirke", "warnings": "HAWKES BAY", "tsWarnings": "TARARUA", "tsWatch": "HAWKES BAY, TARARUA"};
   METS.Widget.WarningMap["dargaville"] = {"location": "Dargaville", "warnings": "NORTHLAND", "tsWarnings": "KAIPARA", "tsWatch": "NORTHLAND"};
   METS.Widget.WarningMap["dunedin"] = {"location": "Dunedin", "warnings": "OTAGO", "tsWarnings": "DUNEDIN CITY", "tsWatch": "DUNEDIN"};
   METS.Widget.WarningMap["gisborne"] = {"location": "Gisborne", "warnings": "GISBORNE", "tsWarnings": "GISBORNE", "tsWatch": "GISBORNE"};
   METS.Widget.WarningMap["gore"] = {"location": "Gore", "warnings": "SOUTHLAND", "tsWarnings": "GORE", "tsWatch": "SOUTHLAND"};
   METS.Widget.WarningMap["greymouth"] = {"location": "Greymouth", "warnings": "WESTLAND", "tsWarnings": "GREYMOUTH", "tsWatch": "WESTLAND"};
   METS.Widget.WarningMap["hamilton"] = {"location": "Hamilton", "warnings": "WAIKATO", "tsWarnings": "WAIKATO, WAIPA, HAMILTON CITY", "tsWatch": "WAIKATO"};
   METS.Widget.WarningMap["hastings"] = {"location": "Hastings", "warnings": "HAWKES BAY", "tsWarnings": "HASTINGS DISTRICT", "tsWatch": "HAWKES BAY"};
   METS.Widget.WarningMap["hokitika"] = {"location": "Hokitika", "warnings": "WESTLAND", "tsWarnings": "WESTLAND", "tsWatch": "WESTLAND"};
   METS.Widget.WarningMap["invercargill"] = {"location": "Invercargill", "warnings": "SOUTHLAND", "tsWarnings": "INVERCARGILL", "tsWatch": "SOUTHLAND"};
   METS.Widget.WarningMap["kaikoura"] = {"location": "Kaikoura", "warnings": "MARLBOROUGH", "tsWarnings": "KAIKOURA, TASMAN", "tsWatch": "MARLBOROUGH"};
   METS.Widget.WarningMap["kaitaia"] = {"location": "Kaitaia", "warnings": "NORTHLAND", "tsWarnings": "FAR NORTH", "tsWatch": "NORTHLAND"};
   METS.Widget.WarningMap["kerikeri"] = {"location": "Kerikeri", "warnings": "NORTHLAND", "tsWarnings": "FAR NORTH", "tsWatch": "NORTHLAND"};
   METS.Widget.WarningMap["levin"] = {"location": "Levin", "warnings": "MANAWATU", "tsWarnings": "HOROWHENUA", "tsWatch": "MANAWATU, KAPITI, HOROWHENUA"};
   METS.Widget.WarningMap["motueka"] = {"location": "Motueka", "warnings": "NELSON", "tsWarnings": "TASMAN", "tsWatch": "NELSON"};
   METS.Widget.WarningMap["napier"] = {"location": "Napier", "warnings": "HAWKES BAY", "tsWarnings": "HASTINGS DISTRICT, NAPIER CITY", "tsWatch": "HAWKES BAY"};
   METS.Widget.WarningMap["nelson"] = {"location": "Nelson", "warnings": "NELSON", "tsWarnings": "NELSON CITY, TASMAN", "tsWatch": "NELSON"};
   METS.Widget.WarningMap["new-plymouth"] = {"location": "New Plymouth", "warnings": "TARANAKI", "tsWarnings": "NEW PLYMOUTH", "tsWatch": "TARANAKI"};
   METS.Widget.WarningMap["oamaru"] = {"location": "Oamaru", "warnings": "OTAGO", "tsWarnings": "WAITAKI", "tsWatch": "NORTH OTAGO"};
   METS.Widget.WarningMap["palmerston-north"] = {"location": "Palmerston North", "warnings": "MANAWATU", "tsWarnings": "MANAWATU, PALMERSTON NORTH CITY", "tsWatch": "MANAWATU"};
   METS.Widget.WarningMap["paraparaumu"] = {"location": "Paraparaumu", "warnings": "MANAWATU", "tsWarnings": "KAPITI COAST", "tsWatch": "KAPITI, HOROWHENUA"};
   METS.Widget.WarningMap["queenstown"] = {"location": "Queenstown", "warnings": "OTAGO", "tsWarnings": "QUEENSTOWN LAKES, CENTRAL OTAGO", "tsWatch": "SOUTHERN LAKES, CENTRAL OTAGO", "roadSnowFall": "LINDIS PASS"};
   METS.Widget.WarningMap["reefton"] = {"location": "Reefton", "warnings": "BULLER", "tsWarnings": "BULLER", "tsWatch": "BULLER", "roadSnowFall": "LEWIS PASS"};
   METS.Widget.WarningMap["rotorua"] = {"location": "Rotorua", "warnings": "BAY OF PLENTY ROTORUA", "tsWarnings": "ROTORUA", "tsWatch": "ROTORUA"};
   METS.Widget.WarningMap["taumarunui"] = {"location": "Taumarunui", "warnings": "TAUMARUNUI", "tsWarnings": "RUAPEHU", "tsWatch": "TAUMARUNUI"};
   METS.Widget.WarningMap["taupo"] = {"location": "Taupo", "warnings": "TAUPO", "tsWarnings": "TAUPO", "tsWatch": "TAUPO", "roadSnowFall": "DESERT ROAD"};
   METS.Widget.WarningMap["tauranga"] = {"location": "Tauranga", "warnings": "BAY OF PLENTY ROTORUA", "tsWarnings": "WESTERN BAY OF PLENTY, TAURANGA", "tsWatch": "BAY OF PLENTY"};
   METS.Widget.WarningMap["te-kuiti"] = {"location": "Te Kuiti", "warnings": "WAITOMO", "tsWarnings": "WAITOMO", "tsWatch": "WAITOMO"};
   METS.Widget.WarningMap["thames"] = {"location": "Thames", "warnings": "COROMANDEL PENINSULA", "tsWarnings": "HAURAKI, THAMES, COROMANDEL", "tsWatch": "COROMANDEL PENINSULA"};
   METS.Widget.WarningMap["timaru"] = {"location": "Timaru", "warnings": "CANTERBURY", "tsWarnings": "TIMARU", "tsWatch": "CANTERBURY PLAINS"};
   METS.Widget.WarningMap["tokoroa"] = {"location": "Tokoroa", "warnings": "WAIKATO", "tsWarnings": "SOUTH WAIKATO", "tsWatch": "WAIKATO"};
   METS.Widget.WarningMap["wanaka"] = {"location": "Wanaka", "warnings": "OTAGO", "tsWarnings": "QUEENSTOWN LAKES", "tsWatch": "SOUTHERN LAKES", "roadSnowFall": "LINDIS PASS"};
   METS.Widget.WarningMap["wanganui"] = {"location": "Wanganui", "warnings": "WANGANUI", "tsWarnings": "WANGANUI", "tsWatch": "WANGANUI"};
   METS.Widget.WarningMap["wellington"] = {"location": "Wellington", "warnings": "WELLINGTON", "tsWarnings": "WELLINGTON CITY, UPPER HUTT CITY, HUTT CITY, PORIRUA", "tsWatch": "WELLINGTON", "roadSnowFall": "RIMUTAKA HILL ROAD"};
   METS.Widget.WarningMap["westport"] = {"location": "Westport", "warnings": "BULLER", "tsWarnings": "BULLER", "tsWatch": "BULLER"};
   METS.Widget.WarningMap["whakatane"] = {"location": "Whakatane", "warnings": "BAY OF PLENTY ROTORUA", "tsWarnings": "WHAKATANE", "tsWatch": "BAY OF PLENTY"};
   METS.Widget.WarningMap["whangarei"] = {"location": "Whangarei", "warnings": "NORTHLAND", "tsWarnings": "WHANGAREI", "tsWatch": "NORTHLAND"};


   METS.Widget.localForcastForJsonpCallback = function(data) {
       if (data.location) {
           METS.jQuery.each(METS.Widget.widgetElements, function(id, widgetElement) {
               if (widgetElement.city.toLowerCase() == data.location.toLowerCase()) {
                   if (widgetElement.type.toLowerCase() == METS.Widget.TypeOne){
                       METS.jQuery('#MSmygallery'+id+'-paginate').find('.MSregion').html(METS.Widget.capitalise(widgetElement.city)); 
                       
                       var daysCount = eval(data.days).length;
                       for (var i = 0; i < daysCount && i < 3 ; i++) {
                           var day = '#MSfcday' + i;
                           forecastElem = METS.jQuery('#'+id);
                           forecastElem.find(day+' .MSdateright').html('Issued: '+data.days[i].issuedAt);    
                           forecastElem.find(day+' .MSdate .MSuppercase').html(data.days[i].dow);
                           forecastElem.find(day+' .MSdate .MSdateMonth').html(data.days[i].date);
                           forecastElem.find(day+' .MStemp .max').before('<img alt="' + data.days[i].forecastWord + '" src="' + METS.homesite + '/assets/img/weather-icons/big/' + METS.Widget.cleanStr(data.days[i].forecastWord, true, true) + '_wht.gif" width="50" height="42" />');
                           forecastElem.find(day+' .MStemp .max').html(data.days[i].max + '&deg;C');
                           forecastElem.find(day+' .MStemp .min').html(data.days[i].min + '&deg;C');
                           forecastElem.find(day+' p:last').html(data.days[i].forecast);
                       }
                   }
                   else if (widgetElement.type.toLowerCase() == METS.Widget.TypeTwo) {
                       METS.jQuery('#'+id).find('#MSmygallery'+id+'-paginate').html(METS.Widget.capitalise(widgetElement.city));
                       var daysCount = eval(data.days).length;
                       for (var i = 0; i < daysCount && i < 3 ; i++) {
                           if (i < 3) {
                               forecastElem = METS.jQuery('#MSfcday'+i+'Temp2'+id);
                               forecastElem.find('.MSuppercase span').html(data.days[i].dow); 
                               forecastElem.find('.MSuppercase').before('<img id="'+'#MSfcday'+i+'Temp2'+id+'Img" alt="' + data.days[i].forecastWord + '" src="' + METS.homesite  + '/assets/img/weather-icons/big/' + METS.Widget.cleanStr(data.days[i].forecastWord, true, true) + '_wht.gif" style="width:35px !important; height:35px !important;"/>');
                               forecastElem.find('.max').html(data.days[i].max + '&deg;C');
                               forecastElem.find('.min').html(data.days[i].min + '&deg;C');
                           }

                       }
                       
                   }
               }
           });
       }
   };
   
   
   METS.Widget.warningsDataForJsonpCallback = function(data) {
       if (data) {
           METS.jQuery.each(METS.Widget.widgetElements, function(id, widgetElement) {
               var town = METS.Widget.WarningMap[widgetElement.city.toLowerCase().replace(' ','-')];
               var showWarning = false;
               for (var j in data.severeWarnings) {
	               if (data.severeWarnings[j].loc == town.warnings) {
	            	   for (var k in data.severeWarnings[j].warn) {
	            		   showWarning = true;
	                   }
            	   }
               }
               
               if (town.tsWatch != undefined && data.thunderstormWatch != undefined && data.thunderstormWatch.text != undefined && data.thunderstormWatch.isIconExpired != true) {
                   var warnText = data.thunderstormWatch.text;
                   var warnTown = ''; 
                   var tsWarnNoted = false;
                   if (town.tsWatch != undefined) {
                       if (town.tsWatch.indexOf(',') >= 0) {
                           var townArr = town.tsWatch.split(',');
                           for ( var tn in townArr) {
                               if (warnText.toUpperCase().indexOf(townArr[tn].trim()) >= 0) {
                                   tsWarnNoted = true;
                                   break;
                               }
                           }
                       }
                       else {
                           if (warnText.toUpperCase().indexOf(town.tsWatch) >= 0) {
                               tsWarnNoted = true;
                           }
                       }
                   }
                   if (tsWarnNoted) {
                       showWarning = true;
                   }
               }
               
               for (var j in data.thunderstormWarnings) {
                   var warnText = data.thunderstormWarnings[j].warnText;
                   var warnTown = ''; 
                   var tsWarnNoted = false;
                   if (town.tsWarnings != undefined) {
                       if (town.tsWarnings.indexOf(',') >= 0) {
                           var townArr = town.tsWarnings.split(',');
                           for ( var tn in townArr) {
                               if (warnText.toUpperCase().indexOf(townArr[tn].trim()) >= 0) {
                                   tsWarnNoted = true;
                                   break;
                               }
                           }
                       }
                       else {
                           if (warnText.toUpperCase().indexOf(town.tsWarnings) >= 0) {
                               tsWarnNoted = true;
                           }
                       }
                   }
                   if (tsWarnNoted) {
                       showWarning = true;
                   }
               }
               
               
               if (data.sWatchText != undefined) {
                   if (data.sWatchText.toUpperCase().indexOf(town.warnings) >= 0) {
                       showWarning = true;
                   }
               }
               if (data.specialAdvisory != undefined) {
                   if (data.specialAdvisory.toUpperCase().indexOf(town.warnings) >= 0) {
                       showWarning = true;
                   }
               }
               for (var j in data.roadSnowWarnings) {
                   if (town.roadSnowFall && town.roadSnowFall.indexOf(data.roadSnowWarnings[j].toUpperCase()) >= 0) {
                       showWarning = true;
                   }
               }
               if (data.isVhf && town.location == 'Auckland') {
                   showWarning = true;
               }
               if (widgetElement.type.toLowerCase() == METS.Widget.TypeOne) {
                    stepcarouselSetup(id, showWarning);
               } 
               else if (widgetElement.type.toLowerCase() == METS.Widget.TypeTwo) {
                   if (showWarning) {
                       METS.jQuery('#MSmygallery'+id).before('<a href="http://www.metservice.com/national/warnings/index" target="_blank" ><span id="MSwarning'+id+'" class="MSwarning">Warnings in force</span></a>');
                       METS.jQuery('#MSmygallery'+id).css('cssText', 'height:68px !important; width: 230px !important; overflow: hidden !important;');
                       METS.jQuery('#MSmygallery'+id).find('.panel').each(function () {
                           METS.jQuery(this).css('cssText', 'height:67px !important;');
                       });
                       METS.jQuery('#MSmygallery'+id).find('.MStemp2').each(function () {
                           METS.jQuery(this).css('cssText', 'height:62px !important;');
                       });
                       METS.jQuery('#MSmygallery'+id).find('.MStemp3').each(function () {
                           METS.jQuery(this).css('cssText', 'height:62px !important;');
                       });
                       
                   }
               }
                
               function stepcarouselSetup(id, showWarningIn) {

                   if (showWarningIn == true) {
                       METS.stepcarousel.setup({
                           galleryid: 'MSmygallery'+id, 
                           beltclass: 'belt', 
                           panelclass: 'panel', 
                           autostep: {enable:false, moveby:1, pause:3000},
                           panelbehavior: {speed:500, wraparound:false, wrapbehavior:'slide', persist:true},
                           defaultbuttons: {enable: true, moveby: 1, leftnav: [METS.homesite+'/assets/img/widget/left-arrow.png', 0, 0, 'leftnav'+id], rightnav: [METS.homesite+'/assets/img/widget/right-arrow.png', -9, 0, 'rightnav'+id]},
                           statusvars: ['statusA', 'statusB', 'statusC'],
                           contenttype: ['inline'] 
                       });
                       METS.jQuery('#rightnav'+id).css({padding:'26px 0px 25px 0px'});  
                       METS.jQuery('#leftnav'+id).css({padding:'26px 0px 25px 0px'});  
                       METS.jQuery('#MSwarning'+id).replaceWith('<a href="http://www.metservice.com/national/warnings/index" target="_blank" ><span id="MSwarning'+id+'" class="MSwarning">Warnings in force</span></a>');
                       
                   }
                   else {
                       METS.stepcarousel.setup({
                           galleryid: 'MSmygallery'+id,
                           beltclass: 'belt',
                           panelclass: 'panel',
                           autostep: {enable:false, moveby:1, pause:3000},
                           panelbehavior: {speed:500, wraparound:false, wrapbehavior:'slide', persist:true},
                           defaultbuttons: {enable: true, moveby: 1, leftnav: [METS.homesite+'/assets/img/widget/left-arrow.png', 0, -14, 'leftnav'+id], rightnav: [METS.homesite+'/assets/img/widget/right-arrow.png', -9, -14, 'rightnav'+id]},
                           statusvars: ['statusA', 'statusB', 'statusC'],
                           contenttype: ['inline']
                       });
                       METS.jQuery('#MSmygalleryMSwidgetTypeOne #belt').removeClass('belt').addClass('belt-nowarning');                       
                   }
                   METS.jQuery('#MSmygallery'+id+'-paginate span').css('cssText', 'padding-right: 8px !important;float: right !important; ');

                }  
           });
       }
   };
   
   
   METS.Widget.loadCSS = function() {
       var iscssLoaded = false;
       METS.jQuery.each(METS.Widget.widgetElements, function(id, widgetElement) {
           if (iscssLoaded == true) return;
           iscssLoaded = true;
           var cssElement = document.createElement('link');
           cssElement.setAttribute("rel", "stylesheet");
           cssElement.setAttribute("type", "text/css");
           cssElement.setAttribute("href",  'http://'+widgetElement.host+ "/assets/css/MSwidget.css");
           (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(cssElement);
       
           if (navigator.appName=="Microsoft Internet Explorer") {
               if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { // test for MSIE x.x;
                   var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
                   if (ieversion >= 9 ) {
                       var cssElementie = document.createElement('link');
                       cssElementie.setAttribute("rel", "stylesheet");
                       cssElementie.setAttribute("type", "text/css");
                       cssElementie.setAttribute("href",  'http://'+widgetElement.host+ "/assets/css/MSwidget-ie9.css");
                       (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(cssElementie);
                   }
                   else if (ieversion == 8 ) {
                       var cssElementie = document.createElement('link');
                       cssElementie.setAttribute("rel", "stylesheet");
                       cssElementie.setAttribute("type", "text/css");
                       cssElementie.setAttribute("href",  'http://'+widgetElement.host+ "/assets/css/MSwidget-ie8.css");
                       (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(cssElementie);
                   }
                   else if (ieversion <= 7) {
                       var cssElementie = document.createElement('link');
                       cssElementie.setAttribute("rel", "stylesheet");
                       cssElementie.setAttribute("type", "text/css");
                       cssElementie.setAttribute("href",  'http://'+widgetElement.host+ "/assets/css/MSwidget-ie7.css");
                       (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(cssElementie);
                  }
               }
           }
       });
   },
   
   METS.Widget.applyCSS = function(id) {
       if (navigator.appName=="Microsoft Internet Explorer") {
           var backgroundCSSIE = 'background: url("'+METS.homesite+'/assets/img/widget/rounded-img.png") no-repeat !important;';
           METS.jQuery('#'+id).css('cssText', backgroundCSSIE);
       }
       else {
           var backgroundCSS = 'background: url("'+METS.homesite+'/assets/img/widget/gradient.png") repeat-x scroll 0% 0% rgb(255, 255, 255) !important;';
           METS.jQuery('#'+id).css('cssText', backgroundCSS);
       }
   };
   
   METS.Widget.echoWidgetHTML = function() {
       var widgetHTML = '';
       var jsonpCalls = {};
       METS.jQuery.each(METS.Widget.widgetElements, function(id, widgetElement) {
           widgetHTML = '';
           if (!METS.homesite) {
               if (widgetElement.host) {
                   METS.homesite = 'http://' + widgetElement.host;
               }
               else{
                   METS.homesite ='http://www.metservice.com';
               }
           }

           if (!jsonpCalls[widgetElement.city]) {
               var jsonpCityName = METS.Widget.capitalise(widgetElement.city);
               jsonpCityName = jsonpCityName.replace(' ', '-');
               jsonpCalls[widgetElement.city] = METS.homesite+"/publicData/localForecastForJsonp"+jsonpCityName; 
           }

           if (widgetElement.type.toLowerCase() == METS.Widget.TypeOne) {
               widgetHTML = '<div id="MSmygallery'+id+'-paginate" class="MSmygallery-paginate">'+"\n";
               widgetHTML +='  <div class="MSregion"></div>'+"\n";
               widgetHTML +='  <div id="circles"><img src="'+METS.homesite+'/assets/img/widget/closedcircle.png" data-over="'+METS.homesite+'/assets/img/widget/graycircle.png" data-select="'+METS.homesite+'/assets/img/widget/opencircle.png" data-moveby="1" /></div>'+"\n";
               widgetHTML +='</div>'+"\n"; 
               widgetHTML += '<div id="MSwarning'+id+'" class="MSnowarning">&nbsp;</div>'+"\n";
               widgetHTML += '<div id="MSmygallery'+id+'" style="width: 230px !important;" class="stepcarousel MSmygallery">'+"\n";
               widgetHTML += '  <div id="belt" class="belt" style="height:65px !important; width: 660px !important; left: -220px; position: absolute !important">'+"\n";
               widgetHTML += '          <div class="panel" style="position: absolute !important; left: 0px; float:left !important; width:231px !important;">'+"\n";
               widgetHTML += '                  <div id="MSfcday0">'+"\n";
               widgetHTML += '                          <div class="MStemp"><span class="max"></span><span class="min"></span></div>'+"\n";
               widgetHTML += '                          <div class="MSdate"><p><span class="MSuppercase">&nbsp;</span><span class="MSdateMonth">&nbsp;</span></p><p></p><div class="MSdateright"></div></div>'+"\n";
               widgetHTML += '                  </div>'+"\n";
               widgetHTML += '          </div>'+"\n";
               widgetHTML += '          <div class="panel" style="position: absolute !important; left: 231px !important; float:left !important; width:231px !important;">'+"\n";
               widgetHTML += '                  <div id="MSfcday1">'+"\n";
               widgetHTML += '                          <div class="MStemp"><span class="max"></span><span class="min"></span></div>'+"\n";
               widgetHTML += '                          <div class="MSdate"><p><span class="MSuppercase">&nbsp;</span><span class="MSdateMonth">&nbsp;</span></p><p></p><div class="MSdateright"></div></div>'+"\n";
               widgetHTML += '                  </div>'+"\n";
               widgetHTML += '          </div>'+"\n";
               widgetHTML += '          <div class="panel" style="position: absolute !important; left: 462px !important; float:left !important; width:231px !important;">'+"\n";
               widgetHTML += '                  <div id="MSfcday2">'+"\n";
               widgetHTML += '                          <div class="MStemp"><span class="max"></span><span class="min"></span></div>'+"\n";
               widgetHTML += '                          <div class="MSdate"><p><span class="MSuppercase">&nbsp;</span><span class="MSdateMonth">&nbsp;</span></p><p></p><div class="MSdateright"></div></div>'+"\n";
               widgetHTML += '                  </div>'+"\n";
               widgetHTML += '          </div>'+"\n";
               widgetHTML += '  </div>'+"\n";
               widgetHTML += '</div>'+"\n";
               widgetHTML += '<a href="#"><img class="MSdisclaimer" id="MSdisclaimer'+id+'" src="'+METS.homesite+'/assets/img/widget/metservice-disclaimer.png" alt="Metservice"></a>'+"\n";
               widgetHTML += '<a href="http://www.metservice.com/" target="_blank" class="MSlogo"><img src="'+METS.homesite+'/assets/img/widget/metservice-logo.png" alt="Metservice" width="118px" height="13"></a>'+"\n";
               widgetHTML += '<a href="http://www.metservice.com/towns-cities/'+widgetElement.city.toLowerCase().replace(' ','-')+'" target="_blank" class="MSfullForecast">10 day forecast</a>';
               METS.jQuery('#'+id).html(widgetHTML);
               
               var disclaimerHTML = '<div class="MSdisclaimerContainer" id="MSdisclaimer'+id+'-Container">';
               disclaimerHTML += '<div class="MSdisclaimerInner">';
               disclaimerHTML += '<h3>DISCLAIMER:</h3>';
               disclaimerHTML += '<p>As a user of this information you acknowledge the uncertainty inherent in weather forecasts. The information is provided "as is" without warranties of any kind, express or implied, including accuracy, completeness, correctness, timeliness or fitness for any particular purpose.</p>';
               disclaimerHTML += '</div>';
               disclaimerHTML += '</div>';
               METS.jQuery('#'+id).after(disclaimerHTML);
               
               METS.Widget.applyCSS(id);
               
               METS.jQuery('#MSmygallery'+id).css('cssText', 'width: 230px !important; overflow: hidden !important;');

           }
           else if (widgetElement.type.toLowerCase() == METS.Widget.TypeTwo) {
               widgetHTML = '<p id="MSmygallery'+id+'-paginate" class="MSmygallery-paginate"></p>'+"\n";
               widgetHTML += '<div id="MSmygallery'+id+'"  style="height:80px !important" class="stepcarousel MSmygallery">'+"\n";
               widgetHTML += '  <div class="belt" style="height:80px !important" >'+"\n";
               widgetHTML += '          <div class="panel" style="height:79px !important">'+"\n";
               widgetHTML += '                  <div id="MSfcday0Temp2'+id+'" class="MStemp2"><p id="MSfcday0UppercaseTemp2'+id+'" class="MSuppercase"><span></span></p>'+"\n";
               widgetHTML += '                          <div class="tempmaxmin"><span id="MSfcday0TempMax'+id+'" class="max"></span><span id="MSfcday0TempMin'+id+'" class="min"></span></div>'+"\n";
               widgetHTML += '                  </div>' + "\n";
               widgetHTML += '                  <div id="MSfcday1Temp2'+id+'" class="MStemp2"><p id="MSfcday1UppercaseTemp2'+id+'" class="MSuppercase"><span></span></p>'+"\n";
               widgetHTML += '                          <div class="tempmaxmin"><span id="MSfcday1TempMax'+id+'" class="max"></span><span id="MSfcday1TempMin'+id+'" class="min"></span></div>'+"\n";
               widgetHTML += '                  </div>'+"\n";
               widgetHTML += '                  <div id="MSfcday2Temp2'+id+'" class="MStemp3"><p id="MSfcday2UppercaseTemp3'+id+'" class="MSuppercase"><span></span></p>'+"\n";
               widgetHTML += '                          <div class="tempmaxmin"><span id="MSfcday2TempMax'+id+'" class="max"></span><span id="MSfcday2TempMin'+id+'" class="min"></span></div>'+"\n";
               widgetHTML += '                  </div>'+"\n";
               widgetHTML += '          </div>'+"\n";
               widgetHTML += '  </div>'+"\n";
               widgetHTML += '</div>'+"\n";
               widgetHTML += '<a href="#"><img class="MSdisclaimer" id="MSdisclaimer'+id+'" src="'+METS.homesite+'/assets/img/widget/metservice-disclaimer.png" alt="Metservice"></a>'+"\n";
               widgetHTML += '<a href="http://www.metservice.com/" target="_blank" class="MSlogo"><img src="'+METS.homesite+'/assets/img/widget/metservice-logo.png" alt="Metservice"></a>'+"\n";
               widgetHTML += '<a href="http://www.metservice.com/towns-cities/'+widgetElement.city.toLowerCase().replace(' ','-')+'" target="_blank" class="MSfullForecast">10 day forecast</a>'+"\n";

               METS.jQuery('#'+id).html(widgetHTML);
               
               METS.Widget.applyCSS(id);
               
               var disclaimerHTML = '<div class="MSdisclaimerContainer" id="MSdisclaimer'+id+'-Container">';
               disclaimerHTML += '<div class="MSdisclaimerInner">';
               disclaimerHTML += '<h3>DISCLAIMER:</h3>';
               disclaimerHTML += '<p>As a user of this information you acknowledge the uncertainty inherent in weather forecasts. The information is provided "as is" without warranties of any kind, express or implied, including accuracy, completeness, correctness, timeliness or fitness for any particular purpose.</p>';
               disclaimerHTML += '</div>';
               disclaimerHTML += '</div>';
               METS.jQuery('#'+id).after(disclaimerHTML);
               
               METS.jQuery('#MSmygallery'+id).css('cssText', 'height:80px !important; width: 230px !important; overflow: hidden !important;');
           }
           

           METS.jQuery('.MSdisclaimer').mouseover( function () {
               METS.jQuery('.MSdisclaimerContainer').hide();
               var left = ((METS.jQuery(this).offset().left))+'px';
               var top = (METS.jQuery(this).offset().top+20)+'px';
               var id = '#' + METS.jQuery(this).attr('id')+'-Container';
              // METS.jQuery(id).css('cssText', 'top:'+top+' !important');
               METS.jQuery(id).css('left', left);
               METS.jQuery(id).css('top', top);
               METS.jQuery(id).fadeIn(100);
           });
           
           METS.jQuery('.MSdisclaimer').mouseleave( function () {
               var id = '#' + METS.jQuery(this).attr('id')+'-Container';
               t = setTimeout( function() { METS.jQuery(id).fadeOut(100) }, 500);
           });
           
           METS.jQuery('.MSdisclaimerContainer').mouseover( function () {
               clearTimeout(t);
           });
           
           
           METS.jQuery('.MSdisclaimerContainer').mouseleave( function () {
               var div =  METS.jQuery(this);
               t = setTimeout( function() {  METS.jQuery(div).fadeOut(100) }, 500);
           }); 
           
       });
       
       METS.jQuery.each(jsonpCalls , function(id, url) {
           METS.jQuery.ajax({
               type: "GET",
               url:  url,
               data: {},
               contentType: "application/json; charset=utf-8",
               dataType: "jsonp",
               jsonp : "callback",
               cache:true,
               jsonpCallback: "METS.Widget.localForcastForJsonpCallback"
           });
       });


       METS.jQuery.ajax({
           type: "GET",
           url:  METS.homesite+"/publicData/warningsDataForJsonp",
           data: {},
           contentType: "application/json; charset=utf-8",
           dataType: "jsonp",
           jsonp : "callback",
           cache:false,
           jsonpCallback: "METS.Widget.warningsDataForJsonpCallback"
       });
       
   }
   
   
   METS.Widget.capitalise = function(string) {
       var capitalisedString = '';
       var strings = string.split(' ');
       METS.jQuery.each(strings, function(id, string) {
           capitalisedString += string.substr(0, 1).toUpperCase() + string.substr(1, string.length - 1);
           if (id != (strings.length - 1)) {
               capitalisedString = capitalisedString + ' ';
           }
       });
       return capitalisedString;
   };
   
   METS.Widget.render = function() {
       METS.Widget.loadCSS();
       METS.Widget.echoWidgetHTML();
   };
   
   METS.Widget.cleanStr = function(str, toLower, removeSpaces) {
       if (str==null) str = '';
       if (toLower==null) toLower = false;
       if (removeSpaces==null) removeSpaces = false;
       var t = (removeSpaces) ? str.replace(/ /g, '-') : str;
       t = t.replace('~', '-');
       t = t.replace('\'', '');
       t = t.replace('/', '-');
       t = (toLower) ? t.toLowerCase() : t;
       return t;
   };
   
    
    /******** Load jQuery if not present *********/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.5.1') {
        var isJQueryLoaded = false;
        var jQueryScriptTag = document.createElement('script');
        jQueryScriptTag.setAttribute("type", "text/javascript");
        // jQueryScriptTag.setAttribute("src","http://202.21.130.171:81/assets/js/jquery-1.5.1.min.js");
        // jQueryScriptTag.setAttribute("src","http://wll054/assets/js/jquery-1.5.1.min.js");
        jQueryScriptTag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js");
        /*@cc_on @*/
        /*@if (@_win32)
            jQueryScriptTag.onreadystatechange = function () { // Same thing but for IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    loadJQueryHandler();
                }
            };
            isJQueryLoaded = true;
        /*@end @*/
        
        if (/Firefox/i.test(navigator.userAgent)) {
            jQueryScriptTag.onload = loadJQueryHandler;
            isJQueryLoaded = true;
        }
        
        if (window.opera) { // sniff
            if (document.addEventListener) {
                document.addEventListener("DOMContentLoaded", loadJQueryHandler, false);
            }
            isJQueryLoaded = true;
        }
        
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(jQueryScriptTag); 
        
        /* for Safari */
        if (/WebKit/i.test(navigator.userAgent)) { 
            var jQueryLoadingTimer = setInterval(function() {
                    if (window.jQuery && window.jQuery.fn.jquery == '1.5.1') {  
                        loadJQueryHandlerWapperSafari();
                    }
                }, 5);
            isJQueryLoaded = true;
        }
        
        if (!isJQueryLoaded) {
            loadJQueryHandler();
        }
    }
    else{
        loadJQueryHandler();
    }
    
    function loadJQueryHandlerWapperSafari() {
        if (arguments.callee.done) return;
        arguments.callee.done = true;
        if (jQueryLoadingTimer) clearInterval(jQueryLoadingTimer);
        loadJQueryHandler();
    }
    
    function loadJQueryHandler() {
        METS.jQuery = window.jQuery.noConflict(true);
        METS.stepcarousel = window.stepcarousel || createStepcarousel();
        // METS.stepcarousel = createStepcarousel();

        METS.jQuery(document).ready(function() { 
            METS.Widget.render();
        });
    }
    function createStepcarousel() {
        return {
                ajaxloadingmsg: '<div style="margin: 1em !important; font-weight: bold !important;"><img src="ajaxloadr.gif" style="vertical-align: middle !important;" /> Fetching Content. Please wait...</div>', // customize HTML to show while fetching Ajax content
                defaultbuttonsfade: 0.4, // Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
                configholder: {},
    
                getCSSValue:function(val) { // Returns either 0 (if val contains 'auto') or val as an integer
                    return (val=="auto") ? 0 : parseInt(val)
                },
    
                getremotepanels:function($, config) { // function to fetch external page containing the panel DIVs
                    config.$belt.html(this.ajaxloadingmsg)
                    $.ajax({
                            url: config.contenttype[1], // path to external content
                            async: true,
                            error:function(ajaxrequest) {
                                    config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
                            },
                            success:function(content) {
                                    config.$belt.html(content)
                                    config.$panels=config.$gallery.find('.'+config.panelclass)
                                    METS.stepcarousel.alignpanels($, config)
                            }
                    })
                },
    
                getoffset:function(what, offsettype) {
		 //   var wooObj = what.getBoundingClientRect();
		 //   window.offsetInfor += "offsettype:"+ offsettype+"|className:"+what.className + "|value:" + what[offsettype] + "|wooObj.left:"+wooObj.left+"jQuery.Offset:"+METS.jQuery(what).offset().left+";"; 
         //           METS.jQuery(what).offset().left; 
		    return (what.offsetParent) ? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
                },
    
                getCookie:function(Name) { 
                    var re=new RegExp(Name+"=[^;]+", "i"); // construct RE to search for target name/value pair
                    if (document.cookie.match(re)) // if cookie found
                        return document.cookie.match(re)[0].split("=")[1] // return its value
                    return null
                },
    
                setCookie:function(name, value) {
                    document.cookie = name+"="+value
                },
    
                fadebuttons:function(config, currentpanel) {
                    config.$leftnavbutton.fadeTo('fast', currentpanel==0 ? this.defaultbuttonsfade : 1)
                        config.$rightnavbutton.fadeTo('fast', currentpanel==config.lastvisiblepanel ? this.defaultbuttonsfade : 1)
                        if (currentpanel==config.lastvisiblepanel) {
                            METS.stepcarousel.stopautostep(config)
                        }
                },
    
                addnavbuttons:function($, config, currentpanel) {
                    config.$leftnavbutton=$('<img id="'+config.defaultbuttons.leftnav[3]+'" src="'+config.defaultbuttons.leftnav[0]+'">').css({zIndex:50, background:'#e3e3e3', padding:'32px 0px 34px 0px', position:'absolute', left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px', cursor:'hand', cursor:'pointer'}).appendTo('body')
                    config.$rightnavbutton=$('<img id="'+config.defaultbuttons.rightnav[3]+'" src="'+config.defaultbuttons.rightnav[0]+'">').css({zIndex:50, background:'#e3e3e3',padding:'32px 0px 34px 0px', position:'absolute', left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px', cursor:'hand', cursor:'pointer'}).appendTo('body')
                    config.$leftnavbutton.bind('click', function() { // assign nav button event handlers
                            METS.stepcarousel.stepBy(config.galleryid, -config.defaultbuttons.moveby)
                    })
                    config.$rightnavbutton.bind('click', function() { // assign nav button event handlers
                            METS.stepcarousel.stepBy(config.galleryid, config.defaultbuttons.moveby)
                    })
                    if (config.panelbehavior.wraparound==false) { // if carousel viewer should stop at first or last panel (instead of wrap back or forth)
                        this.fadebuttons(config, currentpanel)
                    }
                    return config.$leftnavbutton.add(config.$rightnavbutton)
                },
    
                alignpanels:function($, config) {
                    var paneloffset=0
                    config.paneloffsets=[paneloffset] // array to store upper left offset of each panel (1st element=0)
                    config.panelwidths=[] // array to store widths of each panel
                    config.$panels.each(function(index) { // loop through panels
                            var $currentpanel=$(this)
                            // $currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) position panel
							$currentpanel.css({left: paneloffset+'px'})
                            $currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) // bind onpanelclick() to onclick event
                            paneloffset+=METS.stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth || $currentpanel.css('width')) // calculate next panel offset
                            config.paneloffsets.push(paneloffset) // remember this offset
                            config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) // remember panel width
                    })
                    config.paneloffsets.pop() // delete last offset (redundant)
                    var addpanelwidths=0
                    var lastpanelindex=config.$panels.length-1
                    config.lastvisiblepanel=lastpanelindex
                    for (var i=config.$panels.length-1; i>=0; i--) {
                        addpanelwidths+=(i==lastpanelindex? config.panelwidths[lastpanelindex] : config.paneloffsets[i+1]-config.paneloffsets[i])
                        if (config.gallerywidth>addpanelwidths) {
                            config.lastvisiblepanel=i // calculate index of panel that when in 1st position reveals the very last panel all at once based on gallery width
                        }
                    }
                    // config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
                    config.currentpanel=(config.panelbehavior.persist) ? parseInt(this.getCookie(config.galleryid+"persist")) : 0 // determine 1st panel to show by default
                    config.currentpanel=(typeof config.currentpanel=="number" && config.currentpanel<config.$panels.length) ? config.currentpanel : 0
                    var endpoint=config.paneloffsets[config.currentpanel]+(config.currentpanel==0 ? 0 : config.beltoffset)
                    config.$belt.css({left: -endpoint+'px'})
                    if (config.defaultbuttons.enable==true) { // if enable default back/forth nav buttons
                        var $navbuttons=this.addnavbuttons($, config, config.currentpanel)
                        $(window).bind("load resize", function() { // refresh position of nav buttons when page  loads/resizes, in case offsets weren't available document.oncontentload
                                //config.offsets={left:METS.stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:METS.stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}

                                config.offsets={left:METS.jQuery(config.$gallery.get(0)).offset().left, top:METS.jQuery(config.$gallery.get(0)).offset().top}
                                config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
                                config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
                                })
                    }
                    if (config.autostep && config.autostep.enable) { // enable auto stepping of Carousel?
                        var $carouselparts=config.$gallery.add(typeof $navbuttons!="undefined"? $navbuttons : null)
                        $carouselparts.bind('click', function() {
                                config.autostep.status="stopped"
                                METS.stepcarousel.stopautostep(config)
                            })
                        $carouselparts.hover(function() { // onMouseover
                                METS.stepcarousel.stopautostep(config)
                                config.autostep.hoverstate="over"
                                }, function() { // onMouseout
                                        if (config.steptimer && config.autostep.hoverstate=="over" && config.autostep.status!="stopped") {
                                            config.steptimer=setInterval(function(){METS.stepcarousel.autorotate(config.galleryid)}, config.autostep.pause)
                                            config.autostep.hoverstate="out"
                                        }
                                })
                        config.steptimer=setInterval(function(){METS.stepcarousel.autorotate(config.galleryid)}, config.autostep.pause) // automatically rotate Carousel Viewer
                    } // end enable auto stepping check
                    this.createpaginate($, config)
                    this.statusreport(config.galleryid)
                    config.oninit()
                    config.onslideaction(this)
                },
    
                stepTo:function(galleryid, pindex) { /* User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
                    var config=METS.stepcarousel.configholder[galleryid]
                    if (typeof config=="undefined") {
                        // alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
                        return
                    }
                    METS.stepcarousel.stopautostep(config)
                    var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
                    var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
                    if (config.panelbehavior.wraparound==false && config.defaultbuttons.enable==true) { // if carousel viewer should stop at first or last panel (instead of wrap back or forth)
                        this.fadebuttons(config, pindex)
                    }
                    config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function() {config.onslideaction(this)} )
                    config.currentpanel=pindex
                    this.statusreport(galleryid)
                },
    
                stepBy:function(galleryid, steps, isauto) {
                    var config=METS.stepcarousel.configholder[galleryid]
                    if (typeof config=="undefined") {
                        // alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
                        return
                    }
                    if (!isauto) // if stepBy() function isn't called by autorotate() function
                        METS.stepcarousel.stopautostep(config)
                    var direction=(steps>0)? 'forward' : 'back' // If "steps" is negative, that means backwards
                    var pindex=config.currentpanel+steps // index of panel to stop at
                    if (config.panelbehavior.wraparound==false) { // if carousel viewer should stop at first or last panel (instead of wrap back or forth)
                        pindex=(direction=="back" && pindex<=0) ? 0 : (direction=="forward") ? Math.min(pindex, config.lastvisiblepanel) : pindex
                        if (config.defaultbuttons.enable==true){ // if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
                            METS.stepcarousel.fadebuttons(config, pindex)
                        }       
                    }
                    else { // else, for normal stepBy behavior
                        if (pindex>config.lastvisiblepanel && direction=="forward") {
                            // if destination pindex is greater than last visible panel, yet we're currently not at the end of the carousel yet
                            pindex=(config.currentpanel<config.lastvisiblepanel)? config.lastvisiblepanel : 0
                        }
                        else if (pindex<0 && direction=="back") {
                            // if destination pindex is less than 0, yet we're currently not at the beginning of the carousel yet
                            pindex=(config.currentpanel>0)? 0 : config.lastvisiblepanel /* wrap around left */
                        }
                    }
                    var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) // left distance for Belt DIV to travel to
                    if (config.panelbehavior.wraparound==true && config.panelbehavior.wrapbehavior=="pushpull" && (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back')) { 
                        // decide whether to apply "push pull" effect
                        config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function() {
                                config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
                        })
                    }
                    else
                        config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
                    config.currentpanel=pindex
                    this.statusreport(galleryid)
                },
    
                autorotate:function(galleryid) {
                    var config=METS.stepcarousel.configholder[galleryid]
                    this.stepBy(galleryid, config.autostep.moveby, true)
                },
    
                stopautostep:function(config) {
                    clearTimeout(config.steptimer)
                },
    
                statusreport:function(galleryid) {
                    var config=METS.stepcarousel.configholder[galleryid]
                    if (config.statusvars.length==3) { // if 3 status vars defined
                        var startpoint=config.currentpanel // index of first visible panel
                        var visiblewidth=0
                        for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++) { // index (endpoint) of last visible panel
                            visiblewidth+=config.panelwidths[endpoint]
                            if (visiblewidth>config.gallerywidth) {
                                break
                            }
                        }
                        startpoint+=1 // format startpoint for user friendiness
                        endpoint=(endpoint+1==startpoint) ? startpoint : endpoint // If only one image visible on the screen and partially hidden, set endpoint to startpoint
                        var valuearray=[startpoint, endpoint, config.panelwidths.length]
                        for (var i=0; i<config.statusvars.length; i++) {
                             window[config.statusvars[i]]=valuearray[i] // Define variable (with user specified name) and set to one of the status values
                             config.$statusobjs[i].text(valuearray[i]+" ") // Populate element on page with ID="user specified name" with one of the status values
                        }
                    }
                    METS.stepcarousel.selectpaginate(METS.jQuery, galleryid)
                },
    
                createpaginate:function($, config) {
                    if (config.$paginatediv.length==1) {
                        var $templateimg=config.$paginatediv.find('img["data-over"]:eq(0)') // reference first matching image on page
                        var controlpoints=[], controlsrc=[], imgarray=[], moveby=$templateimg.attr("data-moveby") || 1
                        var asize=(moveby==1? 0:1) + Math.floor((config.lastvisiblepanel+1) / moveby) // calculate # of pagination links to create
                        var imghtml=$('<div>').append($templateimg.clone()).html() // get HTML of first matching image
                        srcs=[$templateimg.attr('src'), $templateimg.attr('data-over'), $templateimg.attr('data-select')] // remember control's over and out, and selected image src
                        for (var i=0; i<asize; i++) {
                             var moveto=Math.min(i*moveby, config.lastvisiblepanel)
                             imgarray.push(imghtml.replace(/>$/, ' data-index="'+i+'" data-moveto="'+moveto+'" >') +'\n')
                             controlpoints.push(moveto) // store panel index each control goes to when clicked on
                        }
                        var $controls=$('<span></span>').replaceAll($templateimg).append(imgarray.join('')).find('img') // replace template link with links and return them
                        $controls.css({cursor:'pointer'})
                        config.$paginatediv.bind('click', function(e) {
                                var $target=$(e.target)
                                if ($target.is('img') && $target.attr('data-over')) {
                                    METS.stepcarousel.stepTo(config.galleryid, parseInt($target.attr('data-moveto'))+1)
                                }
                            })
                        config.$paginatediv.bind('mouseover mouseout', function(e) {
                                var $target=$(e.target)
                                if ($target.is('img') && $target.attr('data-over')) {
                                    if (parseInt($target.attr('data-index')) != config.pageinfo.curselected) // if this isn't the selected link
                                        $target.attr('src', srcs[(e.type=="mouseover") ? 1 : 0])
                                    }
                            })
                        config.pageinfo={controlpoints:controlpoints, $controls:$controls,  srcs:srcs, prevselected:null, curselected:null}
                    }
                },
    
                
                selectpaginate:function($, galleryid) {
                    var config=METS.stepcarousel.configholder[galleryid]
                    if (config.$paginatediv.length==1) {
                        for (var i=0; i<config.pageinfo.controlpoints.length; i++) {
                            if (config.pageinfo.controlpoints[i] <= config.currentpanel) // find largest control point that's less than or equal to current panel shown
                                config.pageinfo.curselected=i
                        }
                        
                        if (typeof config.pageinfo.prevselected!=null) // deselect previously selected link (if found)
                            config.pageinfo.$controls.eq(config.pageinfo.prevselected).attr('src', config.pageinfo.srcs[0])
                                
                        config.pageinfo.$controls.eq(config.pageinfo.curselected).attr('src', config.pageinfo.srcs[2]) // select current paginate link
                        config.pageinfo.prevselected=config.pageinfo.curselected // set current selected link to previous
                    }
                },
    
    
                loadcontent:function(galleryid, url) {
                    var config=METS.stepcarousel.configholder[galleryid]
                    config.contenttype=['ajax', url]
                    METS.stepcarousel.stopautostep(config)
                    METS.stepcarousel.resetsettings($, config)
                    METS.stepcarousel.init(METS.jQuery, config)
    
                },
    
                init:function($, config) {
                    config.gallerywidth=config.$gallery.width()
                   // config.offsets={left:METS.stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:METS.stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}

                    config.offsets={left:METS.jQuery(config.$gallery.get(0)).offset().left, top:METS.jQuery(config.$gallery.get(0)).offset().top}
                    config.$belt=config.$gallery.find('.'+config.beltclass) // Find Belt DIV that contains all the panels
                    config.$panels=config.$gallery.find('.'+config.panelclass) // Find Panel DIVs that each contain a slide
                    config.panelbehavior.wrapbehavior=config.panelbehavior.wrapbehavior || "pushpull" // default wrap behavior to "pushpull"
                    config.$paginatediv=$('#'+config.galleryid+'-paginate') // get pagination DIV (if defined)
                    if (config.autostep)
                        config.autostep.pause+=config.panelbehavior.speed
                    
                    config.onpanelclick=(typeof config.onpanelclick=="undefined") ? function(target){} : config.onpanelclick // attach custom "onpanelclick" event handler
                    config.onslideaction=(typeof config.onslide=="undefined") ? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} // attach custom "onslide" event handler
                    config.oninit=(typeof config.oninit=="undefined") ? function(){} : config.oninit // attach custom "oninit" event handler
                    config.beltoffset=METS.stepcarousel.getCSSValue(config.$belt.css('marginLeft')) // Find length of Belt DIV's left margin
                    config.statusvars=config.statusvars || []  // get variable names that will hold "start", "end", and "total" slides info
                    config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
                    config.currentpanel=0
                    METS.stepcarousel.configholder[config.galleryid]=config // store config parameter as a variable
                    if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") // fetch ajax content?
                        METS.stepcarousel.getremotepanels($, config)
                    else
                        METS.stepcarousel.alignpanels($, config) // align panels and initialize gallery
                },
    
                resetsettings:function($, config) {
                    config.$gallery.unbind()
                    config.$belt.stop()
                    config.$panels.remove()
                    if (config.$leftnavbutton) {
                        config.$leftnavbutton.remove()
                        config.$rightnavbutton.remove()
                    }
                    if (config.$paginatediv.length==1) {
                        config.$paginatediv.unbind()
                        config.pageinfo.$controls.eq(0).attr('src', config.pageinfo.srcs[0]).removeAttr('data-index').removeAttr('data-moveto').removeAttr('title') // reset first pagination link so it acts as template again
                                .end().slice(1).remove() // then remove all but first pagination link
                    }
                    if (config.autostep)
                        config.autostep.status=null
                    
                    if (config.panelbehavior.persist){
                        METS.stepcarousel.setCookie(window[config.galleryid+"persist"], 0) // set initial panel to 0, overridden w/ current panel if window.unload is invoked
                    }
                },
    
                setup:function(config) {
                    // Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
                    // document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
    
                    METS.jQuery(document).ready(function($) {
                            config.$gallery=$('#'+config.galleryid)
                            METS.stepcarousel.init($, config)
                        }) // end document.ready
                    METS.jQuery(window).bind('unload', function() { // clean up on page unload
                            METS.stepcarousel.resetsettings($, config)
                            if (config.panelbehavior.persist)
                                METS.stepcarousel.setCookie(config.galleryid+"persist", config.currentpanel)
                            
                            METS.jQuery.each(config, function(ai, oi) {
                                    oi=null
                                })
                            config=null
                        })
                }
        };
    }

})();

