var boolRatingSubmitted = false;
var finalAvg;
var uRating;
var tiptext = "/"+appContext+"/"+"/newui/wiki/tooltip.jsp?width=140&";

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('&');
	}

};

/************ Implementatino ******************/
var ratings = new Array;
var id_prefix = "rating_star_";
var articleID = document.getElementById('documentId').value;
//var url_id = document.getElementById('rating_url');
var url;
var rating_username = document.getElementById('ratingUserId').value;
var site_rating = document.getElementById('siteRating').value;
var project_rating = document.getElementById('projectRating').value;
var page_owner = document.getElementById('pageOwner').value;
var totalRating = document.getElementById('totalRating').value;
var canRate = document.getElementById('canRate').value;
var userrated = document.getElementById('userrated').value;

/**
 * Use 'url_id' to retrieve url for image Gallery related resources
 * otherwise use 'window.location'
 */
//if (typeof(url_id) == 'undefined' || url_id == null ) {
    //url = window.location;
//} else {
	//url = url_id.value;
//}

/**
 * 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(rating_username == null || rating_username == '') {
	rating_username = 'Guest';
}

/**
 * Get partial url for the image
 */
var partialImgUrl = function(path) {
	return path.substr(0, (path.length - 5));
}
/**
 * Control a hovering action.
 */
function hoverRating(index,rating) {
	if(!boolRatingSubmitted){
		var i;
		ratings[0] = rating;
		for (z=1;z<=5;z++) {
			i = document.getElementById(id_prefix + 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) {
	var i;
	for (z=1; z<=5; z++) {
		i = document.getElementById(id_prefix + z);
		partial_img_src = partialImgUrl(i.getAttribute("src"));
		usei = partial_img_src + "0.gif"

		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);
	}
}

/**
 * For Generating alt tag text.
 */
var getImageAltText = function(index) {
	if(index<2) return document.getElementById(id_prefix + 1).getAttribute("alt")
	if(index<3) return document.getElementById(id_prefix + 2).getAttribute("alt")
	if(index<4) return document.getElementById(id_prefix + 3).getAttribute("alt")
	if(index<5) return document.getElementById(id_prefix + 4).getAttribute("alt")
	if(index<6) return document.getElementById(id_prefix + 5).getAttribute("alt")
	return "";
}

/**
 * To disable to submission.
 *		parameters: average = avg. rating.
 *					mode    = 1 (No more rating submission)
 *							= 2 (Already Submitted)
 */
function disableRatingSubmission(average,mode) {
	//alert("disableRatingSubmission("+average+", "+mode+")");
	var alt = getImageAltText(average);
	if(ckUtil_ratinginfo.getSubValue(articleID+'_r_') == null)
		uRating = average;
	else
		uRating = ckUtil_ratinginfo.getSubValue(articleID+'_r_');
	
var txt_ele = document.getElementById("rating_avg_txt");
// defense validation check
if (typeof (txt_ele) == "undefined" || typeof(uRating) == 'undefined') {
	return;
}
if(typeof (ratingData) != "undefined" && ratingData != null && ratingData != "" && ratingData[4] != "0" && ratingData[6] != "0")
{
	var before_avg = parseFloat(ratingData[4]);	
	var before_count = parseInt(ratingData[6]);
	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(ratingData[1]))
		finalAvg = ratingData[4]+'';
}
else
{
	finalAvg = average+'';
}

finalAvg = parseFloat(finalAvg).toPrecision(2);
var avgratingtext = generalMsgLocalizer.getMessage("label_rating_textsubmitrating");
var yourratingtext = generalMsgLocalizer.getMessage("label_rating_textusersubmitrating");
var totalratingtext = generalMsgLocalizer.getMessage("label_rating_texttotalrating");

	switch(mode){
		case 1 : break;
		case 2 : break;//alt = avgratingtext+"="+finalAvg+" (" + totalRating + " " + totalratingtext + "), "+yourratingtext+"="+uRating+"";break;
		default: alert("invalid argument");
	}

	var i;
    var tabIdx;
	var starImagerating = average;

    var submitted_rating = ckUtil_ratinginfo.getSubValue(articleID+'_r_');
	if(submitted_rating != null){
		//alert("Using stored rating.");
		average = submitted_rating;
	}


	for (itrz=1;itrz<=5;itrz++) {
		i = document.getElementById(id_prefix + itrz);
		tabIdx = document.getElementById(id_prefix + 'tab_' + itrz);
        

		partial_img_src=partialImgUrl(i.getAttribute("src"));
		
		if(itrz <= starImagerating)
			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("title",alt);
		i.setAttribute("alt",alt);
		i.setAttribute("class","star_inactive");

		if(tabIdx != null){
            tabIdx.setAttribute("href", tiptext+"ratingDiv=show&avgrating="+eval(finalAvg)+"&totrating="+totalRating+"&ratinguser="+rating_username+"&ratingpageowner="+page_owner+"&userrating="+uRating+"&userrated="+userrated+"&");			
			tabIdx.setAttribute("class", "jTip");
            tabIdx.setAttribute("onfocus", null);
			tabIdx.setAttribute("onclick", null); //Disable click on rest of the stars
            if(itrz == 1 || itrz == 5)
            tabIdx.setAttribute("onblur", null);
        }

	}

	changeRatingSnippet(average);
}

 /**
  * Return "true" if the user has already submitted the rating, otherwise false.
  */
var isSubmitted = function(articleID){
	//alert("isSubmitted("+articleID+")");
	if(rating_username == ckUtil_ratinginfo.getSubValue('username') && articleID == ckUtil_ratinginfo.getSubValue("'"+articleID+"'")){
		//alert("username = "+ckUtil_ratinginfo.getSubValue('username')+" isSubmitted()= true");
		return true;
	} else{
		//alert("Username = "+rating_username+" isSubmitted()= false");
	    return false;
	}
}

/**
 * Store the value in a cookie.
 */
var insertSubValuesInCookie = function(rating){
	//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_'));
}

/**
 * Submit rating
 */
function submitRating(rating) {
	try{
		boolRatingSubmitted = true;

		if(typeof(rating_username) == 'undefined' || rating_username == null || rating_username == "guest")
			rating_username = 'Guest';
		var full_url = siteContext+'newui/wiki/rating.jsp?&docID='+articleID+'&userRating='+rating+'&username='+rating_username;
		//alert(full_url);
		ahCalls.createAhCall('scriptTag', full_url, 'jsonObject', '', false);
		
		// call this if the average star(s) are shown after submission.
		//disableRatingSubmission(ratingData[3],2);

		// Call this if the user submit rating is shown after submission.
		disableRatingSubmission(rating,2);
		

		insertSubValuesInCookie(rating);
		
		
		
	} catch (e) {
		//alert("Error while submitting rating.");
	}
}

/**
 * Calculates and Renders the Average Snippet after rating submission.
 */
function changeRatingSnippet(rating) {

	try	{
		var txt_ele = document.getElementById("rating_avg_txt");
		// defense validation check
		if (typeof (txt_ele) == "undefined" || rating == null || rating == "") {
			return;
		}
		var snippet = txt_ele.innerHTML;
		if(typeof (ratingData) != "undefined" && ratingData != null && ratingData != "" && ratingData[4] != "0" && ratingData[6] != "0"){
			var before_avg = parseFloat(ratingData[4]);
			var before_count = parseInt(ratingData[6]);
			var after_count = before_count + 1;
			var mulNum = before_avg *  before_count;
			var addNum = parseInt(mulNum) + parseInt(rating);
			var after_avg = addNum/after_count;
			after_avg = after_avg.toPrecision(2);

			snippet = "<strong>Avg. Rating:</strong> "+ after_avg +" / 5 ("+(after_count)+" ratings)";

		} else {
			snippet = '<strong>Avg. Rating:</strong> '+ rating +' / 5 (1 ratings)';
		}
		//alert(snippet);
		//txt_ele.innerHTML = snippet; //Also to show the snippet you need to change the width in wiki_rating_js.html -> .rating{float:left;width:280px;} and .rating table tr td p {width:190px;}
		//Also add JUST after first <TR> in wiki_rating_js.html ratingData object - <td class='rating_label'><p id='rating_avg_txt'><strong>Avg. Rating</strong>: $AVERAGE_RATING / 5 ($TOTAL_RATING ratings)</p></td>

		txt_ele.innerHTML = ""; // For not showing the snippet. Uncomment the above line to show the snippet.

	}
	catch (e) {
		 //alert(e);
		// do nothing
	}
}

/**
 * Logic to Renders the Rating UI.
 */

// Global Default: true = enable, false = disable.

var isDefaultOn = true;
var rating_avg = document.getElementById('rating_avg');
//var ratingData = null;

/** 
 * Grab a data pretaining to the articleID,
 * if it doesn't exist, keep as a null.
 */
//try	{
	//ratingData = eval('ratingData');
//
//catch (e) {
    //alert(e);	 
//}

if(isDefaultOn){
	//alert("Global Default is ON");
		if(typeof (ratingData) != "undefined" && ratingData != null && ratingData != ""){
			if(site_rating == 'Y'&& project_rating == 'Y'){
					//alert("Avg and Submission are both enable.");
					rating_avg.innerHTML=ratingData[5];
					// Disable if it is already submitted.
					if(isSubmitted(ratingData[1])){
						disableRatingSubmission(ratingData[4],2);
					}					
						//Disable rating for Guest user - Start
						if(typeof(rating_username) == 'undefined' || rating_username == null || rating_username == "guest" || rating_username == page_owner)
					    {
							for (itrz=1;itrz<=5;itrz++)
							{
								var i;
								var starImagerating = parseFloat(ratingData[4]);
								var alt = getImageAltText(itrz);
								i = document.getElementById(id_prefix + itrz);
								tabIdx = document.getElementById(id_prefix + 'tab_' + itrz);


								partial_img_src=partialImgUrl(i.getAttribute("src"));
								usei = partial_img_src + "0.gif";
								
								if(itrz <= starImagerating)
									usei = partial_img_src + "2.gif";
								else
								{
									if(starImagerating > (itrz-1))
										usei = partial_img_src + "8.gif";
								}

								i.setAttribute("src", usei);
								i.setAttribute("onmouseover", null);
								i.setAttribute("onmouseout", null);
								i.setAttribute("onclick", null);
								i.setAttribute("title",alt);
								i.setAttribute("alt",alt);
								i.setAttribute("class","star_inactive");

								if(tabIdx != null){									
									tabIdx.setAttribute("href", tiptext+"ratingDiv=show&avgrating="+eval(starImagerating)+"&totrating="+totalRating+"&ratinguser="+rating_username+"&ratingpageowner="+page_owner+"&userrated="+userrated+"&");
									tabIdx.setAttribute("class", "jTip");
									tabIdx.setAttribute("onfocus", null);
									if(rating_username == page_owner)
										tabIdx.setAttribute("onclick", null); //Page owner cannot rate his own page
									if(canRate == "no")
										tabIdx.setAttribute("onclick", null); //Check permission for guest to rate the page
									if(itrz == 1 || itrz == 5)
									tabIdx.setAttribute("onblur", null);
								}
							}
						}
						//Disable rating for Guest user - End
			} 
		} else {
			//article level js doesn't exist.
			if(ratingSiteData[1] == "Y"){
				rating_avg.innerHTML=ratingSiteData[3];

				// Disable if it has been already submitted.
				if(isSubmitted(articleID)){
					disableRatingSubmission(0,2);
				}
			} else {
				//alert("Site Level disable");
			}
		}
} else {
	//alert("Global Default is OFF.");
}

