
/**************** Rating ********************/
var AOLVideoSearch=function(appid){var xmlhttpUrl='http://xml.searchvideo.com/libs/xmlhttp';var serviceUrl="http://xml.searchvideo.com/apiv3";var sessionCookie=new Cookie(document,"aolvs_session_token",720);var stateCookie=new Cookie(document,"aolvs_api_state");var urlParams=null;var onUpdateHandlerArray=new Array();var onLoadHandlerArray=new Array();var onErrorHandlerArray=new Array();var errorMessages={'501':'Error connecting to XMLHTTP AJAX service','502':'Invalid AJAX method call: The wrong number of arguments was provided to this method.','503':'Method not available: You must be logged in to use this method.'};this.appid=appid;this.mode='ajax';this.method="";this.query="";this.querySuggestion="";this.previousQuery="";this.Result=null;this.submitRating=function(videoId,rating){if(arguments.length<2){this.onerror(502,errorMessages['502']);return(false);}
var urlParams={'method':'truveo.videos.submitRating','id':videoId,'rating':rating};this.submitRestQuery(urlParams,'ajax');return(true);}
this.attachEvent=function(eventName,handler){switch(eventName){case'onupdate':var index=onUpdateHandlerArray.length;onUpdateHandlerArray[index]=handler;break;case'onerror':var index=onErrorHandlerArray.length;onErrorHandlerArray[index]=handler;break;case'onload':var index=onLoadHandlerArray.length;onLoadHandlerArray[index]=handler;break;}
return(true);}
this.onupdate=function(methodName){for(var i=0;i<onUpdateHandlerArray.length;i++){eval(onUpdateHandlerArray[i]);}}
this.onerror=function(errorCode,errorMessage){for(var i=0;i<onErrorHandlerArray.length;i++){eval(onErrorHandlerArray[i]);}}
this.onload=function(reloadStateFlag){if(arguments.length<1)reloadStateFlag=false;if(reloadStateFlag==true){this.loadAPIState();}
for(var i=0;i<onLoadHandlerArray.length;i++){eval(onLoadHandlerArray[i]);}}
this.saveAPIState=function(){stateCookie.mode=this.mode;stateCookie.method=this.method;stateCookie.query=this.query;stateCookie.previousQuery=this.previousQuery;stateCookie.store();}
this.loadAPIState=function(){if(stateCookie.load()){this.mode=stateCookie.mode;this.method=stateCookie.method;this.query=stateCookie.query;this.previousQuery=stateCookie.previousQuery;stateCookie.remove();}}
this.update=function(xmlText){var xotree=new XML.ObjTree();xotree.force_array=["Video","Tag","Channel","Category","User","Watchlist"];var tree=xotree.parseXML(xmlText);if(tree&&("Response"in tree)){var response=tree.Response;if("Error"in response){this.onerror(response.Error["-Code"],response.Error["#text"]);}
else if(("method"in response)&&(response.method.indexOf("checkToken")>=0)&&response.Result&&response.Result.code){if(response.Result.code==1){this.onload();}
else{sessionCookie.remove();this.onload();}}else if(("method"in response)&&(response.method.indexOf("getToken")>=0)&&response.Result&&response.Result.token){sessionCookie.token=response.Result.token;if(response.Result.publicName){sessionCookie.publicName=response.Result.publicName;}
sessionCookie.store();this.onload(true);}else{var methodName='';if("method"in response){this.method=response.method;methodName=response.method.slice(response.method.lastIndexOf('.')+1);}
if("query"in response){this.previousQuery=this.query;this.query=response.query;}
if("querySuggestion"in response){this.querySuggestion=response.querySuggestion;}
if("Result"in response){this.Result=response.Result;}
this.onupdate(methodName);}}}
this.onXMLHTTPLoad=function(xmlhttp){this.update(xmlhttp.responseText);}
this.onXMLHTTPError=function(message){this.onerror(501,errorMessages['501']+"; "+message);}
this.submitRestQuery=function(urlParams,mode){var xmlhttp=new XMLHTTP();xmlhttp.setXMLHTTPURL(xmlhttpUrl);xmlhttp.registerCallback(this);xmlhttp.open("GET",this.getRestUrl(urlParams),true);xmlhttp.send(null);}
this.getRestUrl=function(urlParameters){var urlString=serviceUrl+'?appid='+encodeURIComponent(this.appid);for(name in urlParameters){urlString+='&'+name+'='+encodeURIComponent(urlParameters[name]);}
return(urlString);}
this.getUrlParameters=function(url){var args=new Object();if(url.lastIndexOf('?')==-1){return(args);}
else{var urlQueryString=url.slice(url.lastIndexOf('?')+1);}
if(urlQueryString.length==0){return(args);}
var pairs=urlQueryString.split('&');for(var i=0;i<pairs.length;i++){var pos=pairs[i].indexOf('=');if(pos==-1){var argname=pairs[i];var value='';}else{var argname=pairs[i].substring(0,pos);var value=pairs[i].substring(pos+1);}
args[argname]=decodeURIComponent(value);}
return(args);}
this.initialize=function(){urlParams=this.getUrlParameters(window.location.href);this.onload();}}
function Cookie(document,name,hours,path,domain,secure){this.$document=document;this.$name=name;if(hours)
this.$expiration=new Date((new Date()).getTime()+hours*3600000);else this.$expiration=null;if(path)this.$path=path;else this.$path=null;if(domain)this.$domain=domain;else this.$domain=null;if(secure)this.$secure=true;else this.$secure=false;}
Cookie.prototype.store=function(){var cookieval="";for(var prop in this){if((prop.charAt(0)=='$')||((typeof this[prop])=='function'))
continue;if(cookieval!="")cookieval+='&';cookieval+=prop+':'+escape(this[prop]);}
var cookie=this.$name+'='+cookieval;if(this.$expiration)
cookie+='; expires='+this.$expiration.toGMTString();if(this.$path)cookie+='; path='+this.$path;if(this.$domain)cookie+='; domain='+this.$domain;if(this.$secure)cookie+='; secure';this.$document.cookie=cookie;}
Cookie.prototype.load=function(){var allcookies=this.$document.cookie;if(allcookies=="")return false;var start=allcookies.indexOf(this.$name+'=');if(start==-1)return false;start+=this.$name.length+1;var end=allcookies.indexOf(';',start);if(end==-1)end=allcookies.length;var cookieval=allcookies.substring(start,end);var a=cookieval.split('&');for(var i=0;i<a.length;i++)
a[i]=a[i].split(':');for(var i=0;i<a.length;i++){this[a[i][0]]=unescape(a[i][1]);}
return true;}
Cookie.prototype.remove=function(){var cookie;cookie=this.$name+'=';if(this.$path)cookie+='; path='+this.$path;if(this.$domain)cookie+='; domain='+this.$domain;cookie+='; expires=Fri, 02-Jan-1970 00:00:00 GMT';this.$document.cookie=cookie;}
function handleVSLoad(){}
function handleError(errorCode,errorMessage){if(errorCode==503){}
else{alert("ERROR: Code "+errorCode+"; "+errorMessage);}}

var ratingPrefix = "";
var savingText = "Saving...";
function submitRating(videoId,rating,prefix){
	AOLVS.submitRating(videoId,rating);
	submittedrating=rating;
	ratingPrefix = prefix;
	elementid="ratinginfo"+videoId;
	$(elementid).innerHTML=savingText;
}
AOLVS=new AOLVideoSearch("x7i2czea7ljn6k8x1");AOLVS.attachEvent('onload','handleVSLoad();');AOLVS.attachEvent('onerror','handleError(errorCode, errorMessage);');AOLVS.attachEvent('onupdate','handleUpdate(methodName);');AOLVS.initialize();
//*****************************************************************************************************
// 	XMLHTTP JS class is is developed by Alex Serebryakov (#0.9.1)
// 	For more information, consult www.ajaxextended.com
//*****************************************************************************************************
XMLHTTP = function() {
  var _maximumRequestLength = 1500
  var _apiURL = null;
  this.status = null
  this.statusText = null
  this.responseText = null
  this.responseXML = null
  this.synchronous = false
  this.readyState = 0
  this.callbackContext = null;
  this.onreadystatechange =  function() {}
  this.onXMLHTTPError = function() {}
  this.onXMLHTTPLoad = function() {}
  this.registerCallback = function(obj) {
  	this.callbackContext = obj;
  }
  this.setXMLHTTPURL = function(url) {
  	_apiURL = url;
  }
  this.abort = function() {
    _stop = true
    _destroyScripts()
  }
  this.getAllResponseHeaders = function() {
    var result = ''
    for (property in _responseHeaders)
      result += property + ': ' + _responseHeaders[property] + '\r\n'
    return result
  }
  this.getResponseHeader = function(name) {
    for(property in _responseHeaders) {
      if(property.toLowerCase() == name.toLowerCase())
        return _responseHeaders[property]
    }
    return null
  }
  this.overrideMimeType = function(type) {
    _overrideMime = type
  }
  this.open = function(method, url, sync, userName, password) {
    if (!_checkParameters(method, url)) return
    _method = (method) ? method : ''
    _url = (url) ? url : ''
    _userName = (userName) ? userName : ''
    _password = (password) ? password : ''
    _setReadyState(1)
  }
  this.openRequest = function(method, url, sync, userName, password) {
    return this.open(method, url, sync, userName, password)
  }
  this.send = function(data) {
    if (_stop) return
    var src = _createQuery(data)
    _createScript(src)
  }
  this.setRequestHeader = function(name, value) {
    if (_stop) return
    for(property in _requestHeaders) {
      if(property.toLowerCase() == name.toLowerCase()) {
        _requestHeaders[property] = value; return
      }
    }
    _requestHeaders[name] = value
  }
  var _method = ''
  var _url = ''
  var _userName = ''
  var _password = ''
  var _requestHeaders = {
    "HTTP-Referer": document.location,
    "Content-Type": "application/x-www-form-urlencoded"
  }
  var _responseHeaders = { }
  var _overrideMime = ""
  var self = this
  var _id = ''
  var _scripts = []
  var _stop = false
  var _throwError = function(description, mythis) {
  	if (arguments.length < 2) { mythis = self; }
	if ((mythis.callbackContext != null) && mythis.callbackContext.onXMLHTTPError) { mythis.callbackContext.onXMLHTTPError(description); }
	else { self.onXMLHTTPError(description); }
    self.abort()
    return false
  }
  var _createQuery = function(data) {
    if(!data) data = ''
    var headers = ''
    for (property in _requestHeaders)
      headers += property + '=' + _requestHeaders[property] + '&'
    var originalsrc = _method
    + '$' + _id
    + '$' + _userName
    + "$" + _password
    + "$" + headers
    + '$' + _escape(data)
    + '$' + _url
    var src = originalsrc
    var max =  _maximumRequestLength, request = []
    var total = Math.floor(src.length / max), current = 0
    while(src.length > 0) {
      var query = _apiURL + '?'
      + 'multipart' 
      + '$' + _id
      + '$' + current++
      + '$' + total
      + '$' + src.substr(0, max)
      request.push(query)
      src = src.substr(max)
    }
    if(request.length == 1)
      src = _apiURL + '?' + originalsrc
    else
      src = request
    return src
  }
  var _checkParameters = function(method, url) {
    if(!method)
      return _throwError('Please, specify the query method (GET, POST or HEAD)')
    if(!url)
      return _throwError('Please, specify the URL')
    if(method.toLowerCase() != 'get' &&
      method.toLowerCase() != 'post' &&
      method.toLowerCase() != 'head')
      return _throwError('Please, specify either a GET, POST or a HEAD method')
    if(url.toLowerCase().substr(0,7) != 'http://')
      return _throwError('Only HTTP protocol is supported (http://)')
    return true
  }
  var _createScript = function(src) {
    if ('object' == typeof src) {
      for(var i = 0; i < src.length; i++)
        _createScript(src[i])
      return
    }
    var script = document.createElement('script')
    script.src = src
    script.type = 'text/javascript'
    if (navigator.userAgent.indexOf('Safari'))
      script.charset = 'utf-8' // Safari bug
    script = document.getElementsByTagName('head')[0].appendChild(script)
    _scripts.push(script)
    return script
  }
  var _escape = function(string) {
    string = escape(string)
    string = string.replace('+', '%2B')
    return string
  }
  var _destroyScripts = function() {
    for(var i = 0; i < _scripts.length; i++)
      if(_scripts[i].parentNode)
        _scripts[i].parentNode.removeChild(_scripts[i])
  }
  var _registerCallback = function() {
    _id = 'v' + Math.random().toString().substr(2)
    window[_id] = self
  }
  var _setReadyState = function(number, mythis) { 	
  	if (arguments.length < 2) { mythis = self; }
    self.readyState = number
	if ((mythis.callbackContext != null) && mythis.callbackContext.onreadystatechange) { mythis.callbackContext.onreadystatechange(); }
	else { self.onreadystatechange(); }
    if(number == 4) {
		if ((mythis.callbackContext != null) && mythis.callbackContext.onXMLHTTPLoad) { mythis.callbackContext.onXMLHTTPLoad(mythis); }
		else { self.onXMLHTTPLoad(); }
	}
  }
  var _parseXML = function() {  
      var type = self.getResponseHeader('Content-type') + _overrideMime
      if(!(type.indexOf('html') > -1 || type.indexOf('xml') > -1)) return
      if(document.implementation &&
	      document.implementation.createDocument &&
	      navigator.userAgent.indexOf('Opera') == -1) {
        var parser = new DOMParser()
        var xml = parser.parseFromString(self.responseText, "text/xml")
        self.responseXML = xml
      } else if (window.ActiveXObject) {
        var xml = new ActiveXObject('MSXML2.DOMDocument.3.0')
        if (xml.loadXML(self.responseText))
        	self.responseXML = xml
      } else {
        var xml = document.body.appendChild(document.createElement('div'))
        xml.style.display = 'none'
        xml.innerHTML = self.responseText
        _cleanWhitespace(xml, true)
        self.responseXML = xml.childNodes[0]
        document.body.removeChild(xml)
     }
  }
  var _cleanWhitespace = function(element, deep) {
    var i = element.childNodes.length; if(i == 0) return
    do {
      var node = element.childNodes[--i]
      if (node.nodeType == 3 && !_cleanEmptySymbols(node.nodeValue))
        element.removeChild(node)
      if (node.nodeType == 1 && deep)
        _cleanWhitespace(node, true)
    } while(i > 0)
  }
  var _cleanEmptySymbols = function(string) {
    string = string.replace('\r', '')
    string = string.replace('\n', '')
    string = string.replace(' ', '')
  	return (string.length == 0) ? false : true 
  }
  this._parse = function(object) { 
    if(_stop) return
    if(object.multipart) return
    if(!object.success)
      return _throwError(object.description, this)
    _responseHeaders = object.responseHeaders
    this.status = object.status
    this.statusText = object.statusText
    this.responseText = object.responseText
    _parseXML()
    _destroyScripts()
    _setReadyState(4, this);
  }
   _registerCallback()
}
//*****************************************************************************************************
// 	XML.ObjTree -- XML source code from/to JavaScript object like E4X
//  See http://www.kawa.net/works/js/xml/objtree-e.html.
//	Copyright (c) 2005-2006 Yusuke Kawasaki. All rights reserved.
//*****************************************************************************************************
if ( typeof(XML) == 'undefined' ) XML = function() {};
XML.ObjTree = function () {
    return this;
};
XML.ObjTree.VERSION = "0.23";
XML.ObjTree.prototype.xmlDecl = '<?xml version="1.0" encoding="UTF-8" ?>\n';
XML.ObjTree.prototype.attr_prefix = '-';
XML.ObjTree.prototype.parseXML = function ( xml ) {
    var root;
    if ( window.DOMParser ) {
        var xmldom = new DOMParser();
        var dom = xmldom.parseFromString( xml, "application/xml" );
        if ( ! dom ) return;
        root = dom.documentElement;
    } else if ( window.ActiveXObject ) {
        xmldom = new ActiveXObject('Microsoft.XMLDOM');
        xmldom.async = false;
        xmldom.loadXML( xml );
        root = xmldom.documentElement;
    }
    if ( ! root ) return;
    return this.parseDOM( root );
};
XML.ObjTree.prototype.parseDOM = function ( root ) { 
    if ( ! root ) return;
    this.__force_array = {};
    if ( this.force_array ) {
        for( var i=0; i<this.force_array.length; i++ ) {
            this.__force_array[this.force_array[i]] = 1;
        }
    }
    var json = this.parseElement( root );
    if ( this.__force_array[root.nodeName] ) {
        json = [ json ];
    }
    if ( root.nodeType != 11 ) {
        var tmp = {};
        tmp[root.nodeName] = json;
        json = tmp;
    } 
    return json;
};
XML.ObjTree.prototype.parseElement = function ( elem ) { 
    if ( elem.nodeType == 7 ) {
        return;
    }
    if ( elem.nodeType == 3 || elem.nodeType == 4 ) {
        var bool = elem.nodeValue.match( /[^\x00-\x20]/ );
        if ( bool == null ) return;
        return elem.nodeValue;
    }
    var retval;
    var cnt = {};
    if ( elem.attributes && elem.attributes.length ) {
        retval = {}; 
        for ( var i=0; i<elem.attributes.length; i++ ) {
            var key = elem.attributes[i].nodeName;
            if ( typeof(key) != "string" ) continue;
            var val = elem.attributes[i].nodeValue;
            if ( ! val ) continue;
            key = this.attr_prefix + key;
            if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
            cnt[key] ++;
            this.addNode( retval, key, cnt[key], val );
        }
    }
    if ( elem.childNodes && (elem.childNodes.length>=0) ) {
        var textonly = true;
        if ( retval ) textonly = false;
        for ( var i=0; i<elem.childNodes.length && textonly; i++ ) {
            var ntype = elem.childNodes[i].nodeType;
            if ( ntype == 3 || ntype == 4 ) continue;
            textonly = false;
        } 
        if ( textonly ) {
            if ( ! retval ) retval = new String();
            for ( var i=0; i<elem.childNodes.length; i++ ) {
                retval += elem.childNodes[i].nodeValue;
            } 
        } else { 
            if ( ! retval ) retval = {};
            for ( var i=0; i<elem.childNodes.length; i++ ) {
                var key = elem.childNodes[i].nodeName;
                if ( typeof(key) != "string" ) continue;
                var val = this.parseElement( elem.childNodes[i] );
                if ( ! val ) continue;
                if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
                cnt[key] ++;
                this.addNode( retval, key, cnt[key], val );
            }
        }
    } 
    return retval;
};
XML.ObjTree.prototype.addNode = function ( hash, key, cnts, val ) {
    if ( this.__force_array[key] ) {
        if ( cnts == 1 ) hash[key] = [];
        hash[key][hash[key].length] = val;
    } else if ( cnts == 1 ) {
        hash[key] = val;
    } else if ( cnts == 2 ) {
        hash[key] = [ hash[key], val ];
    } else {
        hash[key][hash[key].length] = val;
    }
};
XML.ObjTree.prototype.writeXML = function ( tree ) {
    var xml = this.hash_to_xml( null, tree );
    return this.xmlDecl + xml;
};
XML.ObjTree.prototype.hash_to_xml = function ( name, tree ) {
    var elem = [];
    var attr = [];
    for( var key in tree ) {
        if ( ! tree.hasOwnProperty(key) ) continue;
        var val = tree[key];
        if ( key.charAt(0) != this.attr_prefix ) {
            if ( typeof(val) == "undefined" || val == null ) {
                elem[elem.length] = "<"+key+" />";
            } else if ( typeof(val) == "object" && val.constructor == Array ) {
                elem[elem.length] = this.array_to_xml( key, val );
            } else if ( typeof(val) == "object" ) {
                elem[elem.length] = this.hash_to_xml( key, val );
            } else {
                elem[elem.length] = this.scalar_to_xml( key, val );
            }
        } else {
            attr[attr.length] = " "+(key.substring(1))+'="'+(this.xml_escape( val ))+'"';
        }
    }
    var jattr = attr.join("");
    var jelem = elem.join("");
    if ( typeof(name) == "undefined" || name == null ) {
    } else if ( elem.length > 0 ) {
        if ( jelem.match( /\n/ )) {
            jelem = "<"+name+jattr+">\n"+jelem+"</"+name+">\n";
        } else {
            jelem = "<"+name+jattr+">"  +jelem+"</"+name+">\n";
        }
    } else {
        jelem = "<"+name+jattr+" />\n";
    }
    return jelem;
};
XML.ObjTree.prototype.array_to_xml = function ( name, array ) {
    var out = [];
    for( var i=0; i<array.length; i++ ) {
        var val = array[i];
        if ( typeof(val) == "undefined" || val == null ) {
            out[out.length] = "<"+name+" />";
        } else if ( typeof(val) == "object" && val.constructor == Array ) {
            out[out.length] = this.array_to_xml( name, val );
        } else if ( typeof(val) == "object" ) {
            out[out.length] = this.hash_to_xml( name, val );
        } else {
            out[out.length] = this.scalar_to_xml( name, val );
        }
    }
    return out.join("");
};
XML.ObjTree.prototype.scalar_to_xml = function ( name, text ) {
    if ( name == "#text" ) {
        return this.xml_escape(text);
    } else {
        return "<"+name+">"+this.xml_escape(text)+"</"+name+">\n";
    }
};
XML.ObjTree.prototype.xml_escape = function ( text ) {
    return text.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
};

function handleUpdate(methodName){
	if(methodName=='submitRating'){
		var pixelsize=20*submittedrating;
		$('currentrating'+AOLVS.Result.videoId).style.width=pixelsize+"%";
		
		$("ratinginfo"+AOLVS.Result.videoId).style.display = "none";
		$('thanks').style.display = "block";

		for(i=1;i<6;i++){
			var elem = $(AOLVS.Result.videoId+'_star'+i);
			elem.parentNode.removeChild(elem);
		}
	}
}
