var videoTitle = null; // this is read by playerManager.js to track a video start

/* inject IE referrer info */
var isIE = (navigator.userAgent.indexOf('MSIE') != -1);
function goto(url) {
	// remove url and embed parameters
	url = url.replace(/&url=[^&]*/, "").replace(/&embed=[^&]*/, "");
	
	if (isIE) {
		var referLink = document.createElement('a');
			
		// remove url and embed parameters
		referLink.href = url;
		referLink.target = "_top";
		
		document.body.appendChild(referLink);
		referLink.click();
	} else top.location.href = url;
} /* end inject IE referrer info */

function initializeMediaPlayer() {
	setProperty('appRootUrl','/fanzin/prd/');
	setProperty('playerWidth','528');
	setProperty('playerHeight','322');
	initialize();
}

function cleanUp(url) {
	url = url.replace(/\?$/, "");
	url = url.replace(/&$/, "");
	url = url.replace("?&", "?");
	url = url.replace("&&", "&");
	return url;
}

function populateAds()
{
	// used to populate ad divs on load so ad JS doesn't slow down the page while loading images
	document.getElementById("ad160x600").innerHTML="<a href='http://n.admagnet.net/panda/www/delivery/ck.php?n=a8ec0f59&amp;cb=104155060' target='_blank'><img src='http://n.admagnet.net/panda/www/delivery/avw.php?zoneid=2523&amp;n=a8ec0f59' border='0' alt='' /></a>";
	document.getElementById("ad-skyscraper").style.visibility="visible";
}

function changeVideo(video_url, video_title, video_desc, video_thumbnail, track, persist_title, swap_keyword) {
	document.getElementById('next_video_url').value = video_url;
	document.getElementById('next_video_title').value = video_title;
	document.getElementById('next_video_desc').value = video_desc;
	if (persist_title) document.getElementById('persist_title').value = persist_title;
	
	// construct submit url
	var submitURL = location.href.replace(/&url=[^&]*/, "");
	submitURL = submitURL.replace(/app=[^&]*/, ""); submitURL = cleanUp(submitURL);
	
	// used to replace keyword
	if (swap_keyword) {
		submitURL = submitURL.replace(/http:\/\/dev\.[^\.]+\.fanz\.in/, "http://dev."+swap_keyword+".fanz.in");
		submitURL = submitURL.replace(/http:\/\/staging\.[^\.]+\.fanz\.in/, "http://staging."+swap_keyword+".fanz.in");
		submitURL = submitURL.replace(/http:\/\/fanz\.in/, "http://"+swap_keyword+".fanz.in");
	}
	
	// replace url with local city name
	if (document.getElementById('city')) if (document.getElementById('city').value) submitURL = submitURL.replace(/fanz.in\/?[^\?]*/, 'fanz.in/'+document.getElementById('city').value);
	
	// append app tag for local videos
	if (track) {
		if (submitURL.indexOf("?") != -1) submitURL = submitURL.replace("?", "?app="+track+"&");
		else submitURL += "?app="+track;
	}
	
	// get rid page tags
	if (submitURL.indexOf("?") != -1) {
		if (submitURL.indexOf("standalone_video") == -1)
			submitURL = submitURL.replace(/\bpage=[^&]+/, "");
		submitURL = cleanUp(submitURL);
	}
	
	document.getElementById('video_selector').action = submitURL;
	document.getElementById('video_selector').submit();
}

function goToVideoPageFromHomePage(video_url, video_title, video_desc, submit_url) {
	document.getElementById('next_video_url').value = video_url;
	document.getElementById('next_video_title').value = video_title;
	document.getElementById('next_video_desc').value = video_desc;
	document.getElementById('video_selector').action = submit_url;
	document.getElementById('video_selector').submit();
}

function startPlayer(media_url, embed, minimal) {
	/*if (!minimal) {
		// hide comment box temporarily
		if (document.getElementById('comments-box')) document.getElementById('comments-box').style.display = "none";
	}*/
	
	if (!embed) {
		setProperty('urlToLoad',media_url);
		initializeMediaPlayer();
	} else {
		document.getElementById('player').innerHTML = "<embed style='width:528px; height:" +(media_url.match('indiatimes.com')? '425':'322')+ "px; text-align:center' bgcolor='#000000' wmode='transparent' allowscriptaccess='always' autoPlay='1' allowfullscreen='true' type='application/x-shockwave-flash' src='" +media_url+ ((media_url.match('myspace')||media_url.match('blip'))? '':'&autoplay=1&videoAutoPlay=1') + "' flashvars='" +(media_url.match('mtvnservices')? 'configParams=instance%3Dmtv&':'')+ "a=1&autostart=1&ip=true&ap=true&playerVars=autoPlay=yes'>";
	}
	
	if (!minimal) updateShareLinks(media_url, embed);
}

function updateShareLinks(media_url, embed) {
	// insert video link
	var newURL = location.href;
	if (newURL.indexOf("?") == -1)
		newURL += "?url=" + encodeURIComponent(media_url);
	else if (location.href.indexOf("url=") == -1)
		newURL += "&url=" + encodeURIComponent(media_url);
	else if (location.href.indexOf("url=") != -1)
		newURL = newURL.replace(/url=[^&]*/, "url=" + encodeURIComponent(media_url));
	
	// append embed attribute if it doesn't exist (for embedded videos)
	if (newURL.indexOf("embed=") == -1 && embed)
		newURL += "&embed=1";
	
	// remove share attribute if it already exists
	if (newURL.indexOf("share=") != -1)
		newURL.replace(/share=\w*/, "");
	
	// replace url with local city name
	if (document.getElementById('city')) if (document.getElementById('city').value) newURL = newURL.replace(/fanz.in\/?[^\?]*/, 'fanz.in/'+document.getElementById('city').value);
	
	// construct new url's
	document.getElementById('share-link-url-field').value = newURL.replace("?", "?app=link&");
	document.getElementById('fb_share_link').href = newURL.replace("?", "?share=facebook&");
	document.getElementById('twitter_share_link').href = newURL.replace("?", "?share=twitter&");
	document.getElementById('email_share_link').href = newURL.replace("?", "?share=email&");
	
	// construct friend connect comments url
	/*var comments_url = "http://fanz.in/fanzin/prd";
	var gc_comments_url = encodeURIComponent(media_url).replace(/[^\w]/g, "");
	comments_url += "/templates/fanzin/v3/friend_connect.php?url=" + gc_comments_url.substring(gc_comments_url.length-100);
	
	// update friend connect video reference
	window.frames['friend_connect_comments'].location.href = comments_url;
	
	// make comments box visible
	if (document.getElementById('comments-box')) document.getElementById('comments-box').style.display = 'block';*/
}


function unescapeQuotes(src) {
	// unescape single and double quotes from src and return
	src = src.replace("&#39;", "&rsquo;");
	src = src.replace("&rsquo;", "'");
	src = src.replace("&quot;", '"');
	return src;
}

function showDescription(title, desc) {
	
	// truncate long titles and descriptions
	shortTitle = title; shortDesc = desc;
	if (title.length > 60)
		shortTitle = title.substring(0, 60).replace(/(^\s*)|(\s*$)/, "")+"...";
	if (desc.length > 200)
		shortDesc = desc.substring(0, 200).replace(/(^\s*)|(\s*$)/, "")+"...";
	
	document.getElementById('video-title').title = unescapeQuotes(title);
	document.getElementById('video-title').innerHTML = shortTitle;
	document.getElementById('video-description').title = unescapeQuotes(desc);
	document.getElementById('video-description').innerHTML = shortDesc;
}

function searchVideos(track) {
	var tracker = track? "&app="+track : "";
	var searchTerm = document.getElementById('keyword').value.replace(/\s/g, "-");
	searchTerm = searchTerm.replace(/-{2,}/g,"-").replace(/(^-*)|(-*$)/g,""); // contract and remove leading and trailing dashes
	var country = document.getElementById('location').value.replace(/\s/g, "-").replace(/[^\w-]/g,"-");
	country = country.replace(/-{2,}/g,"-").replace(/(^-*)|(-*$)/g,""); // contarct remove leading and trailing dashes
	
	if (!searchTerm) {
		alert("Please enter a search term.");
		document.getElementById('keyword').focus();
		return false;
	}
	
	// construct new url
	var newURL = "http://";
	if (location.href.indexOf('http://dev.') != -1)
		newURL += "dev.";
	else if (location.href.indexOf('http://staging.') != -1)
		newURL += "staging.";
	
	if (searchTerm.match(/[^\w-]/g))
		newURL += searchTerm.replace(/[^\w-]/g,"-") + ".fanz.in/" +country+ "?type=search&keyword="+encodeURIComponent(searchTerm)+tracker;
	else newURL += searchTerm + ".fanz.in/" +country+ "?type=search"+tracker;
	
	goto(newURL);
	return false;
}

function clearSearchField(Focus) {
	var searchField = document.getElementById('search_field');
	if (Focus && searchField.value == "Search for More Videos")
		searchField.value = "";
	else if (!Focus && searchField.value == "")
		searchField.value = "Search for More Videos";
}

function updateFontSize(field, characterThreshold) {
	if (!characterThreshold) {
		if (field == "keyword") characterThreshold = 14;
		else if (field == "location") characterThreshold = 10;
	}
	
	field = document.getElementById(field);
	var text_length = Math.max(0, field.value.length - characterThreshold);
	field.style.fontSize = Math.max(18, 30 - text_length) + "pt";
	field.style.paddingTop = Math.min(10, text_length);
}

function hit_url(url) {
	var referLink = document.createElement('iframe');
	referLink.src = url;
	referLink.style.display = "none";
	document.body.appendChild(referLink);
}

function report_broken_link() {
	hit_url("?share=badVideo&url="+encodeURIComponent(document.getElementById('share-link-url-field').value));
	if (typeof next === 'function') setTimeout("next()", 1500);
}

function track_ad_click(ad_id) {
	var url = location.href;
	if (url.indexOf('?') != "-1") url += "&app="+ad_id;
	else url += "?app="+ad_id;
	hit_url(url);
}

function bookmark() {
	var url = location.href;
	if (url.indexOf('?') != "-1") url += "&app=bookmark";
	else url += "?app=bookmark";
	
	// track url in Google analytics
	hit_url(url.replace("app=","share="));
	
	if (document.all)
		window.external.AddFavorite(url, document.title);
	else alert("Please press CTRL-D to bookmark this page.");
	//else if (window.sidebar) window.sidebar.addPanel(document.title, location.href, '');
}

/* hack for google suggest */
function getElementsByClassName(classname, node) {
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
		if(re.test(els[i].className))a.push(els[i]);
	return a;
}

var cap_results_timeout, cap_results_interval;

function show_related_terms() {
	if (!cap_results_interval) cap_results_interval = setInterval('cap_results()', 50);
	if (cap_results_timeout) {
		clearTimeout(cap_results_timeout);
	} 
	cap_results_timeout = setTimeout('cap_results(1)', 1501);
}

function cap_results(flag) {
	var resultsNode = document.getElementById("google-autocomplete-results");
	var gac_result_a = getElementsByClassName("gac_a",resultsNode);
	var gac_result_c = getElementsByClassName("gac_c",resultsNode);
	// cap to 4 results
	var max_index = Math.min(gac_result_c.length, 4);
	for (var i=0; i < max_index; i++) {
		// skip ad links
		if (!gac_result_c[i].innerHTML.match(/<[aA]/)) {
			if (gac_result_a[i]) gac_result_a[i].style.display='block';
			if (gac_result_c[i]) gac_result_c[i].style.display='inline';
		} else	{
		 max_index++;
		}
	}
	if (flag) { clearInterval(cap_results_interval); cap_results_interval = null; }
}
/* end hack for google suggest */

var tickerInterval;
var separator = ', ';
function moveTicker() {
	var ticker_holder = document.getElementById('popular-sites');
	var ticker_content = ticker_holder.innerHTML.split(new RegExp(separator, 'i'));
	var first_site = ticker_content[0];
	ticker_holder.innerHTML = ticker_holder.innerHTML.substring(first_site.length+separator.length)+separator+first_site;
}

function startTicker() {
	if (!tickerInterval) tickerInterval = setInterval("moveTicker()", 5000);
}

function stopTicker() {
	if (tickerInterval) {
		clearInterval(tickerInterval);
		tickerInterval = null;
	}
}

function toggleSet(set) {
	var relatedVideos = document.getElementById("related-videos");
	var featuredVideos = document.getElementById("featured-videos");
	
	if (set == "related" && relatedVideos.style.display == "none") {
		relatedVideos.style.display = "inline";
		featuredVideos.style.display = "none";
	} else if (set == "featured" && featuredVideos.style.display == "none") {
		featuredVideos.style.display = "inline";
		relatedVideos.style.display = "none";
	}
}

function dimRelated() {
	var related_label = document.getElementById('related-videos-field');
	related_label.innerHTML = "related videos";
	related_label.style.cursor = "text";
	related_label.style.color = "#666";
}

var randomInterval;
function randomize() {
	if (!randomInterval) {
		randomInterval = setInterval("randomPulse()", 100);
		setTimeout("clearInterval(randomInterval);randomInterval=null;searchVideos('random');", 700);
	}
}

function randomPulse() {
	var keywordStartIndex = Math.floor(Math.random() * hotTrends.length);
	var locationStartIndex = Math.floor(Math.random() * countries.length);
	
	var keyword_field = document.getElementById('keyword');
	var location_field = document.getElementById('location');
	keyword_field.value = hotTrends[keywordStartIndex];
	location_field.value = countries[locationStartIndex];
}

function onVideoComplete(){
	// triggered by JW player via playerManager.js when a video play through to the end
	if (typeof next === 'function') next();
}

function setOpacity(obj,value) {
		obj.style.opacity = value/10;
		obj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

// cookie manipulating class
/**
 * @author 	Maxime Haineault (max@centdessin.com)
 * @version	0.3
 * @desc 	JavaScript cookie manipulation class
 * 
 */

Cookie = {	

	/** Get a cookie's value
	 *
	 *  @param integer	key		The token used to create the cookie
	 *  @return void
	 */
	get: function(key) {
		// Still not sure that "[a-zA-Z0-9.()=|%/]+($|;)" match *all* allowed characters in cookies
		tmp =  document.cookie.match((new RegExp(key +'=[a-zA-Z0-9.()=|%/]+($|;)','g')));
		if(!tmp || !tmp[0]) return null;
		else return unescape(tmp[0].substring(key.length+1,tmp[0].length).replace(';','')) || null;
		
	},	
	
	/** Set a cookie
	 *
	 *  @param integer	key		The token that will be used to retrieve the cookie
	 *  @param string	value	The string to be stored
	 *  @param integer	ttl		Time To Live (hours)
	 *  @param string	path	Path in which the cookie is effective, default is "/" (optional)
	 *  @param string	domain	Domain where the cookie is effective, default is window.location.hostname (optional)
	 *  @param boolean 	secure	Use SSL or not, default false (optional)
	 * 
	 *  @return setted cookie
	 */
	set: function(key, value, ttl, path, domain, secure) {
		cookie = [key+'='+    escape(value),
		 		  'path='+    ((!path   || path=='')  ? '/' : path),
		 		  'domain='+  ((!domain || domain=='')?  window.location.hostname : domain)];
		
		if (ttl)         cookie.push('expires='+Cookie.hoursToExpireDate(ttl));
		if (secure)      cookie.push('secure');
		return document.cookie = cookie.join('; ');
	},
	
	/** Unset a cookie
	 *
	 *  @param integer	key		The token that will be used to retrieve the cookie
	 *  @param string	path	Path used to create the cookie (optional)
	 *  @param string	domain	Domain used to create the cookie, default is null (optional)
	 *  @return void
	 */
	unset: function(key, path, domain) {
		path   = (!path   || typeof path   != 'string') ? '' : path;
        domain = (!domain || typeof domain != 'string') ? '' : domain;
		if (Cookie.get(key)) Cookie.set(key, '', 'Thu, 01-Jan-70 00:00:01 GMT', path, domain);
	},

	/** Return GTM date string of "now" + time to live
	 *
	 *  @param integer	ttl		Time To Live (hours)
	 *  @return string
	 */
	hoursToExpireDate: function(ttl) {
		if (parseInt(ttl) == 'NaN' ) return '';
		else {
			now = new Date();
			now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
			return now.toGMTString();			
		}
	},

	/** Return true if cookie functionnalities are available
	 *
	 *  @return boolean
	 */
	test: function() {
		Cookie.set('b49f729efde9b2578ea9f00563d06e57', 'true');
		if (Cookie.get('b49f729efde9b2578ea9f00563d06e57') == 'true') {
			Cookie.unset('b49f729efde9b2578ea9f00563d06e57');
			return true;
		}
		return false;
	},
	
	/** If Firebug JavaScript console is present, it will dump cookie string to console.
	 * 
	 *  @return void
	 */
	dump: function() {
		if (typeof console != 'undefined') {
			console.log(document.cookie.split(';'));
		}
	}
}

