
var Portal = {
  calendarUrl : 'http://calendar.ehawaii.gov/calendar',
  currentSection : '',
  initialized : false,
  _initCallbacks : [],
  _themeChangeCallbacks : [],
  sandboxed : false,
  _templateLoadedCallbacks : {},
  
  onInit : function(callback) {
    if (!Portal.initialized) {
		Portal._initCallbacks.push(callback);
	} else {
	  callback.apply(this, []);
	}
  },
  
  onTemplateLoaded : function(template, callback) {
      if (Portal.sandboxed) {
          if (!Portal._templateLoadedCallbacks[template]) {
	    Portal._templateLoadedCallbacks[template] = [];
	  }
	  Portal._templateLoadedCallbacks[template].push(callback);
	} else {
	  callback.apply(this, []);
	}
  },
  
  fireTemplateLoaded : function(template) {
    if (Portal.sandboxed) {
       var callbacks = Portal._templateLoadedCallbacks[template];
       
       if (callbacks) {
         $.each(callbacks, function(i, callback) {
	    callback.apply(this, []);
	 });
       }
    }
  },
  
  init : function() {
    var now = new Date();
	var hour = now.getHours();
	
	var isIdle = Portal.isIdle();
	if (Portal.isThemingEnabled()) {
	        var theme = $.cookie('theme');
	        var themeSet = !isIdle && theme;
		if (!themeSet) {
			if (hour >= 18 || hour <= 6) {
			  Portal._clickTheme('dusk');
			} else {
			  Portal._clickTheme('day');
			}
		} else {
		  Portal._clickTheme(theme);
		}
		
		$('.site-themes a').click(function() {
		  Portal._clickTheme($(this).text().toLowerCase());
		});
	} 
	
	Portal._prepareNavMenu();
	
	if (Portal.currentSection && Portal.currentSection != 'none') {
	  HowDoI.loadBlock('.how-do-i', Portal.currentSection, 5);
	}
	
	Portal.buildWeatherTicker('#top-weather');
	MM_preloadImages();
	Portal.initLiveChat();
	Portal.markCurrentPage();

	Portal.setupSearch('site');

	Portal.initialized = true;
	$.each(Portal._initCallbacks, function(i, callback) {
	  callback.apply(this, []);
	});
	
	setTimeout(function() {
	Portal.alignHeights();
	}, 100);
	
	window.switchTo5x = true;
	var scriptUrl = Portal.isHttps() ? 'https://ws.sharethis.com/button/buttons.js' : 'http://w.sharethis.com/button/buttons.js';
	$.getScript(scriptUrl, function() {
	  window.stLight.options({publisher:'96dfae2e-6ad8-4e88-bef4-36d8bce54323'});
	  
	  var btn = $('.sharethis_button').get(0);
	  window.stWidget.addEntry({
			"service":"sharethis",
			"element": btn,
			"url": location.href,
			"title":"Share this page",
			"type":"button",
			"text":"Share this page"    
			});
	});
	TextResizer.init();
	if (!Portal.sandboxed) {
            $('.feedback-link').each(function() {
		var $this = $(this);
		$this.attr('href', Portal.toHttps($this.attr('href')));
            });
	}
  },
  
  _prepareNavMenu : function()  {
    if ($.browser.MSIE && $.browser.version < 7) {
      $('.menu > ul > li').mouseover(function() {
	    Portal._toggleNav(this);
      });
	  
      $('.menu > ul > li').mouseout(function() {
	    Portal._toggleNav(this);
      });
    }
    
     $('.menu > ul > li > a').focus(function() {
      var $this = $(this);
      $('.menu > ul > li.menu_active').removeClass('menu_active');
      $this.parents('li').addClass('menu_active');
    });

    $(document).click(function() {
       $('.menu .menu_active').removeClass('menu_active');
    });

    $('.menu > ul > li:last-child ul li:last-child a').blur(function() {
      $('.menu .menu_active').removeClass('menu_active');
    });

    $(document).keydown(function(event) {
       if (event.which == 9 && event.shiftKey) {
         var focused = $('.menu > ul > li > a:focus');

         if (focused.length > 0) {
           if (focused.hasClass('first')) {
             $('.menu .menu_active').removeClass('menu_active');
           }
         }
       }
    });

  },
  
  _toggleNav : function(elem) {
    var $this = $(elem);
    var _ul = $this.find('ul');
    if (!_ul.is(':visible')) {
	_ul.show();
    } else {
        _ul.hide();
    }
  },
  
  setupSearch : function(searchType) {
    var field = $('.' + searchType + '-search .search-field');
	
	if (field.attr('title')) {
	  field.toggleVal({populateFrom: "custom", text: field.attr("title")});
	}
	
    $('.' + searchType + '-search .search-button').click(function() {
	     Portal.doSearch(searchType, field.val());
	});
	
	field.keypress(function(event) {
	     if (event.which == 13) {
		   Portal.doSearch(searchType, field.val());
		 }
	});
  },
  
  doSearch : function(searchType, query) {
    location.href = '/search/' + searchType + '.html?q=' + query;
  },
  
  readJsonFeed : function(feedId, args, callback) {
    var qs = '';
	
	if (args) {
		$.each(args, function(key, value) {
		  if (!$.isArray(value)) {
			qs += key + '=' + value + '&';
		  } else {
		    $.each(value, function(i, value2) {
			  qs += key + '=' + value2 + '&';
			});
		  }
		});
	}
	
	qs += 'callback=?';
	
	var url = Portal.getFeedServiceUrl() + '/' + feedId + '/feed.json?' + qs;
	$.jsonp({
      url: url,
      callbackParameter: "callback",
      success : callback
    });

  },
  
  readPopularServicesFeed : function(callback) {
    if (Portal.sandboxed) {
      Portal.readJsonFeed(17, {}, callback);
    } else {
      var t = new Date().getTime();
      $.getJSON('/json/popular-services.json?t=' + t, callback);
    }
  },
  
  readGovNewsFeed : function(args, callback) {
    if (Portal.sandboxed) {
      Portal.readJsonFeed(9, args, callback);
    } else {
      var t = new Date().getTime();
      $.getJSON('/json/gov-news.json?t=' + t, callback);
    }
  },
  
  buildWeatherTicker : function(selector) {
    var tickerBuilder = this;
    tickerBuilder._weather_ticker = function() {
		var elem = this;
		var weatherList = $(elem).find('.weather-value ul');
		weatherList.animate({left : '-1200'}, 50000, "linear", function() {
			weatherList.css('left', '300px');
			tickerBuilder._weather_ticker.apply(elem, []);
		});
    }
	
    Portal.readJsonFeed(7, {}, function(data) {
	    var elem = $(selector);
		var weather = elem.find('.weather-value');
		weather.html('<ul class="clearfix inline"></ul>');
		
		var weatherList = weather.find('ul');
		if (weatherList) {
			$.each(data, function(key, value) {
				weatherList.append("<li>" +value['island']+ " - " + value['weather'] + ", " + value["temperature"] + "</li>");
			});
			
			if (weatherList.find('li').length > 0) {
				tickerBuilder._weather_ticker.apply(elem, []);
			}
		}
	});

  },
  
  markCurrentPage : function() {
    var related = $('.related-links');
	if (related.length > -1) {
	  var path = location.pathname;
	  
	  related.find('a').each(function() {
	    var $this = $(this);
	    var href = $this.attr('href');
		
		if (href == path) {
		  $this.addClass('selected');
		}
	  });
	}
  },
  
  setTheme : function(theme) {

    var previousTheme = $.cookie('theme');
	
	if (!previousTheme) {
	  previousTheme = theme;
	}
	
    theme = theme.toLowerCase();
    $('#desktopTheme').attr('href', '/css/themes/' + theme + '/style.css');
	
	var searchTheme = $('#searchTheme');
	if (searchTheme.length > 0) {
	  searchTheme.attr('href', '/css/themes/' + theme + '/search.css');
	}
	
	var juiTheme = $('#juiTheme');
	if (juiTheme.length > 0) {
	  juiTheme.attr('href', '/css/themes/' + theme + '/jquery.ui.css');
	}
	
	$.cookie('theme', null);
	$.cookie('theme', theme, {expires : 1, path: '/'});
	
	
	$.each(Portal._themeChangeCallbacks, function(i, callback) {
	   callback.apply(this, [previousTheme, theme]);
	});
  },
  
  getTheme : function() {
    var theme = $.cookie('theme') || 'basic';
	return theme;
  },
  
  onThemeChanged : function(callback) {
    Portal._themeChangeCallbacks.push(callback);
  },
  
   _clickTheme : function(clickedTheme) {
	   $('.site-themes a').each(function(i, link) {
		  var linkElem = $(this);
		  var theme = linkElem.text().toLowerCase();
		  
		  if (clickedTheme == theme) {
			linkElem.parent().find('a').removeClass('selected');
			linkElem.addClass('selected');
			Portal.setTheme(theme);
		  }
	   });
  },
  
  isThemingEnabled : function() {
    return !$.browser.msie || ( $.browser.msie && $.browser.version > 6);
  },
  
  initLiveChat : function() {
    var prefix = location.href.substring(0, location.href.indexOf('/', 9));
    var onlineImg =  prefix + "/css/themes/common/chat-on.png";
	var offlineImg = prefix + "/css/themes/common/chat-off.png";
	var secureUrl = "https://secure.providesupport.com/image";
	var nonSecureUrl = "http://image.providesupport.com";
	var qs = "?ps_h=Mygb\u0026ps_t="+new Date().getTime()+"\u0026online-image=" + onlineImg + "\u0026offline-image=" + offlineImg;
	var urlPrefix = (location.protocol.indexOf("https")==0?secureUrl:nonSecureUrl);
	var url = urlPrefix+"/js/hic/safe-standard.js" + qs;

	var chat = $('.menuchat');
	chat.append('<div id="livehelp"><div id="ciMygb" style="z-index:100;position:absolute"></div><div id="scMygb" style="display:inline"></div><div id="sdMygb" style="display:none"></div>');

	var seMygb=document.createElement("script");
	seMygb.type="text/javascript";
	setTimeout(
	  function() {
	    seMygb.src=url;
		$('#sdMygb').append(seMygb);
		setTimeout(function() {
		    var _img = $('#livehelp img');
			if ($.browser.msie && $.browser.version < 7) {
				_img.attr("width", 100).attr("height", 40).addClass("png");
			}
			var src = _img.attr('src');
			var stat = "Help Chat - Offline";
			if (src) {
			  stat = src.indexOf('chat-on') > -1 ? "Help Chat - Online" : stat;
			  
			  var hcChat = $('#help-center-livehelp');
			  
			  if (hcChat.length > 0) {
			    var hcImg = hcChat.find('img');
			    var hcImgSrc = src.indexOf('chat-on') > -1 ? "helpchat-button-on.jpg" : "helpchat-button-off.jpg";
			    hcImg.attr('src', '/images/' + hcImgSrc);
			    hcImg.attr('alt', stat);
			  }

			}
			_img.attr('alt', stat);
		}, 1000);
	  },1);
  },
  
  alignHeights : function() {
  
    if (Portal.currentSection == 'landing') {
      var highest = 0;
      $.each(['#column1', '#column2', '#column3'], function(i, col) {
        var height = $(col).height();
	
	if (height > highest) {
	  highest = height;
	}
      });
      
      $('#column1,#column2,#column3').css("min-height", highest);
    } else if (Portal.currentSection != 'none'){
      var col1 = $('#column1');
      var section1 = $('#section1');
      
      if (col1.length > 0) {
	var col1Height = col1.height();
	var section1Height = section1.height();
	
	if (col1Height > section1Height) {
	  section1.css("min-height", col1Height);
	  col1.css("min-height", col1Height);
	} else {
	  col1.css("min-height", section1Height);
	  section1.css("min-height", section1Height);
	}
      }
    }

  },
  
  isIdle : function() {
    var activeTime = $.cookie('activeTime');
    var now = new Date();
    
    $.cookie('activeTime', now.getTime());
    
    if (!activeTime) {
      $.cookie('activeTime', new Date().getTime());
      return true;
    } else {
      var time = new Date();
      time.setTime(activeTime);
      
      var diff = Portal.timeDiff(now, time);
      
      if (diff >= 3600) {
        return true;
      }
    }
    return false;
  },
  
  timeDiff : function(time1, time2) {
    var diff = time1.getTime() - time2.getTime();
    return Math.floor(diff/1000);
  },
  
  log : function() {
    if (Portal._hasConsole() && typeof window.console.log != 'undefined') {
      console.log(arguments);
    }
  },

  debug: function() {
    if (Portal._hasConsole() && typeof window.console.debug != 'undefined') {
      console.debug(arguments);
    }
  },

  warn : function() {
    if (Portal._hasConsole() && typeof window.console.warn != 'undefined') {
      console.warn(arguments);
    }
  },

  error : function() {
    if (Portal._hasConsole() && typeof window.console.error != 'undefined') {
      console.error(arguments);
    }
  },

  _hasConsole : function() {
    return (typeof window.console != 'undefined');
  },
  
  isHttps : function() {
    return location.href.indexOf("https") == 0;
  },
  
  getFeedServiceUrl : function() {
    return (Portal.isHttps() ?  'https' : 'http') + '://fs.ehawaii.gov/feed-service/view';
  },
  
  toHttps : function(url) {
    if (url.indexOf('http:') != 0 && url.indexOf('https:') != 0) {
       var href = location.href;
       var hostStart = href.indexOf('://')+3;
       var hostEnd = href.indexOf('/', hostStart);
       var host = href.substring(hostStart, hostEnd);
       url = 'https://' + host + url;
    } else if (url.indexOf('http://') == 0) {
       var hostStart = url.indexOf('://')+3;
       url = 'https://' + url.substring(hostStart);
    }
    return url;
  }
};


var TextResizer = {
  opts : {
     unitType : 'em',
     defaultTextSize : 1,
     defaultMenuTextSize : 1,
     increment : .1,
     maxTextSize : 1.2,
	 minTextSize : 0.8,
	 defaultHeaderWidth : '',
	 resizeTargets : ['.container', '#nav', '.footer']
  },
  
  init : function() {
	  for (var i = 0; i < TextResizer.opts.resizeTargets.length; i++) {
		var selector = TextResizer.opts.resizeTargets[i];
		var isMenu = TextResizer.isMenuElem(selector);
		var target = $(selector);
		var size = TextResizer.textSize(isMenu ? 'menuTextSize' : 'textSize');
		Portal.log('selector', selector, 'size', size);
		$.each(target, function(i, t) {
		  $(t).css({'fontSize' : size});
		});
		
		
	  }
  },
  
  textSize : function(key, size) {
    
    if (typeof size != 'undefined') {
      TextResizer.setCookie(key, size);
    }
    
    if (!size) {
        size = TextResizer.getCookie(key);
    }
    
    if (!size) {
	size = (key == 'menuTextSize' ? TextResizer.opts.defaultMenuTextSize : TextResizer.opts.defaultTextSize) + 'em';
	TextResizer.setCookie(key, size);
    }
    
    return size;
  },
  
  resize : function(multiplier) {
    var opts = TextResizer.opts;
    for (var i = 0; i < opts.resizeTargets.length; i++) {
		var selector = opts.resizeTargets[i];
		var target = $(selector);
		var isMenu = TextResizer.isMenuElem(selector);
		
		var fontSize = target.css('font-size');
		var num = 1;
		
		if (!fontSize) {
		  var size = TextResizer.textSize(isMenu ? 'menuTextSize' : 'textSize');
		  fontSize = size;
		  target.css({'fontSize' : fontSize});
		  num = parseFloat(fontSize);
		} else {
		  var temp = TextResizer._stripSuffix(fontSize);
		  temp = $(temp).toEm();
		  fontSize = temp;
		  num = parseFloat(temp);
		}
		
		var newNum = (num + (multiplier * opts.increment));
		fontSize = newNum + 'em';

		if (multiplier > 0 && num > opts.maxTextSize) {
		  continue;
		} else if (multiplier < 0 && num < opts.minTextSize) {
		  continue;
		}
		
		target.css({'fontSize' :  fontSize});
		TextResizer.textSize('menuTextSize', fontSize);
		target.css({'fontSize' :  fontSize});
		TextResizer.textSize('textSize', fontSize);
		Portal.log('selector', selector, 'fontSize', fontSize);
    }
  },
  
  _stripSuffix : function(size) {
    if (typeof size == 'string') {
      return size.match(/\d*\.?\d+/);
    }
    return size + '';
  },
  
  isMenuElem : function(selector) {
	return selector == '#nav';
  },
  
  reset : function() {
      var opts = TextResizer.opts;
	  for (var i = 0; i < opts.resizeTargets.length; i++) {
		  var selector = opts.resizeTargets[i];
		  var target = $(selector);
		  if (target.length > 0) {
		      var isMenu = TextResizer.isMenuElem(selector);
		      var fontSize = (isMenu ? opts.defaultMenuTextSize : opts.defaultTextSize) + 'em';
		      var type = isMenu ? 'menuTextSize' : 'textSize';
		      
		      target.css({'fontSize' : fontSize});
		      TextResizer.textSize(type, fontSize);
		  }
	  }
  },
  
  setCookie : function(c_name,value,expiredays) {
    $.cookie(c_name, value, {expires : expiredays, path: '/'});
  },
  
  getCookie: function(c_name) {
	return $.cookie(c_name);
  }

};


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
