/* Initialize
------------------------------------------------*/
var __currentHeaderSRC;
var userRequestedTab;


/* DOM Loaded
------------------------------------------------*/

function cp_init() {
	
	// 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;
	  
	});
	
cp_setTab(userRequestedTab);
}


/* Functions
------------------------------------------------*/

function cp_init_sIFR(currentTab){
  if(typeof sIFR != 'undefined'){
    sIFR.replace(header,{
      selector:'#p-rcb ' + currentTab + ' h2',
      css:['.sIFR-root { font-size:24px; font-weight:normal;  color:#1266FF; text-align:left; width:300px; }'],
      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;
	
	// Change placeholder image
	var placeholderSrc = "url(/consumerfiles/pageitems/master/categorypages/PlayersRecorders/assets_lazy/images/videoPlayer_Tab" + (value + 1) +"_placeholder.jpg) no-repeat -2px 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"
      };
      var attributes = {};
    	swfobject.embedSWF(src, "flash-inner-wrapper", "956", "275", "9.0.0","expressInstall.swf", flashvars, params, attributes);
    }
  });
}


/*
 * 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_getMetrics(metric) {
  var content = $("meta[name='PHILIPS.METRICS."+metric+"']").attr("content");
  if (typeof content == 'undefined' || content == null)
      return '';
  else
      return content;
}

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";
      }
}

