/* 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 a").click(function(){

        var length = $(this).attr("href").length;

        var tab    = $(this).attr("href").charAt(length-1);

      	cp_activateTab(tab-1);

    	return false;

	});

	

	// Coverflow action

	cp_coverflow();

	

	// Green

	var greenActive = false;

	$("a.greenLink").click(function(){

		if(!greenActive){

			$(".tab1_green").slideDown("slow");

			sIFR.replace(header, {

		  		selector: '#p-rcb .tab1_green h2'

		  		,css: '.sIFR-root {color:#005c1f;font-size:36px}'

		  		,wmode: 'transparent'

		  	});

			greenActive = true;

		}else{

			$(".tab1_green").slideUp("slow");

			greenActive = false;

		}

		

	});

});





/* Functions

------------------------------------------------*/



// Applies sIFR to elements in current tab if not already applied



/* var header = {src: 'http://www.crsc.philips.com/crsc/images/sifr_gillsanslight_3.436.swf'} ;
sIFR.prefetch(header);
if(sIFR) sIFR.activate(header); */

function cp_init_sIFR(currentTab){

    if(typeof sIFR!='undefined'){ 



	sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' h2.green'

  		,css: '.sIFR-root {color:#005c1f;font-size:36px}'

  		,wmode: 'transparent'

  	});

	sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' h2'

  		,css: '.sIFR-root {color:#ffffff;font-size:36px}'

  		,wmode: 'transparent'

  	});



	sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' h3.green'

  		,css: '.sIFR-root {background-color:#FFFFFF;color:#5c005c;font-size:24px;}'

  		,wmode: 'transparent'

  	});

	sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' h3'

  		,css: '.sIFR-root {background-color:#FFFFFF;color:#5c005c;font-size:24px;}'

  		,wmode: 'transparent'

  	});
	
		sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' h4'

  		,css: '.sIFR-root {background-color:#FFFFFF;color:#5C005C;font-size:14px;}'

  		,wmode: 'transparent'

  	});

		sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' h1'

  		,css: '.sIFR-root {background-color:#FFFFFF;color:#5C005C;font-size:16px; font-weight:bold;}'

  		,wmode: 'transparent'

  	});


  	
  	sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' .tab1_quote'

  		,css: '.sIFR-root {background-color:#FFFFFF;color:#5C005C;font-size:14px;}'

  		,wmode: 'transparent'

  	});
  	sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' .tab3_lovezonestitle'

  		,css: '.sIFR-root {background-color:#FFFFFF;color:#5C005C;font-size:18px;}'

  		,wmode: 'transparent'

  	});
	 sIFR.replace(header, {

  		selector: '#p-rcb ' + currentTab + ' .tab2_kadertitle'

  		,css: '.sIFR-root {background-color:#FFFFFF;color:#FFFFFF;font-size:18px;}'

  		,wmode: 'transparent'

  	});

	}

}



/* 

 * 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;

    

	// set bg on navBar

	cp_setBgOnNavBar(value);

	

    // Change the header

    cp_setHeader(value);

    

    // ping statistics

    cp_sendStatistics(value);



	// fix ie6 png's

	if(client_ie6){

		fixNavPngs();

	}

}



/*

 * Changes the navbar bg

 *

 */



// set bg on navbar

function cp_setBgOnNavBar(value){

	var val = value +1;

	var bg = "url(/consumerfiles/pageitems/master/categorypages/Relationshipcare2009/assets/images/tab"+val+"_menubg.jpg)";

	$("#cp_tab_productdetails").css("background-image",bg);

}





/*

 * 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/Relationshipcare2009/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",

                allowfullscreen: "true"

            };

            var attributes = {};

            swfobject.embedSWF(src, "flash-inner-wrapper", "960", "274", "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 = {bandwidth : status }; 

            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";
	
	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;

}



function cp_coverflow(target){ 

    if (target == undefined) target = 0;

    $("#cp_tab_content_6.flash .block").hide();

    $("#cp_tab_content_6.flash .block:eq(" + target + ")").show();

    cp_init_sIFR("#cp_tab_content_6");

    return false;

}










/* Collapse/Expand for "Expert Advice" section */
	
	var expandedElement = null;
	
	$('h3.question').each(function () {
		this.collapseState = 0;	//Not visible
		this.collapseTarget = $(this).next();

	}).click(function () {
		if (this.collapseState)
		{
			this.collapseTarget.stop().slideUp();
			this.collapseState = false;
			$(this).removeClass('expanded');
			
			expandedElement = null;

		}
		else
		{
			if (expandedElement)
			{
				expandedElement.collapseTarget.stop().slideUp();
				expandedElement.collapseState = false;
				$(expandedElement).removeClass('expanded');
				
				expandedElement = null;
			}
			
			this.collapseTarget.stop().slideDown();
			this.collapseState = true;
			$(this).addClass('expanded');
			
			expandedElement = this;

		}

	});
	
