// Carousels namespace
var Carousels = (function(){

var _intStaySecs = "11";
var VIDEOS = new Array;
var VIDEO_PLAYERS = new Array;
var smallCarousel = null;
var smallCarouselLoaded = false;
var ytplayer; 
var ytnowplayer;
var htcplayer;
var youkuplayer; 
var cloneItem;
var flashRequired = "<div style='padding:220px 0 0 0;'>You will need a Flash-enabled browser to watch this video.</div>";

// Start Private functions
 
/* ----- Utils Functions ----- */
function slidePhones()
{
	var left = null; 
	$('ul.phones li.first').each(function(index){
	$(this).animate({
		left: 0,
		"opacity": 1
	}, 700, 'swing', function(){
		//$(this).removeClass('first');
	});
	});
}

function findStartPos()
{
	startPos = getParameterByName('item'); 
	if(startPos == null || startPos == ""){
		// Check if null
		startPos = 1;
	}
	return startPos;
}

// Embed Youtube using swfobject call
function embedVideos()
{
	for(i = 0; i < VIDEOS.length; i++ ){ 
		
		var pid = VIDEOS[i].playerId;
		//for no flash player
		$('#' + pid).width(850).height(504).html(flashRequired);
		
		switch(VIDEOS[i].videoType){
			case 'youku video':
				//var flashvars = {isAutoPlay: true};
				var flashvars = {isShowRelatedVideo:false,allowFullScreen:"false",skinflag:"2",skincolor1:"ffffff",skincolor2:"555555",skinalpha:"40"};
				var params = { allowScriptAccess: "always", wmode: "transparent", menu: false };
				var atts = { id: pid , name: pid};
				var yt = 'http://player.youku.com/player.php/partnerid/XMTQ4OA==/sid/' + VIDEOS[i].videoId + '/v.swf'; 
				swfobject.embedSWF(yt,pid, "850", "504", "8", null, flashvars, params, atts);
				break;
			case 'htc video':
				//video host by HTC
				var strUrl = '/player/player-licensed.swf'; 
				var flashvars = {file:VIDEOS[i].videoId,repeat:'single',image:VIDEOS[i].videoImage,skin:'/player/whotube.zip',screencolor:'000000'};
				var params = { allowScriptAccess: "always", wmode: "transparent",allowfullscreen:true};
				var atts = {  id: 'htc' + i, name:  'htc' + i  };
				swfobject.embedSWF(strUrl, pid, "850", "504", "8", null, flashvars, params, atts);
			case 'youtube video':
				var params = { allowScriptAccess:"always", wmode:"transparent", menu:false, allowFullScreen:true, quality:"high"};
				var atts = { id: pid };
				var yt = 'http://www.youtube.com/v/' +VIDEOS[i].videoId + '?enablejsapi=1&playerapiid=' + pid; 
				yt += "&showsearch=0&rel=0&fs=1&iv_load_policy=3&cc_load_policy=1";
				swfobject.embedSWF(yt,pid, "850", "504", "8", null, null, params, atts);
				break;
		}
	}
}

function playCurrentVideos(i){
	try{
		if(VIDEOS[i].videoType == 'youku video'){
		
		}
	}
	catch(err)
	{
	}
}

function pauseVideos(i){		
	try{
		switch(VIDEOS[i].videoType){
			case 'youku video':
				youkuplayer = $('#main-carousel').find('#' + VIDEOS[i].playerId);
				if(youkuplayer != null){
					 var clone = youkuplayer.clone(true);
					 youkuplayer.remove();
					 $("#container" + i).html(clone);
				}
				break;
			case 'htc video':
				htcplayer = document.getElementById('htc' + i);
				if(htcplayer != null){
					var state = htcplayer.getConfig().state;
					if(state != 'PAUSED'){
						htcplayer.sendEvent("stop");
					}
				}
				break;
			case 'youtube video':
				ytplayer = document.getElementById(VIDEOS[i].playerId);
				if(ytplayer != null){				
					var playerState = ytplayer.getPlayerState();
					if(playerState != 2){
						ytplayer.pauseVideo();
					}
				}
				break;
		}		
	}
	catch(err)
	{
		//alert(err);
	}
}

// Set on state to the lower carousel on the media page.
function setOnState(currentIndex)
{
	$('#carousel li').each(function(index){
	if(index == currentIndex){
		$(this).addClass('on');
	}else{
		$(this).removeClass('on');
	}
	});
}

// Returns parameter value if found in the query string
function getParameterByName(name)
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec(window.location.href);
	if(results == null)
	return "";
	else
	return results[1];
}

// Sets the lighbox properties
function setLightboxPopup()
{ 
	$('a.media').fancybox({
		'speedIn':400, 
		'speedOut':200, 
		'type':'iframe',
		'width':850,
		'height':633,
		'padding':0,
		'overlayOpacity':0.8,
		'overlayColor':'#000',
		'autoScale':false,
		'scrolling':'no'
	});
};

function hideArrows(intTotalContent)
{
	if(intTotalContent == 1){
		var objCSS = {
			'display' : 'none'
		}
		$('.jcarousel-next-horizontal').css(objCSS);
		$('.jcarousel-prev-horizontal').css(objCSS);
		$('#round-links').css(objCSS);
	}
};

function createStrControl(intTotalContent)
{
	var strControl = '';
	for(i = 1; i<= intTotalContent; i++){
		var css = 'round';
		if(i == 1){
			css = 'roundSelected';
		}
		strControl +='<div class="' + css + '" id="round_btn_' + i + '"></div>';
	}
	strControl = '<div id="jcarousel-control" align="center">' + 
				 '<table id="round-links">' + 
				 '<tr><td align="center">' + strControl + '</td></tr>' + 
				 '</table>' + 
				 '</div>';
	return strControl;	
};

function setStrWrap()
{
	var siteName = location.href.toLowerCase();
	var strWrap = 'both';
	if(siteName.indexOf('/mea-sa/') > -1 || siteName.indexOf('/eg/') > -1){
		if($.browser.opera || $.browser.safari){
			strWrap = 'both';
		}
	}
	return strWrap;
};

function setRoundedLinks(carousel)
{
	$('#round-links div').bind('click', function(){
		var strClickRoundId = this.id;
		var strIdx = strClickRoundId.replace('round_btn_', '');
	carousel.scroll($.jcarousel.intval(strIdx));
	return false;
	}); 
};

function checkSmallMediaScroll(idx)
{
	if(smallCarouselLoaded && ((idx < smallCarousel.first) || (idx > smallCarousel.last))){
		if(idx < smallCarousel.first){
		smallCarousel.scroll($.jcarousel.intval(idx));
		}else if(idx > smallCarousel.last){
		var offsetPos = (idx - smallCarousel.last) + smallCarousel.first;
		smallCarousel.scroll($.jcarousel.intval(offsetPos));	
		}
	}
};

/* ----- Shared Callbacks ----- */

// jcarousel itemFirstInCallback
function itemFirstInCallback(carousel, item, idx, state)
{ 
	$("#round_btn_" + idx).removeClass('round');
	$("#round_btn_" + idx).addClass('roundSelected');
	$("#round_btn_" + idx).unbind('click');

	// Copied from htc_default.js
	//var idxNow = carousel.index(idx, Carousels.total_content + 1);
	/*if(pageTracker){
		var strGA = eval('googlepagename_' + (idxNow -1));
		pageTracker._trackPageview(strGA);
	}*/
}

// jcarousel itemFirstOutCallback
function itemFirstOutCallback(carousel, item, idx, state)
{
	$("#round_btn_" + idx).removeClass('roundSelected');
	$("#round_btn_" + idx).addClass('round');
	$("#round_btn_" + idx).bind('click', function(){
		carousel.scroll(idx);
		return false;
	}); 
}

/* ----- Product Page Carousel ----- */

function productPage_itemLoadCallback(carousel, state)
{
	// Check if the requested items already exist
	if(carousel.has(carousel.first, carousel.last)){
		return;
	}
	
	// Get xml file
	$.get('sushi-boat.xml', {
		first: carousel.first,
		last: carousel.last
	},
	function(xml){
		productPage_itemAddCallback(carousel, carousel.first, carousel.last, xml);
	},
	'xml'
	);
};
 
function productPage_itemAddCallback(carousel, first, last, xml)
{
	var phones = $(xml).find('images'); 
	
		var strControl = createStrControl(phones.length);	 
	$('#sushi-boat').append(strControl);
	setRoundedLinks(carousel);
	hideArrows(phones.length);
 
	phones.each(function(i){
		carousel.add(i + 1, productPage_getItemHTML(i, $(this)));
	});
	carousel.size(phones.length);
	// HTC to confirm this is correct for their tracker
	Carousels.total_content = phones.length;
	// Slide phone in
	slidePhones();
};
 
function productPage_getItemHTML(i, item)
{
	var html = '';
	var phones = $(item).find('image');
	html += '<ul class="phones phones' + phones.length + '">'
	
	phones.each(function(j){
	var productImg = $(this).find("Bigimage").text();
	var titleImg = $(this).find("TagLine").text();
	var href = $(this).find("Link").text();
	var tagLine = $(this).find("Description").text();
	var css = '';
	if(i == 0 && j < 3){
		css += ' class="first"'
	}
	
	html += '<li' + css + '>';
	html += '<a href="' + href + '">';
	html += '<img src="' + productImg + '" alt="" />'
	html += '<span class="title"><img src="' + titleImg + '" alt="" /></span>';
	html += '<span class="tagline">' + tagLine + '</span>';
	html += '</a>';
	html += '</li>';
	});	
						
	html += '</ul>'
	return html;
};

function setProductPageCarousel()
{ 
	var strWrap = setStrWrap();
	$('#sushi-boat').append('<ul id="sushi-boat" class="product-page"></ul>');
	$('#sushi-boat').jcarousel({
		vertical: false,
		wrap: strWrap,
		scroll: 1,
		auto: this._intStaySecs,
		itemLoadCallback: productPage_itemLoadCallback,
		itemFirstInCallback:itemFirstInCallback,
		itemFirstOutCallback: itemFirstOutCallback
	}); 
};

/* ----------------------------------------------------- Banner Carousel -------------------------------------- */
function banner_itemLoadCallback(carousel, state)
{
	// Check if the requested items already exist
	if(carousel.has(carousel.first, carousel.last)){
		return;
	}
	
	// Get xml file
	$.get(ReturnCloserLookXml_path(), {
		first: carousel.first,
		last: carousel.last
	},
	function(xml){
		banner_itemAddCallback(carousel, carousel.first, carousel.last, xml);
	},
	'xml'
	);
};
 
function banner_itemAddCallback(carousel, first, last, xml)
{
	var media = $(xml).find('media'); 
	media.each(function(i){
		carousel.add(i + 1, banner_getItemHTML(i, $(this)));
	});
	// Set the size of the carousel
	carousel.size(media.length);
	// HTC to confirm this is correct for their tracker
	Carousels.total_content = media.length;
	// Set popup settings on the links
	setLightboxPopup();
};
 
function banner_getItemHTML(i, item)
{
	var html = '';
	var img = item.find('thumbnail').text();
	var type = item.find('type').text();
	html += '<a href="media.html?item=' + (i + 1) + '" class="media">';
	html += '<img src="' + img + '" alt="" />';
	if(type.indexOf('video') > -1){
		html += '<img class="icon" src="/images_v2/banner/video.png" alt="" />';
	}
	html += '</a>';
	return html;
};

function setBannerCarousel()
{
	$('#media-carousel').append('<ul></ul>');
	$('#media-carousel ul').jcarousel({
		vertical: true,
		scroll: 1,
		itemLoadCallback: banner_itemLoadCallback
	});
 
}

/* ---------------------------------------- HTC Sense Carousel -------------------------------------- */

function sense_itemLoadCallback(carousel, state)
{
	var intCount = $('#htc-sense #senses ul li').length;
	var strControl = createStrControl(intCount);	 
	$('#htc-sense').append(strControl);
	setRoundedLinks(carousel);
	hideArrows(intCount);
	//carousel.size(intCount);
	// HTC to confirm this is correct for their tracker
	//Carousels.total_content = intCount; 
};
 
function setSenseCarousel()
{ 
	var strWrap = setStrWrap();
	$('#htc-sense #senses').css('display','block');
	$('#htc-sense #senses').jcarousel({
		vertical: false,
		offset: 1,
		wrap: 'both',
		scroll: 1,
		auto: this._intStaySecs,
		initCallback: sense_itemLoadCallback,
		itemFirstInCallback:itemFirstInCallback,
		itemFirstOutCallback: itemFirstOutCallback
	}); 
};

/* ---------------------------------------------------- Main Media Carousel ------------------------------------ */

function mainMedia_itemLoadCallback(carousel, state)
{
	// Check if the requested items already exist
	if(carousel.has(carousel.first, carousel.last)){
		return;
	}
	
	// Get xml file
	$.get(window.parent.ReturnCloserLookXml_path(), {
		first: carousel.first,
		last: carousel.last
	},
	function(xml){
		mainMedia_itemAddCallback(carousel, carousel.first, carousel.last, xml);
	},
	'xml'
	);
};
	
// jcarousel mediaItemFirstInCallback
function mainMedia_itemVisibleInCallback(carousel, item, idx, state)
{
	Carousels.currentPlayingItem = idx - 1;
	playCurrentVideos(idx - 1);
	
	// Set on state
	setOnState(idx - 1);
	
	// if smallCarousel loaded scroll to the same window
	checkSmallMediaScroll(idx);
		
	// Copied from htc_default.js 
	var idxNow = carousel.index(idx, Carousels.total_content + 1);
	 /* if(pageTracker){
		var strGA = eval('googlepagename_' + (idxNow -1));
		pageTracker._trackPageview(strGA);
	}*/
};

function mainMedia_itemVisibleOutCallback(carousel, item, idx, state)
{
	pauseVideos(idx - 1);
}

 
function mainMedia_itemAddCallback(carousel, first, last, xml)
{

	var media = $(xml).find('media'); 
	media.each(function(i){
		carousel.add(i + 1, mainMedia_getItemHTML(i, $(this)));
	});
	carousel.size(media.length);
	
	// HTC to confirm this is correct or still needed for their tracker
	Carousels.total_content = media.length;
	
	// Set links on the small carousel
	$('#carousel ul li').each(function(i){
	$(this).bind('click', function(){
		strIdx = (i + 1);
		carousel.scroll($.jcarousel.intval(strIdx));
		return false;
	});
	});
	// Embed Youtube vids
	embedVideos();
};
 
function mainMedia_getItemHTML(i, item)
{
	var html = ''; 
	var type = item.find("type").text();
	var link = item.find("link").text();
	var text = item.find("text").text();
	var videoimage = item.find("videoimage").text();

	switch(type){
	case 'youku video':
		var videoCount = VIDEOS.length;
		var playerId = 'video' + i;
		var containerId = 'container' + i;
		VIDEOS[videoCount] = {'playerId':playerId, 'videoId':link, 'videoType':type};
		html += '<div id="' + containerId + '"><div id="' + playerId + '"></div></div>';
		break;
	case 'htc video':
		var videoCount = VIDEOS.length;
		var playerId = 'video' + i;
		VIDEOS[videoCount] = {'playerId':playerId, 'videoId':link, 'videoType':type, 'videoImage':videoimage};
		html += '<div id="' + playerId + '"></div>';
		break;
	case 'youtube video':
		// Add to a Video array to embed after inserting the HTML.
		var videoCount = VIDEOS.length;
		var playerId = 'video' + i;
		VIDEOS[videoCount] = {'playerId':playerId, 'videoId':link, 'videoType':type};
		var facebookUrl = 'http://www.facebook.com/sharer.php?u=http://www.youtube.com/watch?v=' + link + 'M&t=' + text
		var twitterUrl = 'http://twitter.com/home?status=' + text + ' http://www.youtube.com/watch?v=' + link
		html += '<div id="' + playerId + '"></div>';
		html += '<p>Share this video via '
		html += '<a href="' + facebookUrl + '" target="_blank">Facebook</a>'
		html += ' or '
		html += '<a href="' + twitterUrl + '" target="_blank">Twitter</a>. '
		html += 'For more videos, visit our official '
		html += '<a href="http://www.youtube.com/htc" target="_blank">YouTube channel</a></p>'
		break;
	case 'image':
		html += '<img src="' + link + '" alt="" />';
		html += '<span>' + text + '</span>';
		break;
	}
	return html;
};

function setMainMediaCarousel()
{ 
	$('#main-carousel').append('<ul></ul>'); 
	var startPos = findStartPos();
	$('#main-carousel').jcarousel({
	vertical: false,
	scroll: 1,
	start: startPos,
	itemLoadCallback: mainMedia_itemLoadCallback,
	itemVisibleInCallback: { onBeforeAnimation: mainMedia_itemVisibleInCallback },
	itemVisibleOutCallback: { onAfterAnimation: mainMedia_itemVisibleOutCallback }
	}); 
};

/* ------------------------------------------------------ Small Media Carousel --------------------------------------- */
	
function smallMedia_initCallback(carousel, state){
	smallCarousel = carousel;
}

function smallMedia_itemLoadCallback(carousel, state)
{
	// Check if the requested items already exist
	if(carousel.has(carousel.first, carousel.last)){
		return;
	}
	
	// Get xml file
	$.get(window.parent.ReturnCloserLookXml_path(), {
		first: carousel.first,
		last: carousel.last
	},
	function(xml){
		smallMedia_itemAddCallback(carousel, carousel.first, carousel.last, xml);
	},
	'xml'
	);
};
 
function smallMedia_itemAddCallback(carousel, first, last, xml)
{
	var media = $(xml).find('media'); 
	media.each(function(i){
		carousel.add(i + 1, smallMedia_getItemHTML(i, $(this)));
	});
	carousel.size(media.length);
	// HTC to confirm this is correct for their tracker
	Carousels.total_content = media.length;
	// Set smallCarousel loaded. This is used as we cannot tell if the small
	// media carousel is initally loaded while we a re loading the main one.
	smallCarouselLoaded = true;
	// Add on state and scroll to
	var startPos = findStartPos();
	setOnState(startPos - 1);
	checkSmallMediaScroll(startPos);
};
 
function smallMedia_getItemHTML(i, item)
{
	var html = '';
	var img = item.find('thumbnail').text();
	var type = item.find('type').text();
	html += '<a href="media.html?item=' + (i + 1) + '" class="media">';
	html += '<img src="' + img + '" alt="" />';
	if(type.indexOf('video') > -1){
	html += '<img class="icon" src="/images_v2/banner/video.png" alt="" />';
	}
	html += '</a>';
	return html;
};

function setSmallMediaCarousel()
{ 
	$('#carousel').append('<ul></ul>');
	$('#carousel').jcarousel({
		vertical: false,
		scroll: 1,
		initCallback: smallMedia_initCallback,
		itemLoadCallback: smallMedia_itemLoadCallback
	}); 
}; 

// End Private functions

// Start Public functions
return { 
	total_content: 0, // Set the default to 0
	carousel_type: null,
	currentPlayingItem: 0,
	 
	/* ----- Utils ----- */
	
	SetOnState:function(index){
	setOnState(index);
	},
	
	/* ----- Product Page ----- */
	
	SetHomePageCarousel:function(){
	setHomePageCarousel();
	},
	
	/* ----- Product Page ----- */
	
	SetProductPageCarousel:function(){
		setProductPageCarousel();
	},
	
	/* ----- Banner ----- */
	
	SetBannerCarousel:function(){
		setBannerCarousel();
	},
	
	/* ----- HTC Sense ----- */
	
	SetSenseCarousel:function(){
		setSenseCarousel();
	},
	
	/* ----- Media Lightbox ----- */
	
	SetSmallMediaCarousel:function(){
		setSmallMediaCarousel();
	},
	
	SetMainMediaCarousel:function(){
		setMainMediaCarousel();
	}
	
}
// End Public functions
})();


// Pages namespace
var Pages = (function(){
// Start Private functions 

function setupNavigationOn()
{
	$.get(ReturnNavigationXml_path(), {
	},
	function(xml){
		var item = $(xml).find('item'); 
		item.each(function(i){
			var currentUrl = location.href.toLowerCase();
			var link = $(this).attr('link').toLowerCase();
			if(currentUrl.indexOf(link) > -1){
				$('#navigation ul li').eq(i).addClass('on');
			}
		});
	},
	'xml'
	);
}

function switchCss(link, cssClass)
{
	$(link).parent().siblings().each(function(index) {
	$(this).removeClass(cssClass);
	});
	$(link).parent().addClass(cssClass);
}

function addSeeMoreLink()
{
	if($('#quotes-list li').length > 4){ 
	var siteName = location.href.toLowerCase();
	if(siteName.indexOf('tw/') > -1 || siteName.indexOf('/cn/') > -1){
		_strQuoteMore = "<span style='font-size: 12px;'>" + _strQuoteMore + "</span>";
		_strQuoteFewer = "<span style='font-size: 12px;'>" + _strQuoteFewer + "</span>";
	}
	var link = '<p id="see-more">' + 
		 '<a href="#" onclick="Pages.ShowQuotes(); return false;" class="more">' + 
		 '<span class="lt"><!-- blank --></span>' + 
		 '<span class="md">' + _strQuoteMore + '</span>' + 
		 '<span class="rt"><!-- blank --></span>' + 
		 '</a>' + 
		 '<a href="#" onclick="Pages.HideQuotes(); return false;" class="fewer">' + 
		 '<span class="lt"><!-- blank --></span>' + 
		 '<span class="md">' + _strQuoteFewer + '</span>' + 
		 '<span class="rt"><!-- blank --></span>' + 
		 '</a>' + 
		 '</p>';
	$('#quotes .middle').append(link);
	}
}

function hideQuotes()
{
	$('#quotes').addClass('hide').removeClass('show');
	$('#quotes-list li:gt(3)').addClass('hidden');
}

function showQuotes(){
	$('#quotes').removeClass('hide').addClass('show');
	$('#quotes-list li.hidden').removeClass('hidden');
}

// End Private functions

// Start Public functions
return {
	/*
	Wrapper for switching the nav css class
	Used for links in ul lists.
	*/
	SwitchCss:function(link){
	switchCss(link, 'on');
	},
	
	/*
	Wrapper for hidding quotes
	*/
	HideQuotes:function(){
		hideQuotes();
	},
	
	/*
	Wrapper for showing quotes
	*/
	ShowQuotes:function(){
		showQuotes();
	},
	
	/*
	Wrapper for adding the see more link
	*/
	AddSeeMoreLink:function(){
		addSeeMoreLink();
	},
	
	SetupNavigationOn:function(){
		setupNavigationOn();
	}	
}
// End Public functions
})();

