var $jq = jQuery.noConflict();
var jQuery132 = jQuery.noConflict();

var hp_timeouts = new Array();

var detectFlash = function() {
    if(swfobject.hasFlashPlayerVersion("1")) {
        return true;
    } else {
        return false;
    }
}

var ismobile=navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i);

var slideshow = function() {
    var $slideshow = jQuery('#slideshow');
	$slideshow.show();
    $slideshow.cycle({
        fx: 'fade',
        timeoutFn: calculateTimeout,
        pager: '.slidepager',
		prev:   '.prevBanner', 
		next:   '.nextBanner', 
        pagerAnchorBuilder: function(index, dom) {
            return '<li><a href="#"></a></li>';
        },
        before: function() {
            var bg = jQuery(this).attr("bg");
			var bgCss = jQuery(this).attr("bgCss");
			jQuery("#BaseBgDiv").css("background","url("+bg+") "+bgCss).css('min-height','750px');
			jQuery('html').append('<img style="display:none" id="bgImgHeight" src="'+bg+'" />');
       		if(jQuery.browser.msie){
				var flashsrc = jQuery(this).attr('flashsrc');
				jQuery('#slideshow .banner').each(function(index){
					if(jQuery(this).is(':visible')){
						jQuery(this).find('.flashBannerContainer:visible').children('object').remove();
						jQuery(this).find('.flashBannerContainer:visible').append("<img src='/HP/images/sonysupport/loading.gif' style='padding-top:140px; padding-left:430px; padding-right:430px' />");
					}
				});
			}
		},
		after: function(){
			var bgHeight = jQuery('#bgImgHeight').height();
			var pageHeight = jQuery(document).height();
			var bgCSSHeight;
			if(bgHeight<=pageHeight){
				bgCSSHeight=bgHeight;
			}else{
				bgCSSHeight=pageHeight;
			}
			jQuery("#BaseBgDiv").css("min-height",bgCSSHeight+"px");
			setTimeout(function(){
				jQuery('#bgImgHeight').remove();
			},1000);
			if(jQuery.browser.msie){
				var flashsrc = jQuery(this).attr('flashsrc');
				jQuery('#slideshow .banner').each(function(index){
					if(jQuery(this).is(':visible')){
						//console.log(index+'\n'+flashsrc);
						//jQuery(this).find('.flashBannerContainer:visible').children('object').remove();
						jQuery(this).find('.flashBannerContainer:visible').flash({
							swf: flashsrc,
							width: 931,
							height: 310,
							wmode: 'transparent',
							scale: 'noborder',
							allowScriptAccess: 'always'
						});
					}
				});
			}
		}
    });
};

var newsTicker = function() {
    var $newsTicker = jQuery('.newsTicker');
    $newsTicker.cycle({
        fx:     'scrollVert',
        next:   '#btnDown',
        prev:   '#btnUp',
		width:	540,
		height:	15,
		//fit:	1,
        pause:  1
	});

    // If only one li in newsticker, hide the top/down buttons
    if ( $newsTicker.children('li').length ==1) {
        jQuery('#newsTickerBtns').css('display','none');
    }
};

var listing = function() {
	jQuery(".listing ul li img").hover(function() {
			jQuery(this).css("position","relative").stop().animate({ top: "-15px" }, 300);
		},function(){
			jQuery(this).css("position","relative").stop().animate({ top: "0px"}, 300);
	});
};

var useragent = navigator.userAgent;
//alert(useragent);

function calculateTimeout(currElement, nextElement, opts, isForward) { 
    var index = opts.currSlide; 
    return hp_timeouts[index] * 1000; 
}

function getNodeValue(e, n) {
	return jQuery(e).find('*').filter(function() {
	
		if (this.nodeName == n)
			return true;
		return false;
	}).text();
}

function parseXML(xmlFile){
	
    if (window.ActiveXObject) {
		//IE	
        var doc = new ActiveXObject('Microsoft.XMLDOM');
		doc.async = false;
        doc.loadXML(xmlFile);
        return doc;
    } else if (window.DOMParser) {
		return (new window.DOMParser).parseFromString(xmlFile, 'text/xml');
    } else {		
		return xmlFile;
	}
}

function getFileExtension(filename) {
	return filename.split('.').pop();
}

jQuery(document).ready(function(){

	var hasFlash = detectFlash();
	var locale='';
	var logicalPage='';
	jQuery('meta').each(function(){
		if(jQuery(this).attr('name')=='locale'){
			locale = jQuery(this).attr('content');
		}
		if(jQuery(this).attr('name')=='logicalPage'){
			logicalPage = jQuery(this).attr('content');
		}
	});
	
	if(logicalPage=='HPTopLandingPage'){
		var siteParam = document.getElementById('siteParam').value;
		jQuery.ajax({
			type: "GET",
			url: "/rss/coverstoryflash.rss?site="+siteParam, //RSS file and path for Top Page Carousel Banners
			dataType: (jQuery.browser.msie) ? "text" : "text",
			contentType : 'application/rss+xml',
			success: function(data) {
	
				var xml = (jQuery.browser.msie) ? parseXML(data) : parseXML(data);
				
				var results = "";
	
				jQuery(xml).find('item').each(function() {		
				
					var banner = getNodeValue(this,'sony:banner');
					var bannerType = getNodeValue(this,'sony:bannerType');
					var isInteractive = eval(getNodeValue(this, 'sony:allowInteraction'));
					var isSwf = ( getFileExtension(banner) == "swf" ) ? true : false;
					var dcqPos = getNodeValue(this,'sony:dcqPosition');
					var dcqTitle = getNodeValue(this,'sony:title');
					
					if(bannerType!='Small Banner'){
						results +=	"<div bg='" + getNodeValue(this,'sony:htmlBgImage') + "' bgCss='"+ getNodeValue(this,'sony:cssRule') +"' flashsrc='" + banner + "' class='banner' style='background-color:#fff'>\n";
		
						if ( !isInteractive ) {
								results +=	"	<a href='" + getNodeValue(this,'sony:url') + "' target='" + getNodeValue(this,'sony:target') + "' class='slide-container-link' dcqpos='"+dcqPos+"' dcqtitle='"+dcqTitle+"' >\n";
						}
						
						if ( isSwf && hasFlash ) {
							results += 	"		<div class='hasFlash'>\n"
						}
						
						if ( !isInteractive && isSwf && hasFlash ) {			
							results +=	"			<img alt='' style='position:absolute' src='/HP/images/common/spacer.gif' width='930' height='310' />\n"
						}			
						
						if ( isSwf && hasFlash ) {
							if(jQuery.browser.msie){
								results +=	"			<div class='flashBannerContainer'>\n"
										+	"			<img src='/HP/images/sonysupport/loading.gif' style='padding-top:140px; padding-left:430px' /></div>\n"
										+	"		</div>\n";
							}else{
								results +=	"			<div class='flashBannerContainer'>\n"
										+	"			<object width='930' height='310' id='flashBanner'>\n"
										+	"				<param value='" + banner + "' name='movie'>\n"
										+	"				<param value='transparent' name='wmode'>\n"
										+	"				<param value='high' name='quality'>\n"
										+	"				<param value='noborder' name='scale'>\n"
										+	"				<param value='#fff' name='bgcolor'>\n"
										+	"				<param value='always' name='allowScriptAccess'>\n"
										+	"				<embed width='930' height='310' allowScriptAccess='always' wmode='transparent' scale='noborder' quality='high' name='flashBanner' src='" + banner + "'>\n"
										+	"			</object>\n"
										+	"			</div>\n"
										+	"		</div>\n";
							}
						} else {
							results	+=	"		<div class='noFlash'>\n"
									+	"			<img width='930' height='310' alt='"+dcqTitle+"' title='"+dcqTitle+"' src='" + ((isSwf && !hasFlash) ? getNodeValue(this,'sony:alternateImage') : banner) + "' class='banner-img' />\n"
									+	"		</div>\n";
						}
						
						if ( !isInteractive ) {
							results += 	"	</a>\n";
						}
						results += 	"	<div class='control'>\n"
								+	"		<ul class='slidepager'></ul>\n"
								+	"	</div>\n"
								+	"</div>\n";
						
						hp_timeouts.push(getNodeValue(this,'sony:duration'));
					}
				});
	
				jQuery('#slideshow').html(results);
				slideshow(hp_timeouts);
			
				// Omniture tracking
				jQuery('.slide-container-link').click(function(){
					var dcqpos = jQuery(this).attr('dcqpos');
					var dcqtitle = jQuery(this).attr('dcqtitle');
					trackHomeCSF_MainBanner(dcqpos,dcqtitle);
				});
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("XMLHttpRequest="+XMLHttpRequest+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
				 
			}
	
		});
	
		jQuery.ajax({
			type: "GET",
			url: "/rss/producthighlightsflash.rss?site="+siteParam, //RSS path and file for the Product Grid Listing
			dataType: (jQuery.browser.msie) ? "text" : "text",
			contentType : 'application/rss+xml',
			success: function(data) {
				var xml = (jQuery.browser.msie) ? parseXML(data) :parseXML(data);
				var results = "";
				jQuery(xml).find('item').each(function() {
					swf = getNodeValue(this,'sony:banner');
					var dcqPos = getNodeValue(this,'sony:dcqPosition');
					var dcqTitle = getNodeValue(this,'sony:brandTitle');
					
					results +=	"<li>\n"
							+	"	<a class='grid-container-link' href='" + getNodeValue(this,'sony:url') + "' target='" + getNodeValue(this,'sony:target') + "' dcqpos='"+dcqPos+"' dcqtitle='"+dcqTitle+"'>\n"
							+	"		<img alt='"+dcqTitle+"' title='"+dcqTitle+"' src='" + getNodeValue(this,'sony:zoomInFile') + "' class='banner-img'>\n"
							+	"		<strong>" + getNodeValue(this,'sony:brandTitle') + "</strong>\n"
							+	"	</a>\n"
							+	"</li>\n";
				});
				jQuery('div.listing ul').html(results);
	
				listing();
	
				// Omniture tracking
				jQuery('.grid-container-link').click(function(){
					var dcqpos = jQuery(this).attr('dcqpos');
					var dcqtitle = jQuery(this).attr('dcqtitle');
					trackHomePHF_Visit(dcqpos,dcqtitle);
				});
			}
		});
	}
	
	setTimeout(function(){
		// force max width to 210px
		//jQuery('#marketing .item').each(function(){
		//	if(jQuery(this).children('a').children('img').width()>210){
		//		jQuery(this).children('a').children('img').width(210);
		//	}
		//});
	
		//IE7 fix for overflow
		if(jQuery.browser.msie && jQuery.browser.version <=7){
			jQuery('#marketing .item').each(function(){
				var titleHeight = jQuery(this).children('.title').height();
				var imgHeight = jQuery(this).children('a').children('img').height();
				jQuery(this).children('.content').height(290-(titleHeight+imgHeight));
			});
		}
	},2000);
	

    newsTicker();

	adjustHeight('#marketing .marketingTop', '.title', true);
	adjustHeight('#marketing .marketingBottom', '.title', true);
	adjustHeight('#marketing-alternative', '.title', true);
	adjustHeight('#marketing .marketingTop', '.title-link', false);
	adjustHeight('#marketing .marketingBottom', '.title-link', false);
	adjustHeight('#marketing-alternative', '.title-link', false);
	
	setTimeout(function(){
		var newsLabelWidth = jQuery('.news .label').width();
		jQuery('.news .desc').width(679-newsLabelWidth);
		
		if(locale=="ar_ME" || locale=="fa_IR"){
			jQuery('.news .desc').width(678-newsLabelWidth);
		}
		
		if(jQuery.browser.msie && jQuery.browser.version<=7){
			setTimeout(function(){jQuery('.news .desc').css('zoom','100%')},500);
			if(locale=="ar_ME" || locale=="fa_IR"){
				jQuery('.news .desc').width(688-newsLabelWidth);
				jQuery('.marketingTop .title').equalHeightTopPage();
				jQuery('.marketingBottom .title').equalHeightTopPage();
			}	
		}
		
		jQuery('.marketingTop .item').equalHeightTopPage();
		jQuery('.marketingBottom .item').equalHeightTopPage();		
	},600);
	
});

function adjustHeight(panel, heading, padFront) {
	var titles = jQuery(panel).find(heading);
	var panelHeights = new Array();
	var needFormat = new Array();
	var baseHeight = 0; 

	titles.each(function() {
		panelHeights.push(jQuery(this).height());
	});

	panelHeights.sort(sortNumber);

	if(panelHeights[0] == panelHeights[panelHeights.length-1]) {
	} else {
		baseHeight = panelHeights[0];

		titles.each(function() {
			if(jQuery(this).height() == baseHeight) {
	        	if(jQuery.browser.msie && jQuery.browser.version<=7){
	        		if(jQuery('#siteParam').val()=="hp_ar_ME_i" || jQuery('#siteParam').val()=="hp_fa_IR_i" || jQuery('#siteParam').val()=="hp_ar_ME_e" || jQuery('#siteParam').val()=="hp_fa_IR_e"){
						jQuery(this).html(jQuery(this).text());
					} else {
						if (padFront) {
						   jQuery(this).html('<br />' + jQuery(this).text());
						} else {
							jQuery(this).html(jQuery(this).text() + '<br /><br />');
						}
					}
				}else{
					if (padFront) {
					   jQuery(this).html('<br />' + jQuery(this).text());
					} else {
						jQuery(this).html(jQuery(this).text() + '<br /><br />');
					}
				}
			} 
		});
	}
}

function sortNumber(a,b) {
	return a-b;
}

//function onAfter(curr, next, opts) {
//var index = opts.currSlide;
//$('#prev')[index == 0 ? 'hide' : 'show']();
//$('#next')[index == opts.slideCount - 1 ? 'hide' : 'show']();
//} 

if(ismobile){
	setTimeout(function(){
		jQuery('#maincontent #navBanner').show();
	},2000);
}

//Equal Height
(function($){
	$.fn.equalHeightTopPage = function() {
		tallest = 0;
		this.each(function(){
			thisHeight = $(this).height();
			if( thisHeight > tallest)
				tallest = thisHeight;
		});
		this.each(function(){
			var x = 5;
			//if($.browser.msie){x = 10}
			$(this).height(tallest+x);
		});
	}
})(jQuery);
