/* Initialize

------------------------------------------------*/

var __currentHeaderSRC;

var userRequestedTab;





/* DOM Loaded

------------------------------------------------*/



$(document).ready(function () {



    // GET QUERYSTRING

    $.getQueryString();

    userRequestedTab = $.jget['tab'];

    for (var i = 0; i < universalTabNames.length; i++) { // find index from universal tab names

        if (universalTabNames[i] == userRequestedTab)

            userRequestedTab = i;

    }

    if (userRequestedTab == $.jget['tab'])

        userRequestedTab = 0;

    //sIFR needs a timeout for safari or sometimes sIFR won't behave correctly

    setTimeout("cp_setTab(" + userRequestedTab + ")", "10");



    // CHANGE TABS

    $("#cp_tab_productdetails > li").click(function () {
        var aHref = $(this).children("a").attr("href");
        var tab = aHref.charAt(aHref.length - 1);
        cp_activateTab(tab - 1);
    });

    $("#cp_tab_productdetails a").click(function () {
        var length = $(this).attr("href").length;
        var tab = $(this).attr("href").charAt(length - 1);
        cp_activateTab(tab - 1);
        return false;
    });
});

function openSensotouchTab2() {
	cp_activateTab(1);
}




/* Functions

------------------------------------------------*/



function cp_init_sIFR(currentTab){ // Applies sIFR to elements in current tab if not already applied
    //return;
	if(typeof sIFR != 'undefined'){

	    var header = { src: 'http://www.crsc.philips.com/crsc/images/sifr_gillsanslight_3.436.swf' };

	    sIFR.replace(header, {
	        selector: '#p-rcb ' + currentTab + ' h2'
            , css: '.sIFR-root {background-color:#FFFFFF;color:#FFFFFF;font-size:21pt;letter-spacing: +0.5;}'
            ,wmode: 'transparent'
	    });
		sIFR.replace(header, {
	        selector: 'h2.header-whitetabs'
            , css: '.sIFR-root {background-color:#FFFFFF;color:#00545C;font-size:23pt;letter-spacing: +0.5;}'
            ,wmode: 'transparent'
	    });
		
        sIFR.replace(header, {
            selector: '#cp_tab_productdetails li span'
            , css: '.sIFR-root {text-align: center; background-color:#FFFFFF;color:#d2d7e5;font-size:10pt;letter-spacing: +0.5;}, a:link { color:#d2d7e5; text-decoration: none; }, a:hover { color:#d2d7e5; text-decoration: none; }, a:visited { color:#d2d7e5; text-decoration: none; }, a:active { color:#d2d7e5; text-decoration: none; }'
            , wmode: 'transparent'
        });

  	    //alert(currentTab);
	    if (currentTab == '#cp_tab_content_1') {
	        sIFR.replace(header, {
	            selector: '#p-rcb .SensoContent'
                , css: '.sIFR-root {background-color:#FFFFFF;color:#d2d7e5;font-size:14pt;letter-spacing: +0.5;}'
                , wmode: 'transparent'
	        });
  	        sIFR.replace(header, {
  	            selector: '#p-rcb .SensoLinkText1'
                , css: '.sIFR-root {background-color:#FFFFFF;color:#cefdfe;font-size:12pt;letter-spacing: +0.5;}, a:link { color:#cefdfe; text-decoration: none; }, a:hover { color:#cefdfe; text-decoration: none; }, a:visited { color:#cefdfe; text-decoration: none; }, a:active { color:#cefdfe; text-decoration: none; }'
                , wmode: 'transparent'
  	        });
			
  	        sIFR.replace(header, {
  	            selector: '#p-rcb .SensoLinkText2 span'
                , css: '.sIFR-root {background-color:#FFFFFF;color:#FFFFFF;font-size:12pt;letter-spacing: +0.5;}, a:link { color:#FFFFFF; text-decoration: none; }, a:hover { color:#FFFFFF; text-decoration: none; }, a:visited { color:#FFFFFF; text-decoration: none; }, a:active { color:#FFFFFF; text-decoration: none; }'
                , wmode: 'transparent'
  	        });
  	    }

  	    if (currentTab == '#cp_tab_content_2') {
  	        sIFR.replace(header, {
  	            selector: '#p-rcb .SensoContent2'
                , css: '.sIFR-root {background-color:#FFFFFF;color:#FFFFFF;font-size:14pt;letter-spacing: +0.5;}'
                , wmode: 'transparent'
  	        });
  	        sIFR.replace(header, {
  	            selector: '#p-rcb .SensoContent3'
                , css: '.sIFR-root {background-color:#FFFFFF;color:#4a6487;font-size:14pt;letter-spacing: +0.5;}'
                , wmode: 'transparent'
  	        });
  	        sIFR.replace(header, {
  	            selector: '#p-rcb .SensoLinkText3'
                , css: '.sIFR-root {background-color:#FFFFFF;color:#FFFFFF;font-size:14pt;letter-spacing: +0.5;}, a:link { color:#FFFFFF; text-decoration: none; }, a:hover { color:#FFFFFF; text-decoration: none; }, a:visited { color:#FFFFFF; text-decoration: none; }, a:active { color:#FFFFFF; text-decoration: none; }'
                , wmode: 'transparent'
  	        });
  	        sIFR.replace(header, {
  	            selector: '#p-rcb .SensoLinkText4'
                , css: '.sIFR-root {background-color:#FFFFFF;color:#FFFFFF;font-size:12pt;letter-spacing: +0.5;}, a:link { color:#FFFFFF; text-decoration: none; }, a:hover { color:#FFFFFF; text-decoration: none; }, a:visited { color:#FFFFFF; text-decoration: none; }, a:active { color:#FFFFFF; text-decoration: none; }'
                , wmode: 'transparent'
  	        });
  	    }
  	    
		
		// WIDTH spacer link images
		$("SensoLinkText2 a img").css('width', $("#SensoLinkText2 object").width())
								.css('height', $("#SensoLinkText2 object").height());
		
	}

}





/* 

 * Wrapper function for activating a tab.

 */

function cp_setTab(value) {



  if (value == "undefined")

    value = 0;

  if (!parseInt(value))

    value = 0;

  if (value >= $('#p-rcb #cp_wrap_tab_productdetails li').length)

    value = 0;

  if (__currentTabIndex == value)

    return;

    

  $('li#cp_tab_' + (value + 1) + ' a').click();

  

  return false;

  

}



// <TABS LOGIC>

var __currentTabIndex;

/*

 * show a tab and hides others

 *

 * @var integer or string, the index of the availableTabs global or a string which must be present in availableTabs

 */

function cp_activateTab(value) {



		// Hide all

    for (var i = 0; i < $('#p-rcb #cp_wrap_tab_productdetails li').length; i++) {

        var content_tab = '#cp_tab_content_'+(i+1);

        if (i == value) {

            // First tab

            if ((value + 1) == 1) {

                $('#cp_tab_'+(i+1)).addClass('cp_active_firstTab'); // extra class needed because IE6 doesn't fully support multiple class chains

            }

            // Last tab

            if ((value + 1) == $('#p-rcb #cp_wrap_tab_productdetails li').length){

                $('#cp_tab_'+(i+1)).addClass('cp_active_lastTab');

            }

            $('#cp_tab_'+(i+1)).addClass('cp_active');

            $('#cp_tab_'+(i+1)).prev().addClass('cp_active_leftSibling');

            $('#cp_tab_'+(i+1)).next().addClass('cp_active_rightSibling');

            $('#cp_tab_'+(i+1)).removeClass('cp_inactive');

            $(content_tab).show();

            // initialise the sIFR within this tab

            cp_init_sIFR(content_tab);

        } else {

            $('#cp_tab_'+(i+1)).addClass('cp_inactive');

            $('#cp_tab_'+(i+1)).removeClass('cp_active');

            $('#cp_tab_'+(i+1)).removeClass('cp_active_firstTab');

            $('#cp_tab_'+(i+1)).removeClass('cp_active_lastTab');

            $('#cp_tab_'+(i+1)).prev().removeClass('cp_active_leftSibling');

            $('#cp_tab_'+(i+1)).next().removeClass('cp_active_rightSibling');

            $(content_tab).hide();

        }

    }

    // remember last set index

    __currentTabIndex = value;

    

    // Change the header

    cp_setHeader(value);

    

    // ping statistics

    cp_sendStatistics(value);

    

}



/*

 * Changes the header swf

 *

 * @var integer, the index of the availableHeadersSRC global

 */



function cp_setHeader(value) {

	

	if (typeof availableHeadersSRC[value] == undefined)

		return false;



	var src = availableHeadersSRC[value];

	if (src == __currentHeaderSRC)

		return false;



	__currentHeaderSRC = src;

	

	// Change placeholder image

	var placeholderSrc = "url(/consumerfiles/pageitems/master/categorypages/Shavers2010/assets/images/videoPlayer_Tab" + (value + 1) +"_placeholder.jpg) no-repeat 0px 0px";

	$("#flashcontent_header").css("background", placeholderSrc);

	

	// SWFObject 2

	$.testBandwidth(function (status) {
	    
	    if (status == "medium" || status == "high" || status == "vhigh") {

	        var flashvars = {

	            bandwidth: status

	        };

	        var params = {
	            menu: "false",
	            wmode: "transparent",
                allowScriptAccess: "true"
	        };

	        var attributes = {};
			
			var width = "960", height = 0;
			if (value == 0 || value == 1)
			{
				height = "304";
				if (value == 0)
				{
					$("#p-rcb").css("background-color", "#445d73");
					$("#p-rcb").css("background-image", "url('/consumerfiles/pageitems/master/categorypages/Shavers2010/assets/images/sensotouch/bg.jpg')");
				}
				else
				{
					$("#p-rcb").css("background-color", "#445d73");
					$("#p-rcb").css("background-image", "url('/consumerfiles/pageitems/master/categorypages/Shavers2010/assets/images/sensotouch/bg2.jpg')");
				}
			}
			else
			{
				height = "290";
				$("#p-rcb").css("background-color", "#FFFFFF");
				$("#p-rcb").css("background-image", "");
			}
			//alert(height);
			//height = "290";
			$("#flashcontent_header").css('height', height+'px');
			//alert('swfobject.embedSWF value: ' + value);
			//src = '/consumerfiles/pageitems/master/categorypages/Shavers2010/assets/flash/test.swf';
	        swfobject.embedSWF(src, "flash-inner-wrapper", width, height, "9.0.0", "expressInstall.swf", flashvars, params, attributes);

	    }

	});

}

function cp_setOverlayHeader(pathToSwf){

	// SWFObject 2

	// console.log(pathToSwf);



	$("#flash-overlay-wrapper").show();

	$.testBandwidth(function(status){

        if (status == "medium" || status == "high" || status == "vhigh") {

            var flashvars = {};

            var params = {

                menu: "false",

                wmode: "transparent",

				allowScriptAccess: "true",

                allowfullscreen: "true"

            };

            var attributes = {};

            swfobject.embedSWF(pathToSwf, "flash-overlay", "960", "550", "9.0.0","expressInstall.swf", flashvars, params, attributes);

        }

    });

	//return true;

}

function cp_closeOverlayHeader(){

	$("#flash-overlay-wrapper").html("");

	$("#flash-overlay-wrapper").append("<div id=\"flash-overlay\"></div>");

	$("#flash-overlay-wrapper").hide();

}


/*

 * DIV POPUP

 */

 //SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(id){
	centerPopup(id);
	//loads popup only if it is disabled
	if(popupStatus==0){
		/*$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");*/
		$(id).fadeIn("slow");
		popupStatus = 1;
	}
}

//disabling popup with jQuery magic!
function disablePopup(id){
	//disables popup only if it is enabled
	//if(popupStatus==1){
		//$("#backgroundPopup").fadeOut("slow");
		$(id).fadeOut("slow");
		popupStatus = 0;
	//}
}

//centering popup
function centerPopup(id){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $(id).height();
	var popupWidth = $(id).width();
	//centering
	$(id).css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2 + $(window).scrollTop(),
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	/*$("#backgroundPopup").css({
		"height": windowHeight
	});*/
	
}


function showCenteredOverlay(div){
	
	var d = document.getElementById(div);
	
	var divheight = 0;
	var divwidth = 0;
	if(d.offsetHeight) { divheight = d.offsetHeight; }
	else if(d.style.pixelHeight) { divheight = d.style.pixelHeight; }
	
	if(d.offsetWidth) { divwidth = d.offsetWidth; }
	else if(d.style.pixelWidth) { divheight = d.style.pixelWidth; }
	
	
	
	d.style.left = ($(document).width()/2) -  (divwidth/2);
	d.style.top = ($(document).height()/2) -  (divheight/2);
}

//function showOverlay(element, div, left, top, text)
 
function showOverlay(element, div, left, top)

{

	var e = document.getElementById(element);

	var d = document.getElementById(div);

	//var t = document.getElementById('overlay_text');

	

	d.style.display = '';

	//t.innerHTML = text;

	

	var divheight = 0;

	if(d.offsetHeight) { divheight = d.offsetHeight; }

	else if(d.style.pixelHeight) { divheight = d.style.pixelHeight; }



	//left 18 top 50

	//d.style.left = (findPosX(e) - (-left)) + "px";
	//d.style.top = (findPosY(e) - (-top) - divheight) + "px";
	
	d.style.left = "18px";
	d.style.top = (findPosY(e) - (-top) - divheight-100) + "px"; 
	
	return false;
}



function hideMe(div)

{
	
	var d = document.getElementById(div);

	//d.style.display = 'none';
	disablePopup(d);
}



function findPosX(obj)

{

    var curleft = 0;

    if(obj.offsetParent)

        while(1) 

        {

          curleft += obj.offsetLeft;

          if(!obj.offsetParent)

            break;

          obj = obj.offsetParent;

        }

    else if(obj.x)

        curleft += obj.x;

    return curleft;

}



function findPosY(obj)

{

  var curtop = 0;

  if(obj.offsetParent)

      while(1)

      {

        curtop += obj.offsetTop;

        if(!obj.offsetParent)

          break;

        obj = obj.offsetParent;

      }

  else if(obj.y)

      curtop += obj.y;

  return curtop;

}



/*

 * Bandwidth detection

 */

(function($){

  $.bandwidth = null;

  $.bandwidthTestEndpoint = 'http://test.philips.com/esi/getbw_js_tpi.esi';

  $.testBandwidth = function(cb){

    if ($.bandwidth) {

      cb($.bandwidth);

    } else {

      $.onBandwidthTested = cb;

      $.getScript($.bandwidthTestEndpoint);

    }

  }

})(jQuery);





/**

 * jget plugin

 * @author Alexandre Magno

 * @desc get a query string to be accessible for javascript

 * @version 1.0

 * @example

 *

 * http://www.foo.com/test.php?var1=test1

 * var outputQuery = $.jget['var1'];

 * $.debug(outputQuery);

 * //Will show 'test1'

 *

 *

 * @license free

 * @param bool vertical, bool horizontal

 * @site http://blog.alexandremagno.net

 *

 */



jQuery.extend({



	//starting the jget object

	jget: {},

	//get the url

	url: window.location.href.replace(/^[^\?]+\??/,''),

	//get the queryString

	parseQuery: function ( query ) {

	   var Params = {};

	   if ( ! query ) {return Params;}// return empty object

	   var Pairs = query.split(/[;&]/);

	   for ( var i = 0; i < Pairs.length; i++ ) {

	      var KeyVal = Pairs[i].split('=');

	      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}

	      var key = unescape( KeyVal[0] );

	      var val = unescape( KeyVal[1] );

	      val = val.replace(/\+/g, ' ');

	      Params[key] = val;

	   }

	   return Params;

	},

	//Make the jget object available to jQuery.extend

	getQueryString: function() {

		this.jget = this.parseQuery(this.url);

	}



});





/*

 * Send statictics when the user interacts with the tabs.

 */

var __statsHaveNotBeenSendViaTabInteraction = true;

function cp_sendStatistics(value) {

    if (typeof s != 'object')

        return;



    // normalize tab values;

    if (typeof universalTabNames[value] != 'undefined')

        value = universalTabNames[value];

    else

        value = "TAB" + value;

        

    if (!__statsHaveNotBeenSendViaTabInteraction) {

	    var PRODUCTSUBCATEGORY = cp_getMetrics('PRODUCTSUBCATEGORY');

	    var DIVISION = cp_getMetrics('DIVISION');

	    var SECTION = cp_getMetrics('SECTION');

	    var CATALOGTYPE = cp_getMetrics('CATALOGTYPE');

	    var PRODUCTGROUP = cp_getMetrics('PRODUCTGROUP');

	    var PRODUCTCATEGORY = cp_getMetrics('PRODUCTCATEGORY');

	    

        if (PRODUCTSUBCATEGORY != "") {

            var TABSECTION = PRODUCTSUBCATEGORY + '_' + value;

            s.pageName = DIVISION + ":" + SECTION + ":" + TABSECTION + ":" + CATALOGTYPE;

        } else if (PRODUCTCATEGORY != "") {

            var TABSECTION = PRODUCTCATEGORY + '_' + value;

            s.pageName = DIVISION + ":" + SECTION + ":" + TABSECTION + ":" + CATALOGTYPE;

        }

        s.t();

    }

	__statsHaveNotBeenSendViaTabInteraction = false;

}



function cp_getMetrics(metric) {

    var content = $("meta[name='PHILIPS.METRICS."+metric+"']").attr("content");

    if (typeof content == 'undefined' || content == null)

        return '';

    else

        return content;

    

}

