var boolRatingSubmitted = false;
var finalAvg;
var uRating;
var tiptext = "/"+appContext+"/"+"/newui/blog/tooltip.jsp?width=140&ratingDiv=show&";

var ahCalls = {
	
	theReturnType:null,
	called:false,
	queryStr:null,
	counter:0,
	scriptTagCallBackFunction:null,
	scriptTagJsonType:null,
	
	createAhCall:function(httpType,url,returnType,callBackFunction,params,proxyPath)
	{
		if(!document.getElementById || !document.createTextNode){return;}
		this.theReturnType = returnType;
		
		if(httpType != 'scriptTag'){//is not using script tag
			this.queryStr = (!params) ? null : encodeURIComponent(params);
			var xmlHttp = ahCalls.createXmlHttpObject();
			if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){// proceed only if the xmlHttp object isn't busy
				
				xmlHttp.onreadystatechange = function(){// define the method to handle server responses
				
					switch(xmlHttp.readyState){
						case 1: if(!this.called){/*alert('waiting on server!');*/this.called = true} break;
						case 2: break;
						case 3: break;
						case 4:
							if ( xmlHttp.status == 200 ){// only if "OK"
								try{
									responseObj = ahCalls.parseXmlHttpResponse(xmlHttp);
									success = true;
								}catch(e){ 
									alert('Parsing Error: The value returned could not be evaluated.');
									success = false;
								}
								if(success) callBackFunction( responseObj ); //if all is good send the response to the callback function
							}else{ 
								alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
							}
							break;
					}
				}
				
				if(httpType == 'get' || httpType == 'post'){
					xmlHttp.open(httpType, ahCalls.noCache(url), true);
				}else{
					if(httpType == 'proxyGet'){
						xmlHttp.open('get', (proxyPath+'?path='+(encodeURIComponent(url))), true);
					};
					if(httpType == 'proxyPost'){
						xmlHttp.open('put', (proxyPath+'?path='+(encodeURIComponent(url))), true);
					};
				}
				
				if(params){xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8")};
				xmlHttp.send(this.queryStr);// make the server request and send queryStr or null as an argument
				
			}else{// if the connection is busy, try again after one second 
				setTimeout('ahCalls.createAhCall();', 1000);
			}
		}else{//using scriptTag
			this.scriptTagCallBackFunction = callBackFunction;
			if(returnType == 'jsonObject' || returnType == 'jsonString'){//getting json return via script tag
			    //alert('jsonObject or jsonString');
				ahCalls.JsonXmlScriptRequest(ahCalls.noCache(url+'&callback=ahCalls.JsonXmlScriptHandleRequest'));
			}else{//getting xml return via script tag
				var xmlPath = encodeURIComponent(url);
				ahCalls.JsonXmlScriptRequest(proxyPath+'?path='+xmlPath);
			}
		}	
	},
	
	createXmlHttpObject:function()
	{
		var ahCalls; // will store the reference to the XMLHttpRequest Object
		
		try{
			ahCalls = new XMLHttpRequest();// this should work for all browsers except IE6 and older
		}catch(e){
			var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP');
			for (var i=0; i<XmlHttpVersions.length && !ahCalls; i++) {
				try { 
					// try to create XMLHttpRequest object
					ahCalls = new ActiveXObject(XmlHttpVersions[i]);
				}catch (e) {}
			}
		}
		
		if(!ahCalls){alert("Error creating the XMLHttpRequest Object.")}else{return ahCalls};// return the created object or display an error message		
	},
	
	JsonXmlScriptRequest:function(fullUrl)
	{
		//alert('Inside JsonXmlScriptRequest()');
		ahCalls.counter += 1;
		var scriptId = 'JscriptId' + ahCalls.counter;
		
		var scriptObj = document.createElement("script");// Create the script tag
		
    	scriptObj.setAttribute("type", "text/javascript");   // Add script object attributes
		scriptObj.setAttribute("charset", "utf-8");
		scriptObj.setAttribute("src", fullUrl);
		scriptObj.setAttribute("id", scriptId);
		
		var headLoc = document.getElementsByTagName("head").item(0);
		headLoc.appendChild(scriptObj);
	},
	
	JsonXmlScriptHandleRequest:function(jsonData)
	{
		//alert('Inside JsonXmlScriptHandleRequest()');
		switch(ahCalls.theReturnType) {
		case "xmlObject": var xmlDataObject = ahCalls.xmlTextToObject(jsonData); ahCalls.scriptTagCallBackFunction(xmlDataObject);break;
		case "xmlString": ahCalls.scriptTagCallBackFunction(jsonData); break;
		case "jsonObject": ahCalls.scriptTagCallBackFunction(jsonData); break;
		case "jsonString": /*var jsonDataString = jsonData.toJSONString();ahCalls.scriptTagCallBackFunction(jsonDataString);*/ break;
		default: 
			// if there is no case "*" match, execute this code
			alert("error")
		};
		
		var scriptElement;
		for (var i = 1; i < 10; i++) {
			scriptElement = document.getElementById('JscriptId' + i);
			if(scriptElement){
			document.getElementsByTagName("head")[0].removeChild(scriptElement);
			}
		}
	},
	
	parseXmlHttpResponse:function(responseObject){
		var theType = ahCalls.theReturnType;
		if(theType != 'proxyPost' || theType != 'proxyGet'){//local xhr call
			switch(theType) {
			case "string": return responseObject.responseText; break;
			case "xmlObject": return responseObject.responseXML; break;
			case "xmlString": return responseObject.responseText; break;
			case "jsonObject": return responseObject.responseText.parseJSON();break;
			case "jsonString": return responseObject.responseText; break;
			default: 
				// if there is no case "*" match, execute this code
				alert("error")
			}
		}else{
			switch(theType) {//cross domain xhr to proxy and then back again
			case "xmlObject": return responseObject.responseXML; break;
			case "xmlString": return responseObject.responseText; break;
			case "jsonObject": return responseObject.responseText.parseJSON();break;
			case "jsonString": return responseObject.responseText; break;
			default: 
				// if there is no case "*" match, execute this code
				alert("error")
			}
		}
	},
	
	xmlTextToObject:function(text){
		if (typeof DOMParser != "undefined") {
		// Mozilla, Firefox, and related browsers
		return (new DOMParser()).parseFromString(text, "application/xml");
		}
		else if (typeof ActiveXObject != "undefined") {
			// Internet Explorer.
			var doc = new ActiveXObject("MSXML2.DOMDocument");  // Create an empty document
			doc.loadXML(text);            // Parse text into it
			return doc;                   // Return it
		}
		else {
			// As a last resort, try loading the document from a data: URL
			// This is supposed to work in Safari.
			var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text);
			var request = new XMLHttpRequest();
			request.open("GET", url, false);
			request.send(null);
			return request.responseXML;
		}
	},
	
	noCache:function (url){
		//alert('Inside noCache()');
		var qs = new Array();
		var arr = url.split('?');
		var scr = arr[0];
		if(arr[1]) qs = arr[1].split('&');
		qs[qs.length]='nocache='+new Date().getTime();
		//alert(scr+'?'+qs.join('&'));
		return scr+'?'+qs.join('&');
	}

};

var rating_username = document.getElementById('ratingUserId').value;
var boolRatingSubmitted = false;
var ratings = new Array;
var id_prefix = "rating_star_";
var tiptext = "/"+appContext+"/"+"/newui/blog/tooltip.jsp?width=140&ratingDiv=show&";


/**
 * Cookies util 
 */
var ckUtil_visitorinfo =  new CJL_CookieUtil("visitorinfo",0,"/","");
//IF IT IS LOCAL HOST THEN KEEP THE LAST ARGUMENT EMPTY, OTHERWISE ADD THE DOMAIN NAME
//Cookie will be stored for only 1 sec and user can rate the page again Replaced 1440*90 by 1/60. Fix for Bug 35247.
var ckUtil_ratinginfo  =  new CJL_CookieUtil("samepage_ratinginfo_"+rating_username,1/60,"/",""); //TODO : put the apporiate TTL in min.
//if the "visitorinfo" exists, extract a value for a username.
if(ckUtil_visitorinfo.cookieExists()){
	//alert("ratinginfo exists");
	rating_username = ckUtil_visitorinfo.getSubValue("name");
} 

//IF IT IS LOCAL HOST THEN KEEP THE LAST ARGUMENT EMPTY, OTHERWISE ADD THE DOMAIN NAME
//Cookie will be stored for only 1 sec and user can rate the page again Replaced 1440*90 by 1/60. Fix for Bug 35247.
//var ckUtil_ratinginfo  =  new CJL_CookieUtil("samepage_ratinginfo_"+rating_username,1/60,"/",""); //TODO : put the apporiate TTL in min.

/**
 * Submit rating
 */
function submitRating(rating,articleID,total,average,owner) {
	try{
		boolRatingSubmitted = true;
		
		if(typeof(rating_username) == 'undefined' || rating_username == null || rating_username == "guest")
			rating_username = 'Guest';
		var full_url = siteContext+'newui/blog/rating.jsp?&docID='+articleID+'&userRating='+rating+'&username='+rating_username;
		
		ahCalls.createAhCall('scriptTag', full_url, 'jsonObject', '', false);
		
		// Call this if the user submit rating is shown after submission.
		disableRatingSubmission(average,2,articleID,total,rating,owner);
		
		insertSubValuesInCookie(rating,articleID);
		
		//showCookieValues(articleID);
		
	} catch (e) {
		//alert("Error while submitting rating.");
	}
}

function showCookieValues(articleID)
{
	/*if(ckUtil_ratinginfo.getSubValue(articleID+'_r_') == null)
		uRating = average;
	else
		uRating = ckUtil_ratinginfo.getSubValue(articleID+'_r_');

	for (z=1;z<=5;z++) {
			i = document.getElementById(id_prefix + articleID+ "_" + z);
	}*/
}

/**
 * Control a hovering action.
 */
function hoverRating(index,rating,postId) {
	if(!boolRatingSubmitted){
		var i;
		ratings[0] = rating;
		for (z=1;z<=5;z++) {
			i = document.getElementById(id_prefix + postId+ "_" + z);
			partial_img_src = partialImgUrl(i.getAttribute("src"));
			if (z <= index) {
				usei = partial_img_src + "2.gif";
			} else {
				usei = partial_img_src + "3.gif";
			}
			i.setAttribute("src", usei);
		}
	}
}

/**
 * Controls an unhovering action.
 */
function unhoverRating(index, upostId) {
	var i;
	for (z=1; z<=5; z++) {
		i = document.getElementById(id_prefix + upostId+ "_" + z);
		partial_img_src = partialImgUrl(i.getAttribute("src"));
		usei = partial_img_src + "0.gif"
	//	usei = (ratings[0] >= z) ? partial_img_src + "1.gif" : partial_img_src + "7.gif";
		// changes made by Suyog to show blue half stars
		// if condition is for showing full star and eles condition is used for half star
		if (ratings[0] >= z)
			usei = partial_img_src + "1.gif"
		else
		{
			if(ratings[0] > (z-1))
				usei = partial_img_src + "7.gif"
		}
		i.setAttribute("src", usei);
	}
}


/**
 * Get partial url for the image
 */
var partialImgUrl = function(path) {
	return path.substr(0, (path.length - 5));
}

function disbleRating(articleID,articleOwner)
{
	//alert(articleID);
	//alert(articleOwner);
	if(isSubmitted(articleID,articleOwner))
	{
		//alert("true");
		//disableRatingSubmission(avgRating,2,articleID,total,articleOwner);
		for (itrz=1;itrz<=5;itrz++) {
			i = document.getElementById(id_prefix + articleID+ "_" + itrz);
			i.setAttribute("onmouseover", null);
			i.setAttribute("onmouseout", null);
			i.setAttribute("onclick", null);
			i.setAttribute("class","star_inactive");

			tabIdx = document.getElementById(id_prefix + 'tab_' + articleID+ "_" + itrz);
			if(tabIdx != null){
				tabIdx.setAttribute("onfocus", null);
				tabIdx.setAttribute("onclick", null); //Disable click on rest of the stars
				tabIdx.setAttribute("onblur", null);
			}

		}
	}
}

/**
  * Return "true" if the user has already submitted the rating, otherwise false.
  */
var isSubmitted = function(articleID,articleOwner){
	//alert("isSubmitted("+articleOwner+")");
	if(rating_username == articleOwner){
		//alert("username = "+ckUtil_ratinginfo.getSubValue('username')+" isSubmitted()= true");
		return true;
	} else{
		//alert("Username = "+rating_username+" isSubmitted()= false");
	    return false;
	}
}


/**
 * To disable to submission.
 *		parameters: average = avg. rating.
 *					mode    = 1 (No more rating submission)
 *							= 2 (Already Submitted)
 */
function disableRatingSubmission(average,mode,articleID,total,rating,owner) {
	if(ckUtil_ratinginfo.getSubValue(articleID+'_r_') == null)
		uRating = rating;
	else
		uRating = ckUtil_ratinginfo.getSubValue(articleID+'_r_');

	if(average != "0" && total != "0")
	{
		var before_avg = parseFloat(average);	
		var before_count = parseInt(total);
		var after_count = before_count + 1;
		var mulNum = before_avg *  before_count;
		var addNum = parseInt(mulNum) + parseInt(uRating);
		var after_avg = addNum/after_count;
		after_avg = after_avg.toPrecision(2);
		finalAvg = after_avg+'';
		if(isSubmitted(articleID,owner))
		finalAvg = average+'';
	}
	else
	{
		finalAvg = rating+'';
	}
	finalAvg = parseFloat(finalAvg).toPrecision(2);
	if(!(isSubmitted(articleID,owner)))
		total = total+ 1;
	
	for (itrz=1;itrz<=5;itrz++) {
		i = document.getElementById(id_prefix + articleID+ "_" + itrz);
		//i = document.getElementById(id_prefix + itrz);
		tabIdx = document.getElementById(id_prefix + 'tab_' + articleID+ "_" + itrz);
		//tabIdx = document.getElementById(id_prefix + 'tab_' + itrz);
        partial_img_src=partialImgUrl(i.getAttribute("src"));
		if(itrz <= rating)
		{
			usei = partial_img_src + "6.gif";
		}
		else
		{
			usei = partial_img_src + "0.gif";
		}
		
		i.setAttribute("src", usei);
		i.setAttribute("onmouseover", null);
		i.setAttribute("onmouseout", null);
		i.setAttribute("onclick", null);
		i.setAttribute("class","star_inactive");

		if(tabIdx != null){
			//tabIdx.setAttribute("href", tiptext+"avgrating="+eval(finalAvg)+"&totrating="+totalRating+"&ratinguser="+rating_username+"&ratingpageowner="+"suyog"+"&userrated="+userrated+"&");			
			tabIdx.setAttribute("href", tiptext+"avgrating="+finalAvg+"&totrating="+total+"&ratinguser="+rating_username+"&ratingpageowner="+owner+"&userrated="+uRating+"&");			
			tabIdx.setAttribute("onfocus", null);
			tabIdx.setAttribute("onclick", null); //Disable click on rest of the stars
            tabIdx.setAttribute("onblur", null);
			
        }

	}

	//changeRatingSnippet(average);
}

/**
 * Store the value in a cookie.
 */
var insertSubValuesInCookie = function(rating,articleID){

	//alert("insetSubValueInCookie() articleID = "+articleID+" rating = "+rating);
	ckUtil_ratinginfo.setSubValue("username",rating_username);
	ckUtil_ratinginfo.setSubValue("'"+articleID+"'",articleID);
	ckUtil_ratinginfo.setSubValue(articleID+'_r_',rating);
	//alert("Checking : "+articleID +" = "+ckUtil_ratinginfo.getSubValue("'"+articleID+"'")+" Rating = "+ckUtil_ratinginfo.getSubValue(articleID+'_r_'));
}