/*
Page:           rating.js
Created:        Aug 2006
Last Mod:       Mar 11 2007
Handles actions and requests for rating bars.	
--------------------------------------------------------- 
ryan masuga, masugadesign.com
ryan@masugadesign.com 
Licensed under a Creative Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/
See readme.txt for full credit details.
--------------------------------------------------------- */

var g_base_url = "/includes/star_rating";
//var g_base_url = "/webs/stars";

var xmlhttp
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	  try {
	  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
	 } catch (e) {
	  try {
	    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	  } catch (E) {
	   xmlhttp=false
	  }
	 }
	@else
	 xmlhttp=false
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined')
	{
	 try
	 {
	  xmlhttp = new XMLHttpRequest();
	 }
	 catch (e)
	 {
	  xmlhttp=false
	 }
	}
	function myXMLHttpRequest()
	{
	  var xmlhttplocal;
	  try
	  {
	    xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
	 	}
	 	catch (e)
	 	{
	  	try
	  	{
	    	xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
	  	}
	  	catch (E)
	  	{
	    	xmlhttplocal=false;
	  	}
	 	}

		if (!xmlhttplocal && typeof XMLHttpRequest!='undefined')
		{
			try
			{
				var xmlhttplocal = new XMLHttpRequest();
			}
			catch (e)
			{
				var xmlhttplocal=false;
			  alert('couldn\'t create xmlhttp object');
			}
		}
		return(xmlhttplocal);
	}

function sndReq(vote,id_num) {
	var theUL = document.getElementById('unit_ul'+id_num); // the UL
	
	// switch UL with a loading div
	theUL.innerHTML = '<img src="/images/loading.gif" />';

	//debug
	//alert("submitting to: " + g_base_url+'/rating.php?j='+vote+'&q='+id_num+'&rpc=1');

  xmlhttp.open('get', g_base_url+'/rating.php?j='+vote+'&q='+id_num+'&rpc=1');
  xmlhttp.onreadystatechange = handleResponse;
  xmlhttp.send(null);	
}

function sendReq(sUrl,loadingId)
{
	var oLoadingEl = document.getElementById(loadingId);
	if(oLoadingEl != null)
		oLoadingEl.innerHTML = '<img src="/images/loading.gif" />';

	xmlhttp.open('get', sUrl);
	xmlhttp.onreadystatechange = handleResponse;
	xmlhttp.send(null);	
}

function postReq(sUrl,oForm,loadingId)
{
	var oLoadingEl = document.getElementById(loadingId);
	if(oLoadingEl != null)
		oLoadingEl.innerHTML = '<img src="/images/loading.gif" />';

	var oEl, i = 0, parameters = "";
	while(oEl = oForm.elements[i++])
	{
		if((oEl.type == "checkbox" || oEl.type == "radio") && !oEl.checked)
			continue;

		if(parameters.length > 0)
			parameters += "&";
		parameters += oEl.name + "=" + encodeURI(oEl.value);
	}

  xmlhttp.open('post', sUrl);
  xmlhttp.onreadystatechange = handleResponse;
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.setRequestHeader("Content-length", parameters.length);
  xmlhttp.setRequestHeader("Connection", "close");
  xmlhttp.send(parameters);
}

function sndEmailFriendReq(form) {
	var id = form.q.value;
	var fromname = form.fromname.value;
	var toname = form.toname.value;
	var toemail = form.toemail.value;
	var vote = form.vote.value;

	var theUL = document.getElementById('send_long'+id); // the UL

	// switch UL with a loading div
	theUL.innerHTML = '<div class="loading"></div>';
	
  xmlhttp.open('get', g_base_url+'/rating.php?q='+id+'&fromname='+fromname+'&toname='+toname+'&toemail='+toemail+'&vote='+vote+'&rpc=1');
  xmlhttp.onreadystatechange = handleResponse;
  xmlhttp.send(null);	
}

function handleResponse()
{
  if(xmlhttp.readyState == 4)
  {
		if (xmlhttp.status == 200)
		{
      var response = xmlhttp.responseText;
			var iSplit = response.indexOf("|");
			if(iSplit >= 0)
			{
				var objId = response.substr(0,iSplit);
				var newText = response.substr(iSplit + 1);
				var funcName = "";

				iSplit = objId.indexOf(",");
				if(iSplit >= 0)
				{
					funcName = objId.substr(iSplit + 1);
					objId = objId.substr(0,iSplit);
				}

				changeText(objId, newText);
				initOverLabels();

				if(isFunction(funcName))
					window[funcName]();
			}
		}
	}
}

function isFunction(name)
{
	if(name.length <= 0)
		return false;

	var obj = eval(name);
  return (typeof obj == 'object' && obj != null) || typeof obj == 
'function'; 
}

function changeText( div2show, text ) {
		//debug
		//alert(text);
	document.getElementById(div2show).innerHTML = text;
	/*
    // Detect Browser
    var IE = (document.all) ? 1 : 0;
    var DOM = 0; 
    if (parseInt(navigator.appVersion) >=5) {DOM=1};

    // Grab the content from the requested "div" and show it in the "container"
    if (DOM) {
        var viewer = document.getElementById(div2show);
        viewer.innerHTML = text;
    }  else if(IE) {
        document.all[div2show].innerHTML = text;
    }
	*/
}

function initOverLabels () {
  if (!document.getElementById) return;      

  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // labels with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {

    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      } 

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to label elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}

/* =============================================================== */
var ratingAction = {
		'a.rater' : function(element){
			element.onclick = function(){
                        
                       
			var parameterString = this.href.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2');
			var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2');
			var parameterList = new Array();

			for (j = 0; j < parameterTokens.length; j++) {
				var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
				var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1
				parameterList[parameterName] = parameterValue;
			}
			var theratingID = parameterList['q'];
			var theVote = parameterList['j'];
                        $(this).parent().parent().find('a').removeClass('curr').removeClass('temp');
                        $(this).parent().prevAll().find('a').addClass('curr');
                        $(this).addClass('curr');
                        $('#vote_btn').show();
                        $('#vote_btn').unbind('click');
                        if (!$(this).hasClass('video_vote')) {
                          $('#vote_btn').bind('click', function(){
                            sndReq(theVote,theratingID); return false;  
                          });
                        } else {
                          $('#vote_btn').bind('click', function(){
                            voteWorks(theVote,theratingID); return false;  
                          });
                        }                        
                        
                        
                        $(".rating_ul").unbind('hover').hover(
                          function () {
                            $(this).find('a.curr').addClass('temp').removeClass('curr');
                          }, 
                          function () {
                            $(this).find('a.temp').addClass('curr');
                          }
                        );
  
  
			//console.log($(this));
//			alert('sndReq('+theVote+','+theratingID+','+theuserIP+','+theunits+')'); 

                        return false;
			//sndReq(theVote,theratingID); return false;		
			}
		}
		
	};
Behaviour.register(ratingAction);

