/*************************************************************************************************
Description: A script used by all pages, to perform common functions
Author: Jason McNeil, Marty Tremblay, Steven Leggett
Date: November 14, 2011
Current Version: 0.9
Version Notes:
	0.1 (Apr. 10, 2011) - Initial Development
	0.2 (May. 17, 2011) - Added language detection utils and function
        0.3 (July 15, 2011) - Capture Software Downloads and PDF downloads in Analytics
        0.4 (Aug. 3, 2011) - Determine User Level in Analytics
        0.5 (Aug. 24, 2011) - Fixing issue with language on BB devices going to consumer/en/en
        0.6 (Sept. 2, 2011) - Adding External link tracking
        0.7 (Oct. 21, 2011) - Additional Event Tracking for homepage trackLink() with async GA code
        0.8 (Oct. 25, 2011) - MP3 Tracking - Modified Homepage slider tracking, removed tracklink 
        0.9 (Nov. 14, 2011) - Adding image rollover effect
*************************************************************************************************/

//********** Functions and Utilities **********

// Usage  : alert(isdefined('myvar'));
function isdefined( variable) {
  return (typeof(window[variable]) == "undefined")?  false: true;
}


// Record External Link
function trackExternal (page) {
    var currentPage = $(location).attr('href').split("index.html");
    currentPage = currentPage[0];
    _gaq.push(['_trackEvent', 'Outbound Links', currentPage, page]);
}


// Change the current page language
function langChange (lang) {
    
     var currentPage = $(location).attr('href');
     switch (lang) {
           case "en":
               var splitPage = currentPage.split("/fr");
               var newPage = splitPage[0] + "/" + lang;
           break;

           case "fr":
                var splitPage = currentPage.split("/en");
                var newPage = splitPage[0] + "/" + lang;
           break;
     }
     //Redirect
     $(location).attr('href',newPage);
}

function langCheck () {
                var cookieLang = $.cookie('cookieLanguage');
                
		//setSiteLanguage( $.cookie('cookieLanguage') );
                //Jump to Initial Language Version of the same page? Cookie previously set
                var currentPage = $(location).attr('href');
                
                var currentPageLang = $(location).attr('href').split('/');
                // Determine Actual current Page Lang
                if ($.inArray("en", currentPageLang) != -1) {

                    currentPageLang = "en";
                    var splitPage = currentPage.split("/en");
                }
                else {
                    currentPageLang = "fr";
                    var splitPage = currentPage.split("/fr");
                }

                // If the Cookie Lang doesn't match page URL lang redirect
                if (currentPageLang != cookieLang) {
                    // Replace URL to different lang
                    newPage = splitPage[0] + "/" + cookieLang;
                    langChange(cookieLang);
                }
    
}

// Persist language by writing both a session and persistent cookie
function persistSiteLanguage (lang) {
	$.cookie('cookieLanguage', lang, { 
		expires: 365,
		path: "/"
	});
        
	$.cookie('sessionLanguage', lang, {
		path: "/"
	} );
}

//********** Fire this when a page has started loading **********

// Gracefully try to select appropriate language based first on cookie, then browser setting
if ( $.cookie('sessionLanguage') == null ) {
        // Has cookie - returning user
	if ( $.cookie('cookieLanguage') != null ) {
             var cookieLang = $.cookie('cookieLanguage');
              persistSiteLanguage( $.cookie('cookieLanguage') );
              langCheck();
	}//end has cookie

        // New User
	else {
		// Get the HTTP headers from a servlet to determine the browser's language.
		var browserLanguage = 'en'; // default to English

		$.ajax({
			url: "/resources/js/echoRequestHeadersSSI.html",
	
			dataType: 'json',
			success: function(headers) {
				browserLanguage = ( headers['Accept-Language'].substring(0,2).toLowerCase() == 'fr' ? 'fr' : 'en' );
				persistSiteLanguage(browserLanguage);
                                langCheck();
                                // Jump to language flip option - no cookie, set, new visitor
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
                        //alert("Error: "+textStatus);
			}
		});
	}
}

// ********** Fire this when a page has finished loading **********
$(document).ready(function () {
	
	
	// Convert (tm) nav items to proper superscript trademarks
	// English Trademarks
	$(".mid_column").find("h1:contains('(tm)')").each(function () {
		origTM = $(this).html();
		tmE = "<sup>TM</sup>";
		newTM = origTM.replace("(tm)", tmE);
		$(this).html(newTM);
	});
	
	$(".mid_column").find("h3:contains('(tm)')").each(function () {
		origTM = $(this).html();
		tmE = "<sup>TM</sup>";
		newTM = origTM.replace("(tm)", tmE);
		$(this).html(newTM);
	});
	
	//French Trademarks
	$(".mid_column").find("h1:contains('(mc)')").each(function () {
		origTM = $(this).html();
		tmE = "<sup>MC</sup>";
		newTM = origTM.replace("(mc)", tmE);
		$(this).html(newTM);
	});
	
	$(".mid_column").find("h3:contains('(mc)')").each(function () {
		origTM = $(this).html();
		tmE = "<sup>MC</sup>";
		newTM = origTM.replace("(mc)", tmE);
		$(this).html(newTM);
	});
	

	// Move all spans with the moveLinkToPreviousSibling class to the end of their previous sibling
	$(".moveLinkToEndOfPreviousSibling").each(function () {
		// Add a whitespace before the span is appended
		$(this).prev().append(" ");
		$(this).prev().append($(this));
	});
	
	// Bind to language links so to handle persistence
	$("a[href='../fr']").click(function () {
		persistSiteLanguage('fr');	
	});
	$("a[href='../en']").click(function () {
		persistSiteLanguage('en');
	});


	// Image RollOver Effect
    $(".rollover").hover(
    		function () {
		    	var iconName = $(this).attr("src");
                var rollover = iconName.replace( /active/, 'rollover' );
                $(this).attr({ src: rollover });
    		},
    		function () {
    			var iconName = $(this).attr("src");
                var static = iconName.replace( /rollover/, 'active' );
                $(this).attr({ src: static });
    });
    

 // ********** Google Analytics ********** 
////////////////////////////////////////////////    
    
        // Determine User Security Level for GA Custom Variable
    	/*
        var pages = $(location).attr('href').split('/');
        // ["http:", "", "www.empire.ca", "consumer", "about-us", "contact-us", "group-regional-offices", "en", "index.html"]
        // 
        // Secure Advisor
        if ($.inArray("secure", pages) != -1) {
            
            _gaq.push(['_setCustomVar',
                  1,                // Slot 1
                  'user-type',      // The name of the custom variable.  Required parameter.
                  'secure-advisor', // The value of the custom variable.  Required parameter.
                  1                 // Sets the scope to visitor-level.  Optional parameter.
             ]); 
        }

        // Advisor
        else if (($.inArray("secure", pages) == -1) && ($.inArray("advisor", pages) != -1)){
            
            _gaq.push(['_setCustomVar',
                  1,                // Slot 1
                  'user-type',      // The name of the custom variable.  Required parameter.
                  'advisor',        // The value of the custom variable.  Required parameter.
                  1                 // Sets the scope to visitor-level.  Optional parameter.
             ]); 
        }
            
        // Consumer
        else if (($.inArray("secure", pages) == -1) && ($.inArray("consumer", pages) != -1)){
           
            _gaq.push(['_setCustomVar',
                  1,                // Slot 1
                  'user-type',      // The name of the custom variable.  Required parameter.
                  'consumer',       // The value of the custom variable.  Required parameter.
                  1                 // Sets the scope to visitor-level.  Optional parameter.
             ]); 
        }
        
        */

        // Capture Software Downloads, PDF downloads and MP3's in Analytics
        $("a[href$='.exe'],a[href$='.pdf'],a[href$='.mp3']").click(function(){
            var filename = $(this).attr("href").split('/').pop();
            var filetype = $(this).attr("href").split('.').pop();
            _gaq.push(['_trackEvent', 'Downloads', filetype, filename]);
        });

        // Capture External Link Clicks 
        $(".extLink").click(function () {
            var extPage = $(this).attr("href");
            trackExternal(extPage);
        });
        
   
        // Capture Homepage Slider Clicks
        $("#curr-img").live('click',function () {
      		var clickItem = $(this).attr("src");
      		var currentLink = $(this).parent('a').attr("href");
      		 _gaq.push(['_trackEvent', 'Homepage Slider', clickItem, currentLink]);
    	
    		// Delay setting the location for one second
        	setTimeout(function() {window.location = currentLink}, 1000);
        	return false;
		  }); 
		  
		$(".inner-text a").live('click',function () {
      		var clickItem = $(this).text();
      		var currentLink = $(this).attr("href");
      		 _gaq.push(['_trackEvent', 'Homepage Slider', clickItem, currentLink]);
    		
    		// Delay setting the location for one second
        	setTimeout(function() {window.location = currentLink}, 1000);
        	return false;
		  });  

     
      
});

