var tempX = 0;
var tempY = 0;  

var IMG_ROOT = 'http://components.myrrhworship.com/style/common/images/';
var STARBAR_IMG_ROOT = IMG_ROOT + 'stars/';
var SONGSHARE_SET_PAGE = '/myrrh/songshare/rating';
var SONGSEARCH_SET_PAGE = '/myrrh/admin/songsearch/rate';

var STAR_CRD_MAX_1 = 13; 
var STAR_CRD_MAX_2 = 26;
var STAR_CRD_MAX_3 = 39;
var STAR_CRD_MAX_4 = 52;
var STAR_CRD_MAX_5 = 65;

var WIDGET_TYPE_SONG_STD = 2;

// Rollover Stars - We will preload these
var USERSTARS = [
	STARBAR_IMG_ROOT + "1_00.png",
	STARBAR_IMG_ROOT + "1_10.png",
	STARBAR_IMG_ROOT + "1_20.png",
	STARBAR_IMG_ROOT + "1_30.png",
	STARBAR_IMG_ROOT + "1_40.png",
	STARBAR_IMG_ROOT + "1_50.png"
];

var ALT_SONG_1 = "Click to rate this song \"Hate It\"";
var ALT_SONG_2 = "Click to rate this song \"Don\'t Like It\"";
var ALT_SONG_3 = "Click to rate this song \"Like It\"";
var ALT_SONG_4 = "Click to rate this song \"Really Like It\"";
var ALT_SONG_5 = "Click to rate this song \"Love It\"";

var ALT_SONG_STATIC_1 = "Hate It";
var ALT_SONG_STATIC_1 = "Don\'t Like It";
var ALT_SONG_STATIC_1 = "Like It";
var ALT_SONG_STATIC_1 = "Really Like It";
var ALT_SONG_STATIC_1 = "Love It";

var ALT_GENERIC = "Star Rating For Song";

var CLEAR_RATING = "clear";
var NO_OPINION = "noseen";
var NOT_INTERESTED = "norec";
    
var RATING_1 = 1;
var RATING_2 = 2;
var RATING_3 = 3;
var RATING_4 = 4;
var RATING_5 = 5;

var W_OBJ_PFX = "w";
var SB_OBJ_PFX = "st";
var NO_OBJ_PFX = "no";
var NI_OBJ_PFX = "ni";
var NIM_OBJ_PFX = "nm";
var CR_OBJ_PFX = "cr";

var STD_STARBAR_SRC = STARBAR_IMG_ROOT + WIDGET_TYPE_SONG_STD + "_"; //performance optimization

function preloadStarRollover() {
	
     userStar	= new Image();
	 spinner	= new Image();
	 
	// start preloading Stars...
	for(var i = 0; i < USERSTARS.length; i++) {
		userStar.src = USERSTARS[i];
	}
	 
	// .. and the Spinner
	spinner.src = IMG_ROOT + "spinner.gif";
} 

// Run that preloader
preloadStarRollover();


function wR(widgetId, wType, wRating, wMethod) {  //Widget REGISTER
    
    widget = document.getElementById(W_OBJ_PFX + widgetId);
    if (widget.registered == null) {
        widget.registered = true;
        
        widget.widgetId = widgetId;
        widget.onmouseout = doRestore;
        
        
        starbar = document.getElementById(SB_OBJ_PFX + widgetId);
   
        if (starbar) {
            widget.starbar = true;
            starbar.widgetId = widgetId;
            starbar.widgetType = wType;
            starbar.restorePath = starbar.src;
            starbar.onmouseup = doStarCommit;
            starbar.onmousemove = doStarRollover;
            starbar.onmouseout = doMouseout;
            starbar.prediction = wRating;
			starbar.method = wMethod;
        }
    } 
}

function doRestore(evt) {

    var widgetId = this.widgetId;
    setTimeout('restoreWidget("' + widgetId + '", false)', 10);
}

function restoreWidget(widgetId, starDelayActive) {

    widget = document.getElementById(W_OBJ_PFX + widgetId);
	
    if (widget.starbar) {
        if (starDelayActive) {
            setTimeout('restoreWidget("' + widgetId + '", ' + !starDelayActive + ')', 100);
            
        } else {
            starbar = document.getElementById(SB_OBJ_PFX +  widgetId);
            if (starbar && !starbar.active ) {
                starbar.src = starbar.restorePath;
                starbar.offsetX = null;
            }
        }
    }

}

function setRating(widgetType, widgetId, value, method) {
	var url;
	var callback;
	var rc	= "ratingcount_" + widgetId;
	
	switch (method) {
		
		case "songsearch":
			url =	SONGSEARCH_SET_PAGE + "?";
			url +=	"songSearchIdentifier=" + widgetId;
			url +=	"&songSearchRating=" + value;
			callback = songsearchCallback;
			break;
			
		case "songshare":
			url =	SONGSHARE_SET_PAGE + "?";
			url +=	"id=" + widgetId;
			url +=	"&rating=" + value;
			callback = songshareCallback;
			break;
		
		default:
			url =	"";
			callback = "";
			break;
	}

	if (url != "") {
		callServer(url, callback, false, false, widgetId);
	}
	
	// Start the spinner over the rating count.
	if (document.getElementById && document.getElementById(rc)) {
		var n = document.getElementById(rc);
		var t = n.removeChild(n.firstChild);
		var s = document.createElement("img");
		s.src = IMG_ROOT + "spinner.gif";
		s.setAttribute("title","Recording your rating...");
		n.appendChild(s);
	}
	
}

function doStarCommit(evt) { 
    this.active = true;
    var starValue = getCurrentStarValue(evt, this);
    this.restorePath = this.src;
    notim = document.getElementById(NIM_OBJ_PFX + widgetId);
	noti = document.getElementById(NI_OBJ_PFX + widgetId);
	clrr = document.getElementById(CR_OBJ_PFX + widgetId);
	if (noti) {
        noti.src = STARBAR_IMG_ROOT + "/ni_low.png";
        noti.restorePath = noti.src;
    } else if (notim) {
    	notim.src = NOTIM_OFF;
        notim.restorePath = notim.src;
    }
	resetClear(false, this.widgetId);
    setRating(this.widgetType, this.widgetId, starValue, this.method);
    
} 

function doButtonCommit(evt) { 

    this.active = true;
    this.restorePath = this.src;
    var widgetId = this.widgetId;

	clickValue = this.clickvalue;
	
    starbar = document.getElementById(SB_OBJ_PFX + widgetId);
    

    if (clickValue == CLEAR_RATING) { 
        starbar.src = STD_STARBAR_SRC + starbar.prediction + ".png"

        this.restorePath = STARBAR_IMG_ROOT + "clear_unavailable.png";
		this.cleared = true;
        
    }
	
	if (clickValue != NOT_INTERESTED) {

		noti = document.getElementById(NI_OBJ_PFX + widgetId);
		notim = document.getElementById(NIM_OBJ_PFX + widgetId);
		if (noti) {
	        noti.src = STARBAR_IMG_ROOT + "/ni_low.png";
	        noti.restorePath = noti.src;
	    } else if (notim) {
    		notim.src = NOTIM_OFF;
        	notim.restorePath = notim.src;
    	}
		resetClear(true, widgetId);
	}
    
	starbar.restorePath = starbar.src;
    
    setRating(this.widgetType, widgetId, clickValue, this.method);
    
} 

function resetClear(isCleared, widgetId) {
	 clrr = document.getElementById(CR_OBJ_PFX + widgetId);
	 if (clrr) {
	 	clrr.cleared = isCleared;
		clrr.src = STARBAR_IMG_ROOT + "/clear_low.png";
        clrr.restorePath = clrr.src;
	 }
}


function doCrRollover() {
    if (!this.cleared) {
		this.active = true;
	    this.alt, this.title = "Clear Rating";
	    this.src = STARBAR_IMG_ROOT + "clear_high.png";
	    starbar = document.getElementById(SB_OBJ_PFX + this.widgetId);
	    starbar.active = true;
	    starbar.src = STD_STARBAR_SRC + starbar.prediction + ".png"   
	}
}

function doMouseout() {
    this.active=false;
    var widgetId = this.widgetId;
    starbar = document.getElementById(SB_OBJ_PFX + widgetId);  
    starbar.active = false;
}

function getCurrentStarValue(evt, curEmt) {
    var xC = -1;  
    if (!evt) var evt = window.event;
    
    if (evt.offsetX) {
        xC = evt.offsetX;
    } else if (curEmt.offsetX != null) {
        eXC = curEmt.offsetX;
        xC = evt.layerX - eXC;
    } else if (evt.layerX) {
        eXC = getElementOffsetX(curEmt);
        xC = evt.layerX - eXC;
        curEmt.offsetX = eXC;
    }
    
    if (xC <= STAR_CRD_MAX_1) return 1;   
    else if (xC <= STAR_CRD_MAX_2) return 2;
    else if (xC <= STAR_CRD_MAX_3) return 3;
    else if (xC <= STAR_CRD_MAX_4) return 4;
    else if (xC <= STAR_CRD_MAX_5) return 5;
    else return 0;
}

function doStarRollover(evt) {
   
    this.active = true;
    widgetId = this.widgetId;
    noti = document.getElementById(NI_OBJ_PFX + widgetId);
    notim = document.getElementById(NIM_OBJ_PFX + widgetId);
    noop = document.getElementById(NO_OBJ_PFX + widgetId);
    
    if (noti) {
        noti.active = true;
        noti.src = NOTI_OFF;
    } else if (notim) {
    	notim.active = true;
        notim.src = NOTIM_OFF;
    }
    if (noop) noop.src = NOOP_OFF;
    restoreWidget(this.widgetId, false);
    var starValue = getCurrentStarValue(evt, this);

    this.src    =  STARBAR_IMG_ROOT + "1_" + starValue + "0.png";
    setAltText(this, starValue);
    
    

}  

function setAltText(starbar, value) {
    var widgetType = starbar.widgetType;
    var starValue = value;
    
    switch (widgetType) {
        default:
            switch (value) {
                case 1: starbar.alt, starbar.title = ALT_SONG_1; break;
                case 2: starbar.alt, starbar.title = ALT_SONG_2; break;
                case 3: starbar.alt, starbar.title = ALT_SONG_3; break;
                case 4: starbar.alt, starbar.title = ALT_SONG_4; break;
                case 5: starbar.alt, starbar.title = ALT_SONG_5; break;
            
                default: starbar.alt, starbar.title = ALT_GENERIC; break;
            }       
        break;
    }
    
}

/* Computes the total horizontal offset of a node, the sum of the enclosing objects' horizontal offset. */
function getElementOffsetX(element) {
    var totalOffset = 0;
    if (element.offsetLeft != null) {
        totalOffset += element.offsetLeft;
        while (element.offsetParent) {
            totalOffset += element.offsetParent.offsetLeft;
            element = element.offsetParent;
        }
    }
    return totalOffset;
}

/* Computes the total vertical offset of a node, the sum of the enclosing objects' vertical offset. */
function getElementOffsetY(element) {
	var totalOffset = 0;
	if (element.offsetTop != null) {
        totalOffset += element.offsetTop;
		while (element.offsetParent) {
			totalOffset += element.offsetParent.offsetTop;
			element = element.offsetParent;
		}
	}
	return totalOffset;
}

function StarbarFillInAll() {}




// ========================================================================
//
//	xmlHttpRequest Functions
//
// ========================================================================

var calls					= new Array();
var pendingResponseCount	= 0;
var shouldDebugAjax			= false;

// The callback of xmlHttpRequest is a dynamically-generated function which
// immediately calls this function.
function onResponseStateChange(callKey) {

	call = calls[callKey];
	xmlHttpRequest = call.xmlHttpRequest;
	
	if (xmlHttpRequest.readyState < 4) { //Still waiting
		return;
	}
	
	if (xmlHttpRequest.readyState == 4) { //Transmit to actual callback
		if (shouldDebugAjax) {
			alert("Call " + callKey + " with context [" + call.callingContext + "]"
				+ " to " + call.url + " has returned.");
		}
		
		callbackFunction = call.callbackFunction;
		
		if (!callbackFunction) { // Possibly still loading, e.g. in another JS file
			//eval('f = function() { onResponseStateChange(' + i + '); }');
			//setTimeout(f, 100); // TODO break if too many timeouts
		}
		
		try {
			if (shouldDebugAjax) {
				alert("Response Text:	" + xmlHttpRequest.responseText);
			}
			if (call.isPlainTextResponse) {
				callbackFunction(xmlHttpRequest.responseText, call.callingContext);
			} else {
				callbackFunction(xmlHttpRequest.responseXML, call.callingContext);
			}
		} catch(e) {
		  alert(e.number);
		}
	}
	// and if readyState > 4, error occurred. So we'll still dispose it...
	// (is this right? might still need it due to redirects?)
	
	call = null; // Technically the GC's responsibility
	delete calls[callKey];
	pendingResponseCount--;

}

// Browser-agnostic factory function
function createXMLHttpRequest() {
	var xmlHttpRequest;
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		return new ActiveXObject('Microsoft.XMLHTTP')
	}
}

function callServer(url, callbackFunction, isPlainTextResponse, shouldGET, callingContext, vars) {

	if (shouldDebugAjax) {
		alert("callServer() called. About to request URL\n"
			+ "call key: [" + calls.length + "]\n"
			+ "url: [" + url + "]\n"
			+ "callback function: [" + callbackFunction + "]\n"
			+ "returns plaintext?: [" + isPlainTextResponse + "]\n"
			+ "use GET protocol?: [" + shouldGET + "]\n"
			+ "calling context: [" + callingContext + "]\n"
			+ "vars: [" + vars + "]");
	}

	var xReq = createXMLHttpRequest();
	
	callKey = "" + calls.length;
	call = {
		xmlHttpRequest:		xReq,
		callbackFunction:		callbackFunction,
		isPlainTextResponse:	isPlainTextResponse,
		callingContext:		callingContext,
		url:					url
	};
	calls[callKey] = call;
	
	eval('f = function() { onResponseStateChange(' + callKey + '); }');
	xReq.onreadystatechange = f;
	
	var requestStyle = shouldGET ? "GET" : "POST";
	xReq.open(requestStyle, url, true);
	if( !vars ) {
		xReq.send(null);
	} else {
		var varsString = "";
		for( key in vars ) {
			varsString += '&' + key + '=' + vars[key];
		}
		if (shouldDebugAjax) {
			alert(varsString);
		}
		varsString = varsString.substring(1); // chomp initial '&'
		
		xReq.setRequestHeader('Content-Type',
		'application/x-www-form-urlencoded; charset=UTF-8');
		xReq.send(varsString);	
	}
}


// ========================================================================
//
//	Callback Functions
//
// ========================================================================

function songshareCallback() {
	
	var args	= songshareCallback.arguments;
	var rxml	= args[0];
	var sid		= args[1];
	var rcn		= "ratingcount_" + sid;
	var arn		= "averagerating_" + sid;
	var rca		= rxml.getElementsByTagName("numberOfRatings");
	var rc		= document.createTextNode(rca[0].firstChild.nodeValue);
	var ara		= rxml.getElementsByTagName("averageRating");
	var ar		= Number(ara[0].firstChild.nodeValue);
	
	if (document.getElementById) {
		// Update the rating Count
		if (document.getElementById(rcn)) {
			// Remove the spinner
			var n = document.getElementById(rcn);
			var t = n.removeChild(n.firstChild);
			// Update the count
			n.appendChild(rc);
		}
		// Update the average rating starbar if need be
		if (document.getElementById(arn)) {
			var n = document.getElementById(arn);
			// Find the original image
			for (var x = 0; x < n.childNodes.length; x++) {
				var c = n.childNodes[x];
				if (c.nodeType == 1 && c.nodeName == "IMG") {
					break;
				}
			}
			// Get on with it.
			var t	= n.removeChild(c);
			var a	= document.createElement("img");
			var ars	= String(ar * 10);
			ars		= (ars.indexOf('.') > -1) ? ars.substring(0,ars.indexOf('.')) : ars;
			
			a.src = STD_STARBAR_SRC + ars + ".png";
			a.className = "star";
			a.setAttribute("alt", ar + " Stars");
			a.setAttribute("title", ar + " Stars");
			n.appendChild(a);
		}
	}
}

function songsearchCallback() {}