/* 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;
	  
	});
	
});


/* 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'
  		,css: '.sIFR-root {background-color:#FFFFFF;color:#ffffff;font-size:24px}'
  		,wmode: 'transparent'
		,filters: {
		Glow: {
		knockout:false
		,strength: 1.5
		,quality: 3
		,color: '#138796'
		,distance: 4
		}
		}
  	});

	sIFR.replace(header, {
  		selector: '#p-rcb ' + currentTab + ' h3'
  		,css: '.sIFR-root {background-color:#FFFFFF;color:#ffffff;font-size:20px;}'
  		,wmode: 'transparent'
		,filters: {
		Glow: {
		knockout:false
		,strength: 1.5
		,quality: 3
		,color: '#138796'
		,distance: 4
		}
		}
  	});

  	sIFR.replace(header, {
  		selector: '#p-rcb ' + currentTab + ' h4'
  		,css: '.sIFR-root {background-color:#FFFFFF;color:#ffffff;font-size:20px;}'
  		,wmode: 'transparent'
		,filters: {
		Glow: {
		knockout:false
		,strength: 1.5
		,quality: 3
		,color: '#138796'
		,distance: 4
		}
		}
  	});

  	sIFR.replace(header, {
  		selector: '#p-rcb ' + currentTab + ' h5'
  		,css: '.sIFR-root {letter-spacing: 2; color:#a2c743;font-size:22px; text-align: left;}'
  		,wmode: 'transparent'
		,filters: {
		Glow: {
		knockout:false
		,strength: 1.5
		,quality: 3
		,color: '#138796'
		,distance: 4
		}
		}
  	});

  	sIFR.replace(header, {
  		selector: '#p-rcb ' + currentTab + ' h6'
  		,css: '.sIFR-root {background-color:#FFFFFF;color:#138796;font-size:22px;}'
  		,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;
    
    // 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;
	
	var headerHeight = "275";
	
	if(value == 0) {
		headerHeight = "275";
	}
	
	if(value!=0) {	
		// Change placeholder image
		var placeholderSrc = "url(/consumerfiles/pageitems/master/categorypages/FlatTV2009/assets_update/images/videoPlayer_Tab" + (value + 1) +"_placeholder.jpg) no-repeat 0px 0px";
		$("#flashcontent_header").css("background", placeholderSrc);
	}
	
	
	// SWFObject 2
	$.testBandwidth(function(status){

	var __DIVISIONFLASH = cp_getMetrics('DIVISION');
	if(!__DIVISIONFLASH) __DIVISIONFLASH = "CP";
	
	var __SECTIONFLASH = cp_getMetrics('SECTION');
	if(!__SECTIONFLASH) __SECTIONFLASH = "CP:main";
		
	var __COUNTRYFLASH = cp_getMetrics('COUNTRY');
	if(!__COUNTRYFLASH) __COUNTRYFLASH = "gb";
	
	var __LANGUAGEFLASH = cp_getMetrics('LANGUAGE');
	if(!__LANGUAGEFLASH) __LANGUAGEFLASH = "en";
		
	var __COUNTRY = __COUNTRYFLASH.toUpperCase();
	
	var locale = __LANGUAGEFLASH + '-' + __COUNTRYFLASH;
	var tld = __COUNTRYFLASH == "gb" ? "co.uk" : __COUNTRYFLASH;
	
		
	if(value==0) {	
		// Change placeholder image
		if(status == "low") {
			var placeholderSrc = "url(/consumerfiles/consumerfiles/pageitems/master/categorypages/FlatTV2009/assets_update/images/videoPlayer_Tab1_placeholder_"+ status+"_"+__LANGUAGEFLASH+".jpg) no-repeat 0px 0px";
			$("#flashcontent_header").html("<a href='?tab=cinema 21:9' target='' class='lowcta'></a>");
		}
		else {
			var placeholderSrc = "url(/consumerfiles/consumerfiles/pageitems/master/categorypages/FlatTV2009/assets_update/images/videoPlayer_Tab1_placeholder.jpg) no-repeat 0px 0px";			
		}
		$("#flashcontent_header").css("background", placeholderSrc);
	}
		
    if (status == "medium" || status == "high" || status == "vhigh") {
	
      var flashvars = {	
	      s_division: __DIVISIONFLASH,
	      s_section: __SECTIONFLASH,  
		  s_country:  __COUNTRYFLASH,    
		  s_language: __LANGUAGEFLASH,
		  locale: locale,
		  bandwidth: status  
      };
      
      var params = {
        menu: "false",
        wmode: "transparent",
		allowFullScreen: "true",
		allowScriptAccess: "always",
		scale:"noScale"
      };
      
      if(value==0) {
      	flashvars['s_section'] = "CP:cinema";
      	flashvars['basePath'] = "/consumerfiles/pageitems/master/categorypages/FlatTV2009/assets_update/flash/tab1/" ;
      	
      	if(cp_getMetrics('COUNTRY')) {
			flashvars['xmlPath'] = "/consumerfiles/pageitems/locales/" + __LANGUAGEFLASH + "_" + __COUNTRY + "/CONSUMER/categorypages/FlatTV2009/assets_update/flash/xml/config.xml?";
		}
		else {
			flashvars['xmlPath'] = "/consumerfiles/pageitems/master/categorypages/FlatTV2009/assets_update/flash/xml/config.xml??";
		}
      }
      
      if(value==1) {
      	flashvars['s_section'] = "CP:cinema21_9_banner";
      }
      if(value==4) {
      	flashvars['s_section'] = "CP:net_tv";
      }
      
      var attributes = {};
      
      cp_flattv_ambilight_resize(275);
      
      swfobject.embedSWF(src, "flash-inner-wrapper", "960", headerHeight, "9.0.0","expressInstall.swf", flashvars, params, attributes);
      
      if(value==0) {
    	/*cp_flattv_overview_initoverlay();*/
      }
    }
  });
}


/*
 * DIV POPUP
 */

//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 = "18px"; //(findPosX(e) - (-left)) + "px";
	d.style.top = (findPosY(e) - (-top) - divheight-100) + "px";
}

function hideMe(div)
{
	var d = document.getElementById(div);
	d.style.display = 'none';
}

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_flattv_ambilight_deeplink(modelno) {
 $("#flash-inner-wrapper").get(0).deeplink("42PFL" + modelno);
}

function cp_getMetrics(metric) {
  var content = $("meta[name='PHILIPS.METRICS."+metric+"']").attr("content");
  if (typeof content == 'undefined' || content == null)
      return '';
  else
      return content;
}

$("#flash-inner-wrapper").wrap('<div id="flash-wrapper"></div>');

function cp_flattv_overview_initoverlay() {
	$("#flashcontent_header, #flash-wrapper, #flash-inner-wrapper").removeClass("docked").addClass("overlay");
}
	
function cp_flattv_overview_dockoverlay() {
	$("#flashcontent_header, #flash-wrapper, #flash-inner-wrapper").removeClass("overlay").addClass("docked");
}


function cp_flattv_ambilight_resize(h) {
	$("#flash-inner-wrapper").css("height", h + "px");
	$("#flashcontent_header").css("height", h + "px");
	$("#flashcontent_header").css("background-color", "#000000");
}


/*
function flattv__resize(h) {
	$("#flash-inner-wrapper").css("height", h + "px");
	$("#flashcontent_header").css("height", h + "px");
	$("#flashcontent_header").css("background-color", "#000000");
}
*/
function ayftOnBeforeBodyOpen(id) {
      var elFlash = document.getElementById('flash-inner-wrapper');
      if (elFlash) {
            elFlash.style.display = "none";
      }
}

function ayftOnBodyClose(id) {
      var elFlash = document.getElementById('flash-inner-wrapper');
      if (elFlash) {
            elFlash.style.display = "block";
      }
}




