var dom = document.getElementById;
var dom = document.getElementById;
var iex = document.all;
var ns4 = document.layers;
var bgContentText;
var bgContentId;

var player_id=null;
var server_time = null;
var server_timestamp = null;
var listId = null;
var defaultClass = null;
var currentClass = null;
var playout_id = null;
var URI= null;
var Container = null;
var engine= Array();
var requestCount = 0;
var changedContent = false;
function trimString(sInString)
{
	sInString = sInString.replace(/^\s+/g, "");
	return sInString.replace(/\s+$/g, "");
}
var debug_msg = '';
function debugAdd(string)
{
	debug_msg = debug_msg+'\n'+string;
}
function dumpDebug()
{
	//alert(debug_msg);
	debug_msg = '';
}
function updateList(index)
{
	var list = document.getElementById(Container);
	list.innerHTML = engine[index].response;
}
var clockInterval=0;
var syncInterval = 60;
function syncTime(index)
{
	syncInterval = 60;
	var temp = engine[index].response.split('<e>');
	temp = temp[1].split('</e>');
	serverTime = temp;
}
function nozeros(input) {
    return input;
    if (input.length > 1 && input.substr(0, 1) == "0") {
        return input.substr(1);
    } else {
        return input;
    }
}
function updateTimer()
{
	if(!server_time) return;

	syncInterval--;
	if(syncInterval <1 && (document.getElementById('playoutId')!= "undefined") && document.getElementById('playoutId'))
	{

		//alert(document.getElementById(playoutId));
		requestCount++;
		var k = requestCount;
		engine[requestCount] = new httpEngine();
		engine[requestCount].requestFile = syncURI;
		engine[requestCount].onCompletion =  function(){ syncTime(k); };
		engine[requestCount].runAJAX();
	}
	clockInterval = setTimeout("updateTimer()",1000);

	var now = server_time.split(":");
	var hour =now[0];
	var min = now[1];
	var sec = now[2];
	sec++;
	if(sec>59)
	{
		sec = 0;
		min++;
		if(min>59)
		{
			min=0;
			hour++;
		}
		if(hour>23)
		{
			hour = 0;
		}
	}

	now = new Date();
	var today = now.getDate();
	var month = now.getMonth()+1;
	var year = now.getFullYear();
	/*
	var hour = now.getHours();
	var min = now.getMinutes();
	var sec = now.getSeconds();
	*/
	/*
	if(today<10){
		today='0'+today;
	}
	if(month<10){
		month='0'+month;
	}
	*/

	if((hour.toString().length == 1))
	{
		hour = '0'+hour;
	}
	if((min.toString().length == 1))
	{
		min = '0'+min;
	}
	if((sec.toString().length == 1))
	{
		sec = '0'+sec;
	}



	server_time = hour+':'+min+':'+sec;
	/*var temp = new Date(Date(year, (nozeros(month)-1), nozeros(today), nozeros(hour), nozeros(min), nozeros(sec)));
	server_timestamp = (temp.getTime()/1000.0);
	*/
	server_timestamp++;
	var clock = document.getElementById('clock');
	if(clock)
		clock.innerHTML= '<b>Onair - '+today+'/'+month+'/'+year+' - '+hour+':'+min+'</b>';
}
function ieControll()
{

	var playerObj = document.getElementById(player_id);
    if (playerObj == null) return;
	//updateTimer();
	var current = playerObj.currentMedia;
    if (current == null) return;
	
    current = current.getItemInfo('WMS_CONTENT_DESCRIPTION_PLAYLIST_ENTRY_URL');
	current = trimString(current);
	var temp =  current.split('m');
	current = temp[1];

	//ukoliko postoji neki content koji se vrti u objektu, a nije background
	//onda ga trebamo istaknuti u listi
	if(current && current !="" && current !=" " && current!="background")
	{
		var lastActive = getElementsByClassName('li',currentClass);
		var currentHTMLobj= document.getElementById('tbl_'+current);

		if(currentHTMLobj)
		{
			//ukoliko postoji kontent koji je predhodno bio iscrtan
			// njegov class name cemo postaviti na default

			if(lastActive){
				if(lastActive!=currentHTMLobj.id)
				{
					var temp = document.getElementById(lastActive);
					temp.className = defaultClass;
					new Ajax.Updater('one', 
	 					 '/frontend_dev.php/livechannel/onair/time/'+current, 
	 					 {
	 					 	asynchronous:true, 
	 					 	evalScripts:true
	 					 }
	 					 ); 
	 					new Ajax.Updater('two', 
	 					 '/frontend_dev.php/livechannel/next/time/'+current, 
	 					 {
	 					 	asynchronous:true, 
	 					 	evalScripts:true
	 					 }
	 					 );;
				}
			}
			//istaknnimo content koji je u objektu
			
			if(!changedContent){
				new Ajax.Updater('one', 
	 					 '/frontend_dev.php/livechannel/onair/time/'+current, 
	 					 {
	 					 	asynchronous:true, 
	 					 	evalScripts:true
	 					 }
	 					 ); 
	 					new Ajax.Updater('two', 
	 					 '/frontend_dev.php/livechannel/next/time/'+current, 
	 					 {
	 					 	asynchronous:true, 
	 					 	evalScripts:true
	 					 }
	 					 );
				changedContent = true;
			}
			currentHTMLobj.className=currentClass;
		}else{
			//posto content koji je object vratio ne postoji u listi
			//sada imamo dvije mogucnosti
			//postoji mogucnost da je object vratio content koji netreba da se ispise, ili
			// smo dosli do kraja liste koju treba osvjeziti
			var contents = document.getElementsByTagName("li");
			var found=0;
			var counter = 0;
			for(var k =0; k<contents.length; k++)
			{
				if(contents[k].className==defaultClass)
				{
					var temp= contents[k].id.split("_");
					var id= temp[1];
					temp = document.getElementById(id+'_START_TIME');
					var startTime = temp.value;
					temp = document.getElementById(id+'_END_TIME');
					var endTime = temp.value;
					temp = server_timestamp;
					if(temp>startTime && temp< endTime)
					{
						//posto je trenutno vrijeme izmedju pocetka i kraja kontenta iz liste
						//taj content trebamo istaknuti
						contents[k].className = currentClass;
						found=1;
						if(lastActive)
						{
							var temp = document.getElementById(lastActive);
							temp.className = defaultClass;
						}
					}
					counter++;
				}
			}
			// ako ne postoji nijedan istaknuti content
			//potrebno je provjeriti dali smo na kraju liste
			var updateTime = document.getElementById('calAfter');
			if(found!=1 && updateTime){
				var updateTimeSec = updateTime.value;
				var temp = server_timestamp;
				//ako je trenutno vrijeme vece od zadnjeg contenta u listi
				//osvjezavamo listu
				if(temp>updateTimeSec)
				{
					requestCount++;
					var k = requestCount;
					engine[requestCount] = new httpEngine();
					engine[requestCount].requestFile = URI;
					engine[requestCount].onCompletion =  function(){ updateList(k); };
					engine[requestCount].runAJAX();
				}
			}
		}
	}else{

	}
	setTimeout('ieControll()',1000);
}
function nonIeControll()
{
	//updateTimer();
	var updateTime = document.getElementById('calAfter');
	var counter=0;
	var found = 0;
	//provjeravamo dali postoji content koji trenutno traje.
	//njegov class name je currentClass	varijabla
	var activeContent = getElementsByClassName('li',currentClass);

	if(activeContent)
	{
			var temp = activeContent.split("_");
			var id = temp[1];
			temp = document.getElementById(id+'_START_TIME');
			if(temp){
			var startTime = temp.value;
			temp = document.getElementById(id+'_END_TIME');
			var endTime = temp.value;
			temp = server_timestamp;
			//ako je trenutno vrijeme vece od vremena kloje je pboljezeno kao end_time contenta
			//tada je content zavrsio i potrebo je promjenuti njegov className
			if(temp>endTime)
			{
				document.getElementById('tbl_'+id).className = defaultClass;
			}else{
				//obiljeziti da je pronadjen content koji je sada
				found=1;
			}
		}else{
			document.getElementById(activeContent).className = defaultClass;
		}
	}
	//pretrazujemo listu contenata za iducim contentom
	var list = document.getElementById('playout_schema');
	if(list){
		var contents = list.getElementsByTagName("li");
		for(var k =0; k<contents.length; k++)
		{
			if(contents[k].className==defaultClass)
			{
				var temp= contents[k].id.split("_");
				var id= temp[1];
				temp = document.getElementById(id+'_START_TIME');
				if(temp){
					var startTime = temp.value;
					temp = document.getElementById(id+'_END_TIME');
					var endTime = temp.value;
					temp = server_timestamp;
					//ako je trenutno vrijeme izmedju pocetka i kraja contenta
					// onda ga je potrebno istaknuti u listi
					// i obiljeziti da je pronadjen content koji je trenutno sada
					if(temp>startTime && temp< endTime)
					{
						new Ajax.Updater('one', 
	 					 '/frontend_dev.php/livechannel/onair/time/'+id, 
	 					 {
	 					 	asynchronous:true, 
	 					 	evalScripts:true
	 					 }
	 					 ); 
	 					new Ajax.Updater('two', 
	 					 '/frontend_dev.php/livechannel/next/time/'+id, 
	 					 {
	 					 	asynchronous:true, 
	 					 	evalScripts:true
	 					 }
	 					 );
					
					
					
						contents[k].className = currentClass;
						found=1;
					}
					counter++;
				}
			}
		}
	}
	//ako nepostoji istaknuti content
	//potrebno je provjeriti dali je potrebno osvjeziti listu
	//
	if(found!=1 && updateTime)
	{
		var updateTimeSec = parseInt(updateTime.value);
		//ako je trenutno vrijeme vece od zadnjeg contenta u listi
		//osvjezavamo listu
		if(server_timestamp>updateTimeSec)
		{
			requestCount++;
			var k = requestCount;
			engine[requestCount] = new httpEngine();
			engine[requestCount].requestFile = URI;
			engine[requestCount].onCompletion =  function(){ updateList(k); };
			engine[requestCount].runAJAX();
		}
	}
	setTimeout('nonIeControll()',1000);
}
function objectControl(URL,player,time,defaultClassName,currentClassName,playoutId,container,s_timestamp)
{
	server_timestamp = s_timestamp;
	Container = container;
	URI= URL;
	server_time = time;
	list_id = listId;
	defaultClass = defaultClassName;
	currentClass = currentClassName;
	player_id = player;
	playout_id = playoutId;
	ieControll();
}

function htmlControl(URL,player,time,defaultClassName,currentClassName,playoutId,container,s_timestamp)
{
	server_timestamp = s_timestamp;
	Container = container;
	URI= URL;
	playout_id = playoutId;
	server_time = time;
	player_id = player;
	list_id = listId;
	defaultClass = defaultClassName;
	currentClass = currentClassName;
	nonIeControll();
}
function convertSecToTime(sec)
{
	var hour = sec/3600;
	var hour = Math.floor(hour);
	if(hour<10) hour = "0"+hour;
	var minute = (sec -3600*hour)/60;
	minute = Math.floor(minute);
	if(minute<10) minute ="0"+minute;
	var seconds = (sec -3600*hour - minute*60);
	seconds = Math.floor(seconds);
	if(seconds<10) seconds = "0"+seconds;

	return hour+':'+minute+':'+seconds;
}
function convertTimeToSec(time)
{
	var temp = time.split(":");
	var ret = Math.floor(temp[0]*3600);
	ret = ret+ Math.floor(temp[1]*60);
	ret = ret+ Math.floor(temp[2]);
	return ret;
}
function getElementsByClassName(tag, Class) {
	var aElm=document.body.getElementsByTagName(tag);
	for(var i=0; i<aElm.length; i++) {
		if(aElm[i].className==Class) {
			return aElm[i].id;
		}
	}
	return null;
}

//===================================================================//
//=====================AJAX ENGINE FOR TIMETABLE=====================//
//===================================================================//

document.addEvent = addEvent;
document.removeEvent = removeEvent;

function eventTriger(e){
	if (! e)
	e = event;
	return e.target || e.srcElement;
}
function addEvent(event,method){
	this[event] = method;
	if(ns4) this.captureEvents(Event[event.substr(2,event.length).toUpperCase()]);
}


function removeEvent(event){
	this[event] = null;
	if(ns4) this.releaseEvents(Event[event.substr(2,event.length).toUpperCase()]);
}
function getEl(name,nest){
	nest = nest ? "document."+nest+"." : "";
	var el = dom ? document.getElementById(name) : iex ? document.all[name] : ns4 ? eval(nest+"document."+name) : false;
	el.css = ns4 ? el : el.style;
	el.getTop = function(){return parseInt(el.css.top) || 0};
	el.setTop = function(y){el.css.top = ns4 ? y: y+"px"};
	el.getLeft = function(){return parseInt(el.css.left) || 0};
	el.setLeft = function(y){el.css.left = ns4 ? y: y+"px"};
	el.setWidth = function(pix){el.css.width= ns4 ? pix: pix+"px"};
	el.setClassName = function(name){el.className = name};
	el.getClassName= function(){return el.className};
	el.getHeight = function(){return ns4 ? el.document.height : el.offsetHeight};
	el.getClipHeight = function(){return ns4 ? el.clip.height : el.offsetHeight};
	el.getWidth = function(){return ns4 ? el.document.width : el.offsetWidth};
	el.getClipWidth = function(){return ns4 ? el.clip.width : el.offsetWidth};
	el.hideVis = function(){el.css.display="none"};
	el.showVis = function(){el.css.display="block"};
	el.addEvent = addEvent;
	el.removeEvent = removeEvent;
	return el;
}
function httpEngine(file) {
	this.xmlhttp = null;
	this.resetData = function() {
		this.method = "POST";
		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
		this.execute = false;
		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
		this.running = null;
	};

	this.resetFunctions = function() {
		this.onLoading = function() { };
		this.onLoaded = function() { };
		this.onInteractive = function() { };
		this.onCompletion = function() { };
		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
		this.running = null;
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.running = true;
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
						self.onLoading();
						break;
						case 2:
						self.onLoaded();
						break;
						case 3:
						self.onInteractive();
						break;
						case 4:
						self.response = self.xmlhttp.responseText;
						self.responseXML = self.xmlhttp.responseXML;
						self.responseStatus[0] = self.xmlhttp.status;
						self.responseStatus[1] = self.xmlhttp.statusText;

						if (self.execute) {
							self.runResponse();
						}

						if (self.elementObj) {
							elemNodeName = self.elementObj.nodeName;
							elemNodeName.toLowerCase();
							if (elemNodeName == "input"
							|| elemNodeName == "select"
							|| elemNodeName == "option"
							|| elemNodeName == "textarea") {
								self.elementObj.value = self.response;
							} else {
								self.elementObj.innerHTML = self.response;
							}
						}
						if (self.responseStatus[0] == "200") {
							self.onCompletion();
						} else {
							self.onError();
						}

						self.URLString = "";
						break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}