// this file contains heavy-wide code used on the frontend user-facing site.
var Heavy = (typeof(Heavy) != "object") ? {} : Heavy;

$.extend(Heavy, {
		/**
		* Cookies! Constructor gets cookie value by default
		* @constructor
		* @param {String} name This is the name of your cookie
		*/
		Cookie : function(name, options) {
			var options = options || {};

			/**
			* Get the cookie and return a string value
			* @return String
			*/
			this.get = function() {
				var cookies = document.cookie.split(';');
				for (var i = 0, c; c = cookies[i]; i++) {
					c = c.replace(/^\s+/, ""); //trim the front of the string
					c = c.split("=");
					if(c[0] == this.name) {
						return this.value = decodeURIComponent(c[1]);
					}
				}
				return null;
			};

			/**
			* Sets the scalar value of the cookie, also performs a save.
			* @return Void
			* @param value {String} Value of the cookie to be set
			*/
			this.set = function(value) {
				this.value = value;
				return this.save();
			};

			this.push = function(v) {
				var valueArray = this.value.split("|");
				if (valueArray[0] !== "") {
					valueArray.push(v);
				} else {
					return this.set(v);
				}
				return this.set(valueArray.join("|"));
			};

			this.pop = function() {
				var valueArray = this.value.split("|");
				return valueArray.pop();
			};

			this.getList = function() {
				return this.value.split("|");
			};

			this.setPath = function(path) {
				return this.path = '; path=' + path;
			};
			this.setDomain = function(domain) {
				return this.domain = '; domain=' + domain;
			};
			this.setExpiration = function(expiration) {
				if (expiration === 0) return this.expires = "";
				date = new Date();
				date.setTime(date.getTime() + (expiration * 24 * 60 * 60 * 1000));
				return this.expires = '; expires=' + date.toGMTString(); // use expires attribute, max-age is not supported by IE
			};

			this.remove = function() {
				this.setExpiration(-1);
				this.value = null;
				return this.save();
			};

			this.save = function() {
				return document.cookie = [this.name, '=', encodeURIComponent(this.value), this.expires, this.path, this.domain].join('');
			};

			// setup internal properties
			this.name       = name;
			this.value      = options.value || "";
			this.expires    = this.setExpiration(options.expires || 0);
			this.path       = this.setPath(options.path || "/");
			// this.domain     = this.setDomain(options.domain || Host.DOMAIN);

			if (options.value) {
				this.save();
			} else {
				this.get();
			};
		},
		hasCookie: function() {
			var c = new Heavy.Cookie("test");
			c.set(Math.random());
			var v = c.get();
			c.remove();
			return v !== null ? true : false;
		}
});

function cache_buster() {
	return Math.floor(Math.random()*10000000);
}


/********************* GEO TARGETING FUN *********************/

var GEO = function() {
	var self = this;
	var cookies = ['geo_content','geo_ad'];

	this.set = function(params) {
		var geo_hash = self.getAll();
		for(var i=0; i < cookies.length; i++){
			var type = cookies[i];
			if(typeof(params) == 'string')
				var value = params;
			else
				var value = (typeof(params[type]) != 'undefined') ? params[type] : geo_hash[type];

			// if geo_content, convert to US,CA,UK, or ANZ
			if(type == 'geo_content') {
				if(value == 'CA' || value == 'UK' || value == 'US') {
					// do nothing.  use the region as-is.
				}
				else if(value == 'AU' || value == 'NZ') {
					value = 'ANZ';
				}
				else {
					value = 'US';
				}
			}

			// setup new cookie
			var geo_cookie = new Heavy.Cookie(type);
			geo_cookie.setExpiration(1);
			geo_cookie.set(value);
		}
	};

	this._get = function(cookie_name) {
		var cookie = new Heavy.Cookie(cookie_name);
		return cookie.value;
	};

	this.getAll = function() {
		var values = {};
		for(var index=0; index < cookies.length; index++){
			var type = cookies[index];
			var cookie = new Heavy.Cookie(type);
			values[type] = cookie.value || 'US';
		}
		return values;
	};

	this.isDefined = function() {
		for(var index=0; index < cookies.length; index++) {
			var type = cookies[index];
			var cookie = new Heavy.Cookie(type);
			var value = cookie.value;
			if(typeof(value) == 'undefined' || value == '' || value == 'WW')
				return false;
		}
		return true;
	};

	this.getAdGeoCode = function() {
		return this._get('geo_ad');
	};

	this.getContentGeoCode = function() {
		return this._get('geo_content');
	};

	this.checkContentGeoCode = function() {
		var gc = this.getContentGeoCode();
		if(gc.length == 2 && geo_content_code != gc) {
			// todo: might have to do more than this
			// refresh the page from server
			// temporarily allow users to receive default region
			//window.location.reload( true );
		}
	};
};

// Add GEO class to Heavy Object
$.extend(Heavy, { geo: new GEO() });

// Called from the doubleclick request
function setGeoCode(geo_code) {
	Heavy.geo.set(geo_code);
	Heavy.geo.checkContentGeoCode();
}

function checkGeoCode() {
	// doubleclick GeoTargeting cookie
	if(Heavy.geo.isDefined()){
		// todo: pass ad geocode to ad object

		Heavy.geo.checkContentGeoCode();
	} else {
		// no cookies, write the ad to the page which sets the geo_code cookies

		// todo: replace line below with correct call to get qa vs. live
		//var zone = (AdWrapper.site.substring(0,2) == 'qa') ? 'qa.heavy.geodetect' : 'hvy.heavy.geodetect';
		// temporary assignment, please fix me
		var zone = 'hvy.heavy.geodetect';
		document.write('<script src="http://ad.doubleclick.net/adj/' + zone + '/default;sz=1x4;ord=' + cache_buster() + '"><\/script>');
	}
}

$.extend(Heavy, {
		Navigation: function() {
			// handler for roll-over images
			$(".rollover").hover(
				function() {
					if($(this).attr("src").indexOf("-hover") == -1) {
						var newSrc = $(this).attr("src").replace(".png", "-hover.png");
						$(this).attr("src", newSrc);
					}
				},
				function() {
					if($(this).attr("src").indexOf("-hover.png") != -1) {
						var oldSrc = $(this).attr("src").replace("-hover.png", ".png");
						$(this).attr("src", oldSrc);
					}
					if(window.location==current_url && $('#section').val()==undefined){
						$("#home_logo").attr('src','/media/images/nav/nav-logo-hover.png');
					}
				}
				);

			// set default text in search box
			$("#query-box").click(function() {
					if($("#query-box").val() == "Search") {
						$("#query-box").val("");
					}
			});

		},
		SearchBox:{
			setup: function(){
				$("#query-box").click(function() {
						if($("#query-box").val() == "Search") {
							$("#query-box").val("");
						}
				});

				$("#query-box").blur(function() {
						if($("#query-box").val() == "") {
							$("#query-box").val("Search");
						}
				});

			}
		},
		UpdateLoginStatus: function(){
			var loginCookie = new Heavy.Cookie("mry");
			if(loginCookie.value){
				login = $('#login');
				login.text('LOG OFF');
				login.attr('href','/user/logoff');
			}
		}
});

// Get GEO code from DoubleClick - DO NOT FUCKING TOUCH THE LINE BELOW
checkGeoCode();
// Javascript to update menu image
$.extend(Heavy, {
		updateMenuImage: function() {
			var channel = new Array();
			var section=$('#section').val();
			if(section!=null && section !=""){
				$("#"+section).attr('src','/media/images/nav/nav-'+section+'-hover.png');
				$("#"+section).attr('class','');
			}else{
				if(typeof(current_url)!="undefined"){
					channel= current_url.split("/");
					if(channel[3]!=null && channel[3]!="" && channel[3] !=undefined){
						channel =channel[3];
						//if(channel !='specials' && channel!="post" && channel!="search" && channel!="video" && channel!="all"){
						if(channel =='comedy' || channel=="sports" || channel=="movies" || channel=="music" || channel=="style" || channel=="games"){
							if($("#"+channel)!=null){
								if($("#"+channel).attr("src").indexOf("-hover") == -1) {
									var newSrc = $("#"+channel).attr("src").replace(".png", "-hover.png");
									$("#"+channel).attr("src",newSrc);
								}
							}
						}
					}
					if(window.location==current_url){
						$("#home_logo").attr('src','/media/images/nav/nav-logo-hover.png');
					}
				}
			}
} });

$.extend(Heavy, {
		getPlaylist: function(id,section_name) {
			var html = $.ajax({
					url: "/playlist/getplaylist/id/"+id,
					async: false,
					type: "POST",
					dataType: "json"
			}).responseText;
			var obj=eval(html);
			var	strOutput="<ul class='top-menu'>";
			strOutput+="<li><a href='/"+section_name+"/'>Blog</a></li>";
			strOutput+="<li><a href='/"+section_name+"/sort/most-recent'>Most Recent</a></li>";
			strOutput+="<li><a href='/"+section_name+"/sort/most-popular'>Most Popular</a></li>";
			for(i=0;i<obj.length;i++){
				if(i>0 && (i-3)%5)
					strOutput+="</ul><ul class='top-menu'>";
				if(obj[i].name.length>=26)
					playlist_name=obj[i].name.substr(0,26);
				else
					playlist_name = obj[i].name;
				strOutput+= "<a href='/"+section_name+"/show/"+obj[i].name+"-"+obj[i].menu_id+"' style='color:#FFF'><li>"+playlist_name+"</li></a>";


			}
			if(obj.length<17) {
				var diff=17 - obj.length;
				for(i=obj.length;i<17;i++){
					if(i>0 && i%5)
						strOutput+="</ul><ul class='top-menu'>";
					strOutput+= "<li>&nbsp</li>";
				}
			}
			strOutput+="</ul>";
			$('#nav-sub-menu').html(strOutput);
		}
});

$(document).ready(function() {
		var browser_version=navigator.appVersion;
		if(browser_version.match("MSIE 7.0")=="MSIE 7.0"){
			$("#email_container").css("margin-left","-100px");
		}
		Heavy.updateMenuImage();
		Heavy.UpdateLoginStatus();
		Heavy.SearchBox.setup();

		$("#current_page").keypress(function (e){
				var code = (e.keyCode ? e.keyCode : e.which);
				if(code==13){
					var pageno=0;
					var lastpgae=0;
					lastpage=Number($("#last_page").val());
					pageno=Number($("#current_page").val());
					if(pageno>=1 && pageno<=lastpage)
						location.href=$("#page_url").val()+pageno;
					else
						alert("Please enter valid page no");
				}
		});

		$("#current_page_bottom").keypress(function (e){
				var code = (e.keyCode ? e.keyCode : e.which);
				if(code==13){
					var pageno=0;
					var lastpgae=0;
					lastpage=Number($("#last_page").val());
					pageno=Number($("#current_page_bottom").val());
					if(pageno>=1 && pageno<=lastpage)
						location.href=$("#page_url").val()+pageno;
					else
						alert("Please enter valid page no");
				}
		});
		/* commented this code as we are not using any more email collection header*/
		/*$("#email_collection").blur(function() {
		if($("#email_collection").val()=="")
		$("#email_collection").val("enter email");
		});*/

		// add extra BR for firefox
		if(browser_version.match("MSIE")!="MSIE") {
			$("#top-menu-br").html('<br clear="all"/>');
		}


		$(".rollover").hover(
			function() {
				if($(this).attr("src").indexOf("-hover") == -1) {
					var newSrc = $(this).attr("src").replace(".png", "-hover.png");
					$(this).attr("src",newSrc);
				}
			},
			function() {
				if($(this).attr("src").indexOf("-hover.png") != -1) {
					var oldSrc = $(this).attr("src").replace("-hover.png", ".png");
					$(this).attr("src",oldSrc);
				}
				if(window.location==current_url && $('#section').val()==undefined){
					$("#home_logo").attr('src','/media/images/nav/nav-logo-hover.png');
				}
			});



		// set default text in search box
		$("#query-box").click(function() {
				if($("#query-box").val() == "Search") {
					$("#query-box").val("");
				}
		});

		$("#invis-button").click(function() {
				if($("#query-box").val()=="Search"){
					alert("Please enter keyword to search");
					$("#query-box").focus();
					return false;
				}else{
					$("#search-form").submit();
				}
		});

		$("#search-form").submit(function() {
				var query_box_val =  $("#query-box").val();
				query_box_val = query_box_val.replace(/[^a-zA-Z 0-9]+/g,'');
				query_box_val = query_box_val.replace(/\s/g,'+');

				var section=$('#section').val();

				if(section!=null && section !=""){
					document.location.href="/search/q/" + query_box_val + "/tag/" + section;
				}
				else {
					document.location.href="/search/q/" + query_box_val;
				}
				return false;
		});
});

//Google Analytics init of tracker...
/**
* Function to track the video events. This function is called  from video player
* @param  act video events like start, stop, 10% video complete, etc
* @param  label video id
* @return none
*/
function ga_playerEventTracker(act, label) {
	/* for the dj hero campaign */
	if (label == "76362")	{
	//URL call on click of a video
	switch (act) {
		case "VideoStart":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=516&type=2371&r=heavy.com&s=heavy.com");
			break;
		case "VideoComplete":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=516&type=2372&r=heavy.com&s=heavy.com");
			break;
		}
	}
	else if (label == "76594")	{
	//URL call on click of a video
	switch (act) {
		case "VideoStart":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=551&type=2603&r=heavy.com&s=heavy.com");
			break;
		case "VideoComplete":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=551&type=2604&r=heavy.com&s=heavy.com");
			break;
		}
	}
	// Sky Sports (the92) http://heavy.com/video/the92couk-intro-video-76810 Video ID: 76810
	else if (label == "76810")	{
	//URL call on click of a video
	switch (act) {
		case "VideoStart":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=450&type=2371&r=heavy.com&s=heavy.com");
			break;
		case "VideoComplete":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=450&type=2372&r=heavy.com&s=heavy.com");
			break;
		}
	}
	// Fruit Shoot http://heavy.com/video/coolest-tricks-from-our-expert-fruit-shoot-kid-76809 Video ID: 76809
	else if (label == "76809")	{
	//URL call on click of a video
	switch (act) {
		case "VideoStart":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=422&type=2371&r=heavy.com&s=heavy.com");
			break;
		case "VideoComplete":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=422&type=2372&r=heavy.com&s=heavy.com");
			break;
		}
	}
	// Gap Xmas http://heavy.com/video/bringing-you-cheer-this-christmas-love-gap-76817 Video ID: 76817
	else if (label == "76817")	{
	//URL call on click of a video
	switch (act) {
		case "VideoStart":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=544&type=12682&r=heavy.com&s=heavy.com");
			break;
		case "VideoComplete":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=544&type=12683&r=heavy.com&s=heavy.com");
			break;
		}
	}
	// Bet Fair (Mike's Question) http://heavy.com/video/mikes-big-question-betfair-front-room-76813 Video ID: 76813
	else if (label == "76813")	{
	//URL call on click of a video
	switch (act) {
		case "VideoStart":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=525&type=13492&r=heavy.com&s=heavy.com");
			break;
		case "VideoComplete":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=525&type=13493&r=heavy.com&s=heavy.com");
			break;
		}
	}
	// Vodaphone (Henry Holland) http://heavy.com/video/henry-holland-builds-his-own-house-of-holland-76815 Video ID: 76815
	else if (label == "76815")	{
	//URL call on click of a video
	switch (act) {
		case "VideoStart":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=542&type=13705&r=heavy.com&s=heavy.com");
			break;
		case "VideoComplete":
			$('#PlayerTrackerImg').attr("src","http://eisenstein.dk/loader/img.php?a=542&type=13706&r=heavy.com&s=heavy.com");
			break;
		}
	}

	var cat = "VideoPlayer";
	var opt = "";

	ga = (!pageTracker) ? ga_getTracker() : pageTracker;
	pageTracker._trackEvent(cat, act, label); //, opt);
}

function ga_getTracker(str) {
	var ga_id = (str) ? str : ga_appId; //"UA-1995064-1";
	var pageTracker = _gat._getTracker(ga_id);
	return pageTracker;
	return null;
}

var pageTracker = ga_getTracker(google_app_id);
pageTracker._trackPageview();


var shareWindow = {
	height: 980,
	width: 940,
	positionType:'absolute',
	positionTop:10,
	positionLeft:400,
	draggable: 1,
	eventType:'click',
	windowSource:'iframe',
	windowPadding:4,
	loader:1,
	loaderImagePath:'/media/images/ajax_wait.gif',
	loaderHeight:16,
	loaderWidth:17
}

function shareWindowPopup(url) {

	var defaultWidth = 970;
	var defaultHeight = 800;
	var windowHeight = ($(window).innerHeight() < defaultHeight) ? $(window).innerHeight() - 30 : defaultHeight;
	var windowWidth = ($(window).innerWidth() < defaultWidth) ? $(window).innerWidth() - 20 : defaultWidth;
	var positionTop = ($(window).innerHeight()  - windowHeight) /3;
	var positionLeft = ($(window).innerWidth()  - windowWidth) /2 - 14;

	var shareWindow = {
		height: defaultHeight,
		width: defaultWidth,
		positionType:'absolute',
		positionTop: positionTop,
		positionLeft: positionLeft,
		draggable: 1,
		eventType:'click',
		windowSource:'iframe',
		windowPadding:4,
		loader:1,
		loaderImagePath:'/media/images/ajax_wait.gif',
		loaderHeight:16,
		loaderWidth:17
	}

	$(".share").attr('href', url);
	$(".share").openDOMWindow(shareWindow);
	$(".share").click();
}

function shareWindowPopup2(url) {
	var defaultWidth = 970;
	var defaultHeight = 800;
	var windowHeight = ($(window).innerHeight() < defaultHeight) ? $(window).innerHeight() - 30 : defaultHeight;
	var windowWidth = ($(window).innerWidth() < defaultWidth) ? $(window).innerWidth() - 20 : defaultWidth;
	var positionTop = parseInt(($(window).innerHeight()  - windowHeight) /3);
	var positionLeft = parseInt(($(window).innerWidth()  - windowWidth) /2 - 14);

	//alert(url); return;

	options = 'toolbar=0, menubar=0, location=0, height=' + windowHeight + ', width=' + windowWidth + ', top=' + positionTop + ', scrollbars=yes, status=yes, resizable=true, left=' + positionLeft;
	//window.open(url, "test");
	window.open(url, "share", options);
}

function shareEmail(section,url) {
	//Added this check for call that is done from player
	if(typeof(section)=="undefined"){
		section="video";
	}
	subject = escape("Check out this Heavy.com "+section+"!");
	if(url==undefined)
		body = escape("Hey there,\r\n\r\nTake a look at this "+section+" I saw on Heavy.com\r\n" + current_url + "\r\n");
	else
		body = escape("Hey there,\r\n\r\nTake a look at this "+section+" I saw on Heavy.com\r\n" + url + "\r\n");
	document.location = 'mailto:?subject='+subject+'&body='+body;
}

function shareFacebook(url) {
	if(typeof(url)=='undefined')
		shareWindowPopup2("http://www.facebook.com/share.php?u=" + escape(current_url));
	else
		shareWindowPopup2("http://www.facebook.com/share.php?u=" + escape(url));

}

function shareTwitter(url) {
	//cur_url = escape(current_url);
	if(typeof(url)=='undefined'){
		var status = "Check+out+this+link+" + current_url + "+from+Heavy.com!";
	}else{
		var  status = "Check+out+this+link+" + url + "+from+Heavy.com!";
	}
	shareWindowPopup2("http://www.twitter.com/home?status=" + status);
}

function shareMySpace(url) {
	//shareWindowPopup("http://www.myspace.com/Modules/PostTo/Pages/?u=" + current_url + "&t=Check+out+this+link+from+Heavy.com&c=testing");
	cur_url = escape(current_url);
	var title = escape("Check+out+this+link+from+Heavy.com");
	descr = "";
	if (typeof(shortDescr) != 'undefined') descr = shortDescr;
	if(typeof(url)=="undefined")
		shareWindowPopup2("http://www.myspace.com/Modules/PostTo/Pages/?u=" + cur_url + "&t=" + title + "&c=" + descr);
	else
		shareWindowPopup2("http://www.myspace.com/Modules/PostTo/Pages/?u=" + escape(url) + "&t=" + title + "&c=" + descr);
}

function shareDigg(url) {
	cur_url = escape(current_url);
	var title = escape("Check+out+this+link+from+Heavy.com");
	if(typeof(url)=="undefined")
		shareWindowPopup2("http://digg.com/submit?phase=2&url=" + cur_url + "&t=" + title);
	else
		shareWindowPopup2("http://digg.com/submit?phase=2&url=" + escape(url) + "&t=" + title);
}

$(document).ready(function() {
		$(".share-email").click(function() {
				shareEmail('video');
		});

		$(".share-email-post").click(function() {
				shareEmail('post',$("#"+this.id).attr("myattr"));
		});
		$(".share-facebook").click(function() {
				if($("#"+this.id).attr("myattr")!="undefined")
					shareFacebook($("#"+this.id).attr("myattr"));
				else
					shareFacebook();
		});

		$(".share-twitter").click(function() {
				if($("#"+this.id).attr("myattr")!="undefined")
					shareTwitter($("#"+this.id).attr("myattr"));
				else
					shareTwitter();
		});

		$(".share-myspace").click(function() {
				if($("#"+this.id).attr("myattr")!="undefined")
					shareMySpace($("#"+this.id).attr("myattr"));
				else
					shareMySpace();
		});

		$(".share-digg").click(function() {
				if($("#"+this.id).attr("myattr")!="undefined")
					shareDigg($("#"+this.id).attr("myattr"));
				else
					shareDigg();
		});

		$(".share-email1").click(function() {
				popupwindow();
		});
});
