
var _isIE = window.navigator.userAgent.indexOf("MSIE") > -1;
var _isChrome = window.navigator.userAgent.indexOf("Chrome") > -1;
var _isFF = window.navigator.userAgent.indexOf("Firefox") > -1;
var _isSafari = window.navigator.userAgent.indexOf("Apple") > -1;
var _isOpera = window.navigator.userAgent.indexOf("Opera") > -1;

function resize_Window(width, height) {
	/*
    if (window.moveTo)
    {
        window.moveTo(0,0);
    }
    */
	window.resizeTo(width, height);
	resize_FlashMovie(width, height);
}

function open_In_Full_Size(){
	window.resizeTo(window.screen.availWidth, window.screen.availHeight);
	resize_FlashMovie(window.screen.availWidth, window.screen.availHeight);
}

function resize_FlashMovie(width, height){
	obj = document.getElementById("ObjectForFlash");
	if(obj && obj.style) {
		obj.style.width = width;
		obj.style.height = height;
	}
}
function SetFocusToControl(id){
	if(id && id != ""){
		obj = document.getElementById(id);
		if(obj && obj.focus){
			obj.focus();
		}
	}
}

function processing(obj, div_id) {
    div_id = div_id || 'popupConfirmation';
	var obj1 = null;
	obj1 = document.getElementById("ProcessingMessage");
	if(obj1 && obj1.style){
		obj1.style.display = "block";
	}
	//window.setTimeout("document.getElementById('Button2').disabled = true", 100);
	scrollTo(0,0);
	//showPopup(div_id, 600);
	showRCPopup(div_id);
	return false;
	//For .Net 1.1
	if (typeof(Page_ClientValidate) == 'function') {
		if(Page_ClientValidate()){
			obj1 = document.getElementById("ProcessingMessage");
			if(obj1 && obj1.style){
				obj1.style.display = "block";
			}
			window.setTimeout("document.getElementById('Button2').disabled = true", 100);
		}
	}
	//For .Net 2.0
	if (typeof(ValidatorOnSubmit) == "function") {
		if(ValidatorOnSubmit()) {
			obj1 = document.getElementById("ProcessingMessage");
			if(obj1 && obj1.style){
				obj1.style.display = "block";
			}
			window.setTimeout("document.getElementById('Button2').disabled = true", 100);
		}
	} 

}

function updatePass(val){
	obj = document.getElementById("Password");
	if(obj) obj.value = val;
	obj = document.getElementById("Password1");
	if(obj) obj.value = val;
}

function trimspaces(obj){
	if(obj && obj.value){
	    obj.value = obj.value.replace(/^\s+|\s+$/g, '');
	}
}

function ToggleClass(oid, class1, class2){
	obj = document.getElementById(oid);
	if(obj && obj.className){
		if(obj.className.indexOf(class1) != -1){
			obj.className = obj.className.replace(class1, class2);
		}
		else if(obj.className.indexOf(class2) != -1){
			obj.className = obj.className.replace(class2, class1);
		}
	}
}

function ChangeImage(oid, newimg){
	obj = document.getElementById(oid);
	if(obj && obj.src){
		obj.src= newimg;
	}
}


/* Added to check for FireFox */
function checkFF(){
	ver = navigator.userAgent;
	if(ver.indexOf("Firefox") > 0 ){
		var objHead = document.getElementsByTagName('head');
		if (objHead[0])
		{
			if (document.createElementNS && objHead[0].tagName == 'head')
				var objCSS = objHead[0].appendChild(document.createElementNS('http://www.w3.org/1999/xhtml', 'link'));
			else
				var objCSS = objHead[0].appendChild(document.createElement('link'));
			objCSS.id = 'ffstyle';
			objCSS.rel = 'stylesheet';
			objCSS.href = 'FFStyles.css';
			objCSS.type = 'text/css';
		}
	}
}
//checkFF();

function submitEmail(obj_btn){
	
	//var obj = obj_btn.parentNode.parentNode.getElementById("submit_email");
	var obj = obj_btn.parentNode.parentNode.getElementsByTagName("INPUT")[0];
	var obj1 = obj_btn.parentNode.parentNode.getElementsByTagName("INPUT")[0];
	if(obj && obj1){
		f = document.forms[0];
		f.signup_email.value= obj.value;
		//f.invitation_code.value = obj1.value;
		f.submit();
	}
	
}

function SetJobCompleted(id){
	var hdn = document.getElementById("hdnJobID");
	var act = document.getElementById("formaction");
	
	if(hdn && act){
		act.value = "job_completed";
		hdn.value = id;
		hdn.form.submit();
	}
}

function checkMaxJobs(obj){
	return;
	if(!obj || !obj.options) return;
	if(parseInt(obj.options[obj.selectedIndex].value, 10) > 10){
		obj.selectedIndex = 9;
		var temp = document.getElementById("NoOfTesters_Err");
		if(temp && temp.style && temp.style.display){
			temp.style.display = "inline";
		}
	} else {
		var temp = document.getElementById("NoOfTesters_Err");
		if(temp && temp.style && temp.style.display){
			temp.style.display = "none";
		}
	}
}

function checkMaxJobsForPromo(obj, num){
	var n = num ? num : 1;
	if(!obj || !obj.options) return;
	if(parseInt(obj.options[obj.selectedIndex].value, 10) > n){
		selectValue(obj, n);
		//obj.selectedIndex = 0;
		var temp = document.getElementById("NoOfTesters_Err1");
		temp.innerHTML = "This promotional offer is limited to a test with "+ n +" tester"+ (n > 1 ? "s" : "") +".<br>";
		if(temp && temp.style && temp.style.display){
			temp.style.display = "inline";
		}
	} else {
		var temp = document.getElementById("NoOfTesters_Err1");
		temp.innerHTML = "";
		if(temp && temp.style && temp.style.display){
			temp.style.display = "none";
		}
	}
}


var rate_num = 0;
function loadBar(num_passed) {
	var num = num_passed == undefined ? rate_num : num_passed;
	rate_num = num;
	var obj = null;
	if(num > 0){
		for(var i =1; i<= num; i++){ 
			obj = document.getElementById("img" + i);
			if(obj){
				obj.src = "../images/star2.gif";
				obj.onclick = rate;
				obj.onmouseover = function () { setImageUpto(this); };
				obj.alt = "";
				obj.style.margin = "0px";
				obj.style.marginTop = "3px";
			}
		}
		for(var i = num+1; i<= 5; i++){ 
			obj = document.getElementById("img" + i);
			if(obj){
				obj.src = "../images/star1_1.gif";
				obj.onclick = rate;
				obj.onmouseover = function () { setImageUpto(this); };
				obj.alt = "";
				obj.style.margin = "0px";
				obj.style.marginTop = "3px";
			}
		}
	} else {
		for(var i = 1; i <= 5; i++){
			obj = document.getElementById("img" + i);
			if(obj){
				obj.src = "../images/star1_1.gif";
				obj.alt = "rate " + i;
				obj.onclick = rate;
				obj.onmouseover = function () { setImageUpto(this); };
				obj.style.margin = "0px";
				obj.style.marginTop = "3px";
			}
		}
	}
}

function setImageUpto(obj){
	var upto = parseInt(obj.id.replace(/img/g, ""), 10);
	upto = upto >= rate_num ? upto : rate_num; 
	var fill = "../images/star2.gif";
	var empty = "../images/star1_1.gif";
	for(var i = 1; i <= upto; i++){
		document.getElementById("img" + i).src = fill;
	}
}

function rate(evt) {
	var e = evt ? evt : window.event;
	var obj = e.srcElement ? e.srcElement : e.target;
	var id = obj.id.replace(/img/g,"");
	
	var url = "../RateVideo.aspx?";
	var data = window.location.search;
	data = data.substring(1);
	data += "&rate=" + escape(id);
	
	GetResponse(url, function() {
		var div = document.getElementById("rating_bar");
		div.innerHTML = "Saving now. Please wait...";
		if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			var resp = xmlHttp.responseText;
			var cnt;
			try {
				cnt = parseInt(resp,10);
				loadBar(cnt);
				div.innerHTML = "Saved";
				window.setTimeout(function() { document.getElementById("rating_bar").innerHTML = ""; }, 3000);
			} catch(e) {
				div.innerHTML = "Some error. Please try again.";
			}
		}
	}, data);
}

function save_rating_reason(evt){
	var e = evt ? evt : window.event;
	var id = document.getElementById("reason_for_rating").value;
	
	var url = "../RateVideo.aspx?";
	var data = window.location.search;
	data = data.substring(1);
	data += "&reason=" + escape(id);
	
	GetResponse(url, function() {
		var div = document.getElementById("rating_bar");
		div.innerHTML = "Saving now. Please wait...";
		if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			var resp = xmlHttp.responseText;
			if(resp == "saved" || resp == "-"){
				div.innerHTML = "Saved";
				window.setTimeout(function() { document.getElementById("rating_bar").innerHTML = ""; }, 3000);
			} else {
				div.innerHTML = "Some error. Please try again." + resp;
			}
		}
	}, data);
}

var xmlHttp=null;

function GetXmlHttpObject() {
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		//Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function GetResponse(url, callback, postdata){
	GetXmlHttpObject();
	if(xmlHttp == null){
		alert("Your browser doesn't support AJAX.");
	} else {
		url = url + "&" + +Math.random();
		if(postdata == undefined) {
			xmlHttp.onreadystatechange = callback;
			xmlHttp.open("GET", url, true);
			xmlHttp.send(null);
		} else {
			xmlHttp.onreadystatechange = callback;
			xmlHttp.open("POST", url, true);
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", postdata.length);
			xmlHttp.setRequestHeader("Connection", "close");
			xmlHttp.send(postdata);
		}
	}
}

function selectValue(sel, val){
	if(sel != undefined && sel.options != undefined){
		for(var i  =0 ; i < sel.options.length-1; i++){
			if(sel.options[i].value == val){
				sel.options[i].selected = true;
				break;
			}
		}
	}
}

function updateRating(obj, r, i, ver_no, hideReasonPopup){
	rating_s = r;
	ver_no = ver_no ? ver_no : "";
	hideReasonPopup = (hideReasonPopup == 1);
	var d_v = $(obj).parent().parent();
	d_v.get(0).old_html = d_v.html();
	d_v.html("Rate Tester(<a onclick=\"OpenRateTesterPopup('Popups/RateVideo.aspx')\" href='javascript:void(0)'>?</a>)<br />Loading..wait..");
	d_v.load((ver_no == "" ? "" : "../") + "popups/ajax/updateRating.aspx", { rate: r, name: i, ver: ver_no }, function(responseText, textStatus, XMLHttpRequest) {
	    if (responseText == "error") {
	        $(this).html(this.get(0).old_html);
	    } else {
	        $(this).html(responseText);
	        if (ver_no != "") {
	            var curr_Bar = this;
	            var all_not_useful_stars = jQuery("a[title='Not Useful']");
	            jQuery.each(all_not_useful_stars, function(i, val) {
	                if (jQuery(val).parent() != curr_Bar) {
	                    jQuery(val).parent().html(responseText);
	                }
	            });
	        }
	        var win_par = window.opener;
	        if (win_par != undefined) {
	            if (win_par.location.href.toLowerCase().indexOf("youraccountclient.aspx") > 0) {
	                if (win_par.rating_given != undefined) {
	                    win_par.rating_given(i, r);
	                }
	            }
	        }
	        if (win_par != undefined && win_par.location.href.toLowerCase().indexOf("youraccount.aspx") > 0) {
	            win_par.location.href = "/youraccount.aspx";
	        }
	        var PanelForViddler = jQuery("[id$='PanelForViddler']").eq(0);
	        if (OpenRateTesterPopup != undefined && PanelForViddler.html() == null && !hideReasonPopup) {
	            OpenRateTesterPopup((ver_no == "" ? "" : "../") + 'Popups/reasonRate.aspx?id=' + i);
	        } $("#div_rating").html($(gPopup).get(0).innerHTML);
	        if (PanelForViddler.html() != null && rating_given) rating_given();
	    }
	});
}

function updateMask(obj, i, path_sel) {
    if (obj == undefined || i == undefined) return;
    var path = (path_sel == undefined || path_sel == "" ? "" : "../") + "popups/ajax/updateRating.aspx";
    $.ajax({
        type: "POST",
        url: path,
        data: { name: i, act: "update_mask", mask: obj.checked ? 1 : 0 },
        cache: false,
        success: function(_data, textStatus) {
            if (_data.indexOf("error") == 0) {
                alert("Error while updating. Please try again.");
            }
        }
    });
}

var rating_s = 0;
var reason_t = "";
function load_reason(i, ver_no){
	ver_no = ver_no ? ver_no : "";
	var path = (ver_no == "" ? "" : "../popups/") + "ajax/UpdateReason.aspx";
	$.ajax({
		type:"GET",
		url:path,
		data:{name: i, act: "get"},
		cache: false,
		success: function (data, textStatus) {
					if(data.indexOf("error:") == 0){
						$("#lblErrorMsg").html(data.replace("error:",""));
					} else {
						reason_t = unescape(data);
					}
				}
	});
}

function save_reason(i, ver_no){
	ver_no = ver_no ? ver_no : "";
	var path = (ver_no == "" ? "" : "../popups/") + "ajax/UpdateReason.aspx";
	var res = escape($("#reason_text", $(gPopup)).get(0).value);
	var mask = $("#reasonmask", $(gPopup)).get(0).checked ? 0 : 1;
	reason_t = res;
	$.ajax({
		type:"POST",
		url:path,
		data:{name: i, act: "set", reason: res, mask: mask},
		cache: false,
		success: function (data, textStatus) {
					if(data.indexOf("error:") == 0){
						$("#lblErrorMsg", $(gPopup)).html(data.replace("error:",""));
					} else {
						$("#lblErrorMsg", $(gPopup)).html("Saved successfully");
					    //$("#lblErrorMsg", $(gPopup)).html("Thank you for your comments.").addClass("SuccessMessage");
					    remove_reason_popup(); 
					    remove_popup();
						$("#reasonmask").val([(mask == 0 ? "reasonmask" : "")]);
					}
				}
	});
}

function save_hau(){
	var path = "popups/ajax/UpdateHau.aspx"
	var d = escape($("#heard_about_us").get(0).value);
	var i = escape($.cookie('uid'));
	if(d == ""){
		$("div.MyAccount_WelcomeBox").hide();
	}
	/*
	alert(d + " - " + i);
	*/
	$.ajax({
		type:"POST",
		url:path,
		data:{name: i,txt: d},
		cache: false,
		success: function (data, textStatus) {
					if($("div.MyAccount_WelcomeBox").html() != null){
						$("div.MyAccount_WelcomeBox").hide();
					}
				}
	});
}
function loadGADataInPage(){
	var z = document.cookie;
	var s = escape(_uGC(z, 'utmcsr=', '|'));
	var m = escape(_uGC(z, 'utmcmd=', '|'));
	var t = escape(_uGC(z, 'utmctr=', '|'));
	var co = escape(_uGC(z, 'utmcct=', '|'));
	var ca = escape(_uGC(z, 'utmccn=', '|'));
	var i = escape($.cookie('uid'));
	var gaw_data= {
		source: s,medium: m,term: t,content: co,campaign: ca, name: i
	};
	var d = document;
	for(var obj in gaw_data){
		var i = d.createElement("INPUT");
		i.name = "_" + obj;
		i.id = "_" + obj;
		i.type = "hidden";
		i.value = gaw_data[obj];
		document.forms[0].appendChild(i);
	}
}

function updateGAData(){
	var path = "popups/ajax/UpdateGA.aspx"
	var z = document.cookie;
	var s = escape(_uGC(z, 'utmcsr=', '|'));
	var m = escape(_uGC(z, 'utmcmd=', '|'));
	var t = escape(_uGC(z, 'utmctr=', '|'));
	var co = escape(_uGC(z, 'utmcct=', '|'));
	var ca = escape(_uGC(z, 'utmccn=', '|'));
	var i = escape($.cookie('uid'));
	if(i && i != "null"){
		$.ajax({
			type:"POST",
			url:path,
			data:{source: s,medium: m,term: t,content: co,campaign: ca, name: i},
			cache: false,
			success: function (data, textStatus) {
						}
		});
	}
}
//if(!$("div").draggable) {
//	$.getScript("/jquery-ui-personalized-1.5.3.min.js");
//}
function showPopupDivForAlt(obj){
	if($(obj).parent){
		//showPopupDiv($(obj).parent().attr("title"));
		features = "toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes,width=400,height=200";
		var win = window.open("", "", features);
		win.document.open();
		win.document.write($(obj).parent().attr("title"));
		win.document.close();
	}
}

function showPopupDiv(msg){
	var pu_div = $("#popup_div");
	if(pu_div.length == 0){
		pu_div = document.createElement("div");
		$(pu_div)
			.attr("id","popup_div")
			.appendTo("body")
			.dialog({draggable: true, width: 400, title : "   Info  "})
		;
	}
	$(pu_div)
		.text(msg)
		.dialog("open");
}
var errors_shown = false;
var errs = [];
function show_errors(){
	if(!errs || !$(errs) || errors_shown) return;
	$(errs).each(function(i, o) {
		var tag = (!o.disp || o.disp == "inline" ? "span" : "div" );
		if(!o.pos || o.pos == "after") {
			$("#" + o.id).after( "<" + tag + " class='ErrorMessage'>&nbsp;" + o.msg + "</" + tag + ">");
		} else {
			$("#" + o.id).before( "<" + tag + " class='ErrorMessage'>&nbsp;" + o.msg + "</" + tag + ">");
		}
	});
	errors_shown = true;
}

function save_data(srv, container_obj, call_back){
	var path = "popups/ajax/UpdateService.aspx"
	/*
	var d = {};
	$(":input", container_obj).each(function(i, o){
	    if(o.name == "") return true;
	    if(o.type == "radio"){
	        if(o.checked) {
	            d[this.name] = $(this).val();
	         }
	    } else {
	        d[this.name] = $(this).val();
	    }
	});
	if($(":input", container_obj).length > 0){
    	d["uid"] = escape($.cookie('uid'));
    	d['srv'] = srv;
	}
	if(d["uid"] == ""){
		//$("div.MyAccount_WelcomeBox").hide();
		return;
	}
	*/
	var d = "uid=" + escape($.cookie('uid')) + "&srv=" + srv + "&";
	d += jQuery(".overlay_popup_container :input").serialize();
	/*
	return;
	*/
	$.ajax({
		type: "POST",
		url: path,
		data: d,
		cache: false,
		success: function (data, textStatus) {
					call_back();
				}
	});
}

/*
Function to set limit for html textbox controls.

obj : Object with properties showing id -> max_limit pair. 
Example: {textbox_id: 1000, textbox_id2: 500}

callback : (Optional) This will be fired for onfocus, onblur & onkeyup events 
for this textbox control. You can use this function to update the UI to show 
characters left. Three parameters are passed to this function. 
First- textbox control id .
Second - max limit set for this textbox control.
Third - Characters left.
*/
function setup_limit_for_textboxes(obj, callback) {
    jQuery.each(obj, function(i, val){
        $("#"+i).bind("keyup focus blur", {limit:val}, function(e){
            var diff = this.value.length - e.data.limit;
            if(diff > 0) {
                if(diff > 1 && e.type == "keyup"){
                    alert("Sorry, but your text entry has more than the " + e.data.limit + " characters that are allowed. Part of your text was cut off so you'll need to edit your entry and try again.");
                }
                this.value = this.value.substr(0, e.data.limit);
            }
            if(callback && typeof(callback) == "function"){
                callback(this.id, e.data.limit, (e.data.limit - this.value.length));
            }
        });
        $("#"+i).bind("keypress", {limit:val}, function(e){
            var k = e.charCode;
            var is_ansi = k > 0 && ! e.ctrlKey;
            if(is_ansi) {
                return (this.value.length + 1 <= e.data.limit);
            }
        });
    });
}


if (window["$"]) { 
	$(document).ready(function (){ show_errors(); }); 
}

function getQuestions1(qtext){
    if(qtext == "") return [];
    var qs = qtext
        .replace(/\n{2,}/g,"")
        .replace(/^[?:]$/g,"")
        .replace(/^[?:]\n$/g,"")
        .replace(/([?:])/g,"$1%%##%%")
        .replace(/\n+$/g, "")
        .replace(/(%%##%%)$/, "")
        .split("%%##%%");
    __qs =qs;
    return qs;
}

function getQuestions(qtext, sep){
    if(qtext == "") return [];
    qtext = qtext.replace(/\n+/g,"").replace(new RegExp("(["+ sep +"])+","g"), "$1\n");
    var qs = qtext.split("\n");
    var temp = "";
    var ret = [];
    jQuery.each(qs, function(i, val) {
        temp = val.replace(new RegExp("^["+ sep +"\\n]+$","g"), "");
        if(temp != ""){
            ret[ret.length] = temp;
        }
    });
    return ret;
}
