/* ForeSee survey implementation

   Added 2011.08.05 by jbri
   ForeSee requires a call to the foresee-trigger.js at the top of every page.
   Currently the only way to do that would be to edit the template for each page type on the site and regen the entire website or
   include it in this global.js - hence:
   
   document.write('<scr' + 'ipt type="text\/javascript" src="\/includes\/foresee\/foresee-trigger.js"><\/script>'); 
*/
   document.write('<scr' + 'ipt type="text\/javascript" src="\/includes\/foresee\/foresee-trigger.js"><\/script>'); 

if (window.pge) _pge = pge;

// global PG&E object : loads external JS scripts dynamically based on the existance of corresponding class name in the DOM
pge = {
    survey : 'off',
	info : 'Pacific Gas & Electric Base JavaScript',
	lang : 'en', // change this to an expression that gets the correct language value [en,es,vi,zh]
	log : function() {
		try{console.log.apply('',arguments);} catch(e) {}
	},
	gbl : {},
	scriptsLoc : '/includes/js/', // change to absolute path once we integrate into platform
	mod : {
		'accordion' : {},
		'calendar' : {},
		'carousel' : {},
		'cookie' : {},
		'dashboardbill' : {},
		'datepicker' : {},
		'disabletable' : {},
		'dismissable_alert' : {},
		'malleable_form' : {},
		'maphilight' : {},
		'modalhelp' : {},
		'password' : {},
		'payment_option_group' : {},
		'programs-filter' : {},
		'req_pay_arrangement_bill_summary' : {},
		'scroll_table_bdy' : {},
		'simplemodal' : {},
		'services' : {},
		'slider' : {},
		'stickie' : {},
		'tablefilter' : {},
		'tablesorter' : {},
		'tabviewer' : {},
		'tipsfilter' : {},
		'toggle' : {},
		'tooltip' : {},
		'usage_utilities' : {},
		'usage_meter_widget' : {},
		'validate' : {},
		'youtube_module' : {}
	},
	loaded : [],
	init : function() {

		var temp;

		// remove non-js message from DOM
		$('.enableJS').remove();

		// preload images
		(function(){
			var imagesToLoad = [
				'/includes/images/TPL/site/landing2.0/bg-tooltip-left.png',
				'/includes/images/TPL/site/landing2.0/bg-tooltip-right.png',
				'/includes/images/TPL/site/landing2.0/bg-tooltip-image-left.png',
				'/includes/images/TPL/site/landing2.0/bg-tooltip-image-right.png'
			];
			$('<div class="no-print" style="position:absolute;left:-9999px;top:-9999px;height:0;width:0;overflow:hidden;"/>').appendTo('body').html('<img src="'+imagesToLoad.join('"/><img src="')+'"/>');
		})();

        // Survey bar
        $(document).ready(function() {
            // Trying to display the survey bar once every four user
            if ( pge.survey == 'on' ){
                if ( Math.floor(Math.random()*4) == 2 ){ // ==2 is random, it could have been any number from 0 to 3
                    // Create html element
                    $(document.createElement("div")).attr("id","glb-alert-container").prependTo("body");
                    $("#glb-alert-container").html('<p>Tell Us How We\'re Doing! Please <a href="http://survey.qualtrics.com/SE/?SID=SV_8AniTmLubWZ2htG&SVID=Prod" target="_blank">take our survey.</a><img src="/includes/images/TPL/icon/remove.gif" alt="remove" /></p>');

                    if ($.cookie("alert-bar") != 'no'){
                        $("#glb-alert-container").slideDown("slow");
                    }

                    $('#glb-alert-container img').click(function() {
                        $.cookie("alert-bar", "no", { expires: 7 });
                        $("#glb-alert-container").slideUp("slow");
                    });
                }
            }
        });

		// [plugin] treat spacebar 'keypress' event the same as the mouse 'click' event
		$.fn.klik = function(f){
			return this.bind('click keypress', function(e) {
				if (!e.keyCode || e.keyCode == 32){
					return f.call(this, e);
				}
			});
		};

		// add easeOutQuad to the easing options and make it the default option
		jQuery.extend(jQuery.easing, {
			def: 'easeOutQuad',
			easeOutQuad: function (x, t, b, c, d) {
				return -c *(t/=d)*(t-2) + b;
			}
		});

		// instantiate language selection and set cookie on selection
		temp = $('#glb-hdr-toolbar .heading').klik(function(){

			var p = this.parentNode;
			$(p).toggleClass('open');
			pge.overlays.pushUnique(p);

			$('#language-options a').klik(function(e) {
				$.cookie('pgeLang',$(this).attr('class'));
			});

			return false;

		})[0];

		// prevent text selection (of language selector text) in ie
		if (temp && temp.attachEvent) {
			temp.attachEvent('onselectstart',function(){return false});
		}

		// submit form
		$('ul#language-options a').klik(function() {
			$('input[name=langSel]').attr('value',$(this).attr('class'));
			$('#change-lang').submit();
		});

		// button roll-over
		if ($.browser.msie && $.browser.version == 6 ) {
			$('input.move-forward, a.move-forward, a.move-backward').hover(function(){ 
				var y = $(this).css('background-position-y'); 
				var newY = parseInt(y) - 50; 
				$(this).css('background-position-y',newY); 
			}, 
			function(){ 
				var y = $(this).css('background-position-y'); 
				var newY = parseInt(y) + 50; 
				$(this).css('background-position-y',newY); 
			});
		}
		else {
			$('input.move-forward, a.move-forward').hover(function(){$(this).addClass('rollover-forward')},function(){$(this).removeClass('rollover-forward')});
			$('a.move-backward').hover(function(){$(this).addClass('rollover-backward')},function(){$(this).removeClass('rollover-backward')});
		}

		// setup and, if needed, load modules & plugins from other files
		$.each(pge.mod, function(moduleName) {
			$.extend(pge.mod[moduleName], {
				className : '.mod-' + moduleName,
				load : function(m) {
					if($.inArray(moduleName, pge.loaded) < 0) {

						var s = document.createElement('script');
						s.src = pge.scriptsLoc + 'pge.' + moduleName.replace(/_/g,'-') + '.js';
						$('head').append(s);

						(function(){
							if(!pge.mod[moduleName].init){
								setTimeout(arguments.callee, 30);
								return;
							}
							pge.mod[moduleName].init(m);
						})();

						pge.loaded.push(moduleName);
					}
				}
			});

			var module = $('.'+moduleName.replace(/_/g,'-'));
			if (module.size()){
				pge.mod[moduleName].load(module);
			}
		});

		// primary nav li:hover
		$('#glb-hdr-primary-nav>li').hover(
			function(){
				if ($('.tertiary-nav',this).size()) {
					$(this).addClass('over');
				}
			},
			function(){
				$(this).removeClass('over');
			}
		);

		// printing - "print-page" class
		$('.print-page').click(function(){window.print()});

		// special treatment for the login page for ie6
		// why not just use a css expression? because it isn't evaluated if you "maximize" or "restore" the window size, or if you only resize it vertically
		$('.ie6 .login').each(function(){
			window.onresize = function(){
				setTimeout(function(){
					$('.login .glb-wrapper,.login .glb-wrapper-inner').css({height: Math.max(575, $('body').height())});
				}, 50);
			};
		});

		// intelligent auto-close-open-overlays (class name of "open" is used to control whether the overlay is 'open')
		$('body').klik(function(e){
			var targ = e.target,
				i = 0,
				keepOpen,
				list = pge.overlays.list;

			while(targ && ++i<10){
				for(var j in list){
					if(targ == list[j]){
						keepOpen = list[j];
					}
				}
				targ = targ.parentNode;
			}

			for(var j in list){
				if(keepOpen != list[j]){
					$(list[j]).removeClass('open'); // or, we could just .hide() it... or similar...
				}
			}
		});

		// global search box
		/**
		 * inputHint $ plugin
		 * @description: simulates default-text existing inside of <input>s by overlaying them with their <label>s
		 *               (<label class="hint" for="input-id"> may be substituted by <div title="for:input-id">)
		 *               http://remysharp.com/2007/03/19/a-few-more-$-plugins-crop-labelover-and-pluck/#labelOver
		 * @param overClass: the className to apply to the input hint (label or div)
		 */
		$.fn.inputHint = function(overClass) {
			return this.each(function(){
				var hint = $(this);
				// in this scope, "var f" means the element attribute "for"
				// .. "for" is a reserved word in the ECMA grammar
				var f = hint.attr('for') || hint.attr('title').split('for:').pop();
				if (f) {
					var input = $('#' + f).data('input-hint', hint[0]);

					this.hide = function() {
						hint.css({ left: -9999 });
					};

					this.show = function() {
						if (input.val() == ''){
							hint.css({ left: 0 });
						}
					};

					// handlers
					input.focus(this.hide);
					input.blur(this.show);
					hint.addClass(overClass).click(function(){input.focus()});

					if (input.val() != ''){
						this.hide();
					}
				}
			});
		};

		// apply plugin
		$('.input-hint').inputHint('hint-over');

		// no thanks links
		$('.no-thanks').klik(function(){
			var p = $(this).parent().parent();
			var div = p.parent().parent();
			if($(this).parents('.carousel').size()){
				p.find('p').css({'width':p.width()});
				p.animate({'width':0,'opacity':0}, 200, 'linear', function(){
					p.remove();
				});
				// trigger the scroll_update now, so that if this is the last item, the list will scroll
				div.trigger('scroll_update', p);
			} else {
				p.parent().animate({'height':0,'opacity':0}, 200, 'linear', function(){
					p.parent().remove();
				});
			}
			return false;
		});

		// pop new window for payment inserts
		$('.pop-inserts').klik(function(){
			window.open('i3-bill-payment-view-bill-insert.html','PacificGasElectricInserts','width=701,height=725,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no');
			return false;
		});

		// pop new window for bill explanation
		$('.pop-explanation').klik(function(){
			window.open('i3-bill-payment-bill-explanation.html','PacificGasElectricBillExplanation','width=701,height=729,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no');
			return false;
		});
	},

	// keep track of open overlays so that we are able to intelligently auto-close open overlays
	overlays:{
		list:[],
		pushUnique:function(o){
			var l = pge.overlays.list;
			for(var i in l){
				if(l[i] == o){
					return;
				}
			}
			l.push(o);
		}
	}

};

// instantiate PGE object
pge.init();

