/* Javascript to handle flash player*/
function ads_js_include($script){
  var script = document.createElement('script');
  script.src = $script;
  script.type = 'text/javascript';
  var head = document.getElementsByTagName('head').item(0);
  head.appendChild(script);
}

var adbaseurl	='http://serve.vdopia.com';
var adserverbaseurl=adbaseurl+"/adserver";
var adjsbaseurl=adbaseurl+"/js";
var adswfbaseurl	='http://cdn.vdopia.com/files/swfs';
var adimagebaseurl = adbaseurl + "/files/images";

var cdnbaseurl	='http://cdn.vdopia.com';

ads_js_include(adjsbaseurl+"/swfobject.js");

function parseJSON(inp) {
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                inp.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + inp + ')');
    } catch (e) {
        return false;
    }
};

function thisMovie(movieName) {
	    if(navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName];
		} else {
			return document[movieName];
		}
	};

function sendEvent(pid,typ,prm) { thisMovie(pid).sendEvent(typ,prm); };

function loadFile(pid, file) {
	thisMovie(pid).loadFile({file:file});
}
var updateCallbacks = [];

function getUpdate(typ,pr1,pr2,pid) {

		if(typeof updateCallbacks[pid]['fn'] == 'function')
			updateCallbacks[pid]['fn'](typ,pr1,pr2,pid);
		else
			getUpdateUsual(typ,pr1,pr2,pid);
};

function getUpdateUsual(typ,pr1,pr2,pid) {
		if(typ == "time") { currentPosition = pr1; }
		else if(typ == "volume") { currentVolume = pr1; }
		//else if(typ == "item") { currentItem = pr1; setTimeout("getItemData(currentItem)",100); }
		var id = document.getElementById(typ);
		id.innerHTML = typ+ ": "+Math.round(pr1);
		pr2 == undefined ? null: id.innerHTML += ", "+Math.round(pr2);
		if(pid != "null") {
			document.getElementById("pid").innerHTML = "(received from the player with id <i>"+pid+"</i>)";
		}
};


function loadMovie(fil, text, pid, width, height,elid,autostart,allowfullscreen, title, summary, link, playerurl,video_quality, user_params) {
	var so;
	if (playerurl == undefined)
		so=new SWFObject(adswfbaseurl+'/mediaplayer.swf',pid,width,height,'7');
	else
		so=new SWFObject(playerurl,pid,width,height,'7');

	so.addParam("allowfullscreen",allowfullscreen);

	so.addParam("wmode", "transparent");
	if(allowfullscreen != "true") {
		so.addVariable("usefullscreen", false);
	}
	so.addVariable("file",fil);
	so.addVariable("autostart",autostart);
	so.addVariable('overlayinterval',75);
	so.addVariable('overlayduration',60);
	so.addVariable("width", width);
	so.addVariable("height", height);

	so.addVariable("cTitle", title);
	so.addVariable("cSummary", summary);
	so.addVariable("summary_url", link);
	if(video_quality!='')
		so.addVariable("video_quality", video_quality);

	so.addVariable("userParams", user_params);
	so.addVariable("baseurl",cdnbaseurl);


	//so.addVariable("overstretch","true");
	//so.addVariable("displayheight",height);


	so.addVariable("callback",adserverbaseurl+"/statistics.php");
	

	so.addParam("allowscriptaccess", "always");
	so.addVariable("enablejs","true");
	so.addVariable('javascriptid', pid);
	so.write(elid);
}

function loadMovieBP(fil, text,  pid, width, height, elid, autostart, btop, logo, backcolor, url,allowfullscreen,video_quality, skinreff) {
	
	var so;

	if(skinreff==null || skinreff=='')
		so=new SWFObject(adswfbaseurl+'/mediaplayer.swf',pid,width,height,'7');
	else
		so=new SWFObject(cdnbaseurl+'/swf/mediaplayer_skin.swf?skinreff='+skinreff,pid,width,height,'7');
	
	so.addParam('allowfullscreen',allowfullscreen);
	so.addParam("wmode", "transparent");
	if(allowfullscreen != "true") {
		so.addVariable("usefullscreen", false);
	}
	//so.addParam('allowscriptaccess','true');
	so.addVariable("file", fil);
	so.addVariable("frontcolor",'0xFFFFFF');
	so.addVariable("backcolor",'0x'+backcolor);
	so.addVariable("lightcolor",'0x333333');
	so.addVariable("screencolor",'0xffffff');
	so.addVariable("callback",adserverbaseurl+"/statistics.php");
	so.addVariable('logo',encodeURIComponent(logo));
	so.addVariable('brandedtop', encodeURIComponent(btop));
	so.addVariable('brandedlink', encodeURIComponent(url));
	so.addVariable('xmargin',2);
	so.addVariable("yoff",50);
	so.addVariable('overlayinterval',75);
	so.addVariable('overlayduration',60);
	so.addVariable('linktarget',"_blank");
	so.addVariable('overstretch','fit');
	so.addVariable("autostart",autostart);
	so.addVariable("baseurl",cdnbaseurl);
		if(video_quality!='')
		so.addVariable("video_quality", video_quality);

	var el = (typeof elid == 'string') ? document.getElementById(elid) : elid;
	so.write(elid);
}


// retrieves the XMLHttpRequest object
function CreateXmlHttpRequestObject()
{
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// if running Internet Explorer
	if(window.ActiveXObject)
	{
		try
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp = false;
		}
	}
	// if running Mozilla or other browsers
	else
	{
		try
		{
			xmlHttp = new XMLHttpRequest();
		}
		catch (e)
		{
			xmlHttp = false;
		}
	}
	// return the created object or display an error message
	if (!xmlHttp)
		alert("Error creating the XMLHttpRequest object.");
	else
		return xmlHttp;
}

/*var func = window.onbeforeunload;
window.onbeforeunload = sendClose;
function sendClose()
{
	var objXmlHttp = CreateXmlHttpRequestObject();
	objXmlHttp.open("POST", adserverbaseurl+"/statistics.php" , true);
	objXmlHttp.setRequestHeader('Content-Type',
	'application/x-www-form-urlencoded; charset=UTF-8;');
	objXmlHttp.onreadystatechange = function() {
		if (objXmlHttp.readyState == 4)
		{
			if(objXmlHttp.status == 200)
			{
				//alert(objXmlHttp.responseText);
			}
			else
			{
				alert("Failure while retrieving information!");
			}
		delete objXmlHttp;
		}
		//alert("reply received");
	};
	objXmlHttp.send("state=browserclose");
	//func();
}*/

if(typeof vdopia == "undefined") var vdopia = {};
vdopia.VDObject = function(_api_key,
					_video_file,
					_video_streamname,
					_ad_format,
					_width,
					_height,
					_ref_url,
					_domain,
					_video_category,
					_allowfullscreen,
					_runtime,
					_api_test,
					_title,
					_summary,
					_link,
					_video_quality,
					_autostart,
					_video_image,
					_user_params,
					_elid) {

	this.api_key = _api_key;
	this.title=_title;
	this.summary=_summary;
	this.link=_link;
	this.video_quality=_video_quality;
	this.api_test = _api_test;
	this.autostart=_autostart;
	this.user_params=_user_params;

	/* To add random extension like flv or swf*/
	if(_video_file.substr(_video_file.length-4, _video_file.length) != ".flv"){
		if(_video_file.indexOf("?")>=0)
			this.video_file = encodeURIComponent(_video_file+"&rand=.flv");
		else
			this.video_file = encodeURIComponent(_video_file+"?rand=.flv");
	}
	else
		this.video_file = encodeURIComponent(_video_file);

	this.video_streamname = 	encodeURIComponent(_video_streamname);
	//this.runtime = _runtime;
	this.ad_format = _ad_format;
	this.height = _height;
	this.width = _width;
	//this.options = _options;
	this.elid = _elid;
	this.ref_url = encodeURIComponent(_ref_url);
	this.video_category = _video_category;
	this.allowfullscreen=_allowfullscreen;
	this.objXmlHttp=false;
	//this.getRuntime();
	this.runtime = _runtime;
	this.video_image = _video_image;
	this.loaded=false;
	document.getElementById(this.elid).innerHTML='';
	this.getPlaylistId();
}
/* 4 steps
1. Find video length
2. Query for a playlist id
3. Instantiate the player
4  Send Statistics
*/
vdopia.VDObject.prototype = {
	write: function(elementId){
		if(this.getAttribute('useExpressInstall')) {
			// check to see if we need to do an express install
			var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
			if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
				this.setAttribute('doExpressInstall', true);
				this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
				document.title = document.title.slice(0, 47) + " - Flash Player Installation";
				this.addVariable("MMdoctitle", document.title);
			}
		}
		if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
			var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
			n.innerHTML = this.getSWFHTML();
			return true;
		}else{
			if(this.getAttribute('redirectUrl') != "") {
				document.location.replace(this.getAttribute('redirectUrl'));
			}
		}
		return false;
	},
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},
	getAttribute: function(name){
		return this.attributes[name] || "";
	},
	startAsynchCall: function(url, pars, method, callback)
	{
		var objRef=this;
		var objXmlHttp = CreateXmlHttpRequestObject();
		objXmlHttp.open(method, url, true);
		objXmlHttp.setRequestHeader('Content-Type',
		'application/x-www-form-urlencoded; charset=UTF-8;');
		objXmlHttp.onreadystatechange = function() {
			if (objXmlHttp.readyState == 4)
			{
				if(objXmlHttp.status == 200)
				{
					//alert(objXmlHttp.responseText);
					var resp = eval('('+objXmlHttp.responseText+')');
					objRef.playlistid=resp['playlistid'];
					if(resp['error'] == undefined) {
						if(objRef.loaded==false) {
						if(resp['branded']=='true')
						{
							loadMovieBP(adserverbaseurl+'/adplaylist.php?id='+objRef.playlistid,
							'', 'mpl', objRef.width, objRef.height, objRef.elid, objRef.autostart,
								resp['branded-top'], resp['branded-logo'],
								resp['branded-color'], resp['branded-url'],
								objRef.allowfullscreen,objRef.video_quality, resp['skinreff']);
						}
						else
							loadMovie(adserverbaseurl+'/adplaylist.php?id='+objRef.playlistid,
							'', 'mpl', objRef.width, objRef.height, objRef.elid, objRef.autostart,
							objRef.allowfullscreen, objRef.title, objRef.summary, objRef.link, resp['playerurl'],objRef.video_quality, objRef.user_params);
						objRef.loaded=true;
						} else {
							try{
							loadFile('mpl',adserverbaseurl+'/adplaylist.php?id='+objRef.playlistid);
							} catch(e) {
								//alert(e);
							}
							
						}
					} else {
						//alert("Error:" + resp['error']);
					}
				}
				else
				{
					//alert("Failure while retrieving information!");
				}
				delete objXmlHttp;
			}
		};
		objXmlHttp.send(pars);
	},
	getRuntime:function()
	{
		updateCallbacks['testmpl'] = [];
		updateCallbacks['testmpl']['fn']=function(typ,pr1,pr2,pid){
			if(typ == "time") {
				var objRef = updateCallbacks[pid]['objRef'];
				currentPosition = pr1;
				objRef.runtime=pr1+pr2;
				//alert(runtime);
			 	document.getElementById(objRef.elid).innerHTML='';
			 	objRef.getPlaylistId();
			 	//sendEvent(pid, 'playpause');
			}
		}
		//updateCallbacks['testmpl']['playpause']="doNothing";
		//updateCallbacks['testmpl']['objRef']=this;
		try{
		loadMovie(this.video_file, '', 'testmpl', '0','0',this.elid,'true');
		} catch(e) {
			
			alert(e);
		}
	},
	getUpdate: function(typ,pr1,pr2,pid){
		if(typ == "time") { currentPosition = pr1; sendEvent(pid, 'playpause');runtime=pr1+pr2; setRuntime(runtime, pid);}
	},
	getPlaylistId: function() {
		var url= adserverbaseurl+'/adserver.php';
		var pars='api_key='+this.api_key+'&video_file=' + this.video_file
				+ '&runtime='+this.runtime+'&ad_format='+this.ad_format
				+ '&ref_url='+this.ref_url +'&category='+this.video_category
				+ '&api_test=' + this.api_test + '&video_streamname='+this.video_streamname
		if(this.video_image!=undefined)
				pars+='&video_image='+this.video_image;
		
		this.startAsynchCall(url, pars, "POST");

	},
	reload: function() {
		this.loaded=true;
		this.getPlaylistId();
	}
}
var VDObject=vdopia.VDObject;
