/* 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(){
	    /* Close header overlay*/
	    cp_closeOverlayHeader();
	    
        var length = $(this).attr("href").length;
        var tab    = $(this).attr("href").charAt(length-1);
      	cp_activateTab(tab-1);
    	return false;
	});
	
	// Coverflow action
	cp_coverflow();
	
	// Phones
	var activePhone = 1;
	$("ul.phones a.phone, a.greenLink").each(function(){
		$(this).attr("href","javascript:;");
	});
	$("ul.phones li.inactive a.phone").fadeTo("fast", 0.5);
	
	var phoneSliding = false;
	$("ul.phones a.phone").hover(
		function(){
			if($(this).attr('rel').replace("item","")!=activePhone){
				$(this).fadeTo("fast", 1);
			}
			var selectedPhone = $(this).attr('rel').replace("item","");
			if(selectedPhone!=activePhone && !phoneSliding){
				phoneSliding = true;
				var maxWidth = $(this).parent().width()+280;
				var minWidth = $("ul.phones li.item"+activePhone).width()-280;
				$("ul.phones li.item"+activePhone+" a.phone").fadeTo("fast", 0.5);
				$("ul.phones li.item"+activePhone+" .description").hide();
				$("ul.phones li.item"+activePhone).animate({width: minWidth+"px", duration:400},"easeout",function(){phoneSliding = false;});
				$("ul.phones li.item"+selectedPhone).animate({width: maxWidth+"px", duration:400 },"easeout");
				$("ul.phones li.item"+selectedPhone+" a.phone").fadeTo("fast", 1);
				$("ul.phones li.item"+selectedPhone+" .description").show();
				activePhone = selectedPhone;
			}
		},
		function(){
			if($(this).attr('rel').replace("item","")!=activePhone){
				$(this).fadeTo("fast", 0.5);
			}
		}
	);
	
	$("ul.phones  a.phone").click(function(){
		
	});
	
	// 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:#005c1f;font-size:24px;}'
  		,wmode: 'transparent'
  	});
	sIFR.replace(header, {
  		selector: '#p-rcb ' + currentTab + ' h3'
  		,css: '.sIFR-root {background-color:#FFFFFF;color:#fff;font-size:24px;}'
  		,wmode: 'transparent'
  	});

  	
  	sIFR.replace(header, {
  		selector: '#p-rcb ' + currentTab + ' .title'
  		,css: '.sIFR-root {background-color:#FFFFFF;color:#ffffff;font-size:30px}'
  		,wmode: 'transparent'
		,filters: {
		Glow: {
		knockout:false
		,strength: 1.5
		,quality: 3
		,color: '#138796'
		,distance: 4
		}
		}
  	});
	}
}

/* 
 * 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/landlinephones/assets/images/tab"+val+"_bg.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/locales/en_US/CONSUMER/categorypages/landlinephones/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 = {};
            var params = {
                menu: "false",
                wmode: "transparent",
				allowScriptAccess: "true",
                allowfullscreen: "true"
            };
            var attributes = {};
            swfobject.embedSWF(src, "flash-inner-wrapper", "960", "314", "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
 */

//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"; (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 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;
}