/*
 * Copyright (c) 2008 AKEEBO CORPORATION. All Rights Reserved.
 *
 * This software is the confidential and proprietary information ("Confidential Information") 
 * of AKEEBO CORPORATION ("AKEEBO CORP"). Any disclosure or use of such Confidential Information other 
 * than in accordance with the terms of the license under which it was received is strictly 
 * prohibited.
 *
 * AKEEBO CORP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF 
 * THE SOFTWARE, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * OR NON-INFRINGEMENT. AKEEBO CORP SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 * THIS SOFTWARE OR ITS DERIVATIVES.
 */

/////////////////
// FOR CACHING //
/////////////////

var channelLogoCache	= new Array();
var categoryOrderCache	= new Array();
var categoryNameCache   = new Array();
var channelIdCache      = new Array();
var channelOrderCache   = new Array();
var channelNameCache    = new Array();
var useGraphicCache     = new Array();
var graphicCache        = new Array();
var noVideoCache        = new Array(); 
var streamAddressCache  = new Array();
var mnemonicCache      	= new Array();
var guideCache         	= new Array();
var favoriteCache		= new Array();
var lockedCache 		= new Array();
var origLockedCache 	= new Array();
var transcodeCache 		= new Array();
var protocolCache 		= new Array();
var guideDataCache;
var surveyQuestionsCache = new Array();
var securityCache = new Array();
var vodSecurityCache = new Array();

var scheduledChannelCache = new Array(); 
var restoredChCache = new Array();
var schStartTime = new Array();
var schDuration = new Array();
var rsStartTime = new Array();

var playSchChTime = new Array();
var playRestoredChTime = new Array();   
var playDuration = new Array();
var currentResChannel = new Array();
var currentSchChannel = new Array();
var audioInfoCache = new Array();


var wTitle = new Array();
var wDescription = new Array();

var vodDirCache = new Array();

var uniqCategoryCache  	= new Array();
var uniqCatNameCache	= new Array();

var adultSiteHeader = new Array();
var adultSiteImgLink = new Array();
var emailIdCache = "";
var phoneNumCache = "";
var weatherCodeCache = "";
//var companyName = "";
//var companyPhoneNum = "";
var mesgInterval = 5*60;
var recurrence = 1;
var popUpDuration = 20;
var duration = 0;
var playSchedulerEvent = null;

////////////////////////////////////
// GET CACHE
var countAjax = -1;

function loadCache() {
		var params = "method=getCache" + "&serial=" + serial;
//		alert(params);
		createAjaxRequest();
		if(ajaxRequest == null)
			return;
		ajaxRequest.onreadystatechange = function() {  
			paintDataCacheInfo();
		};
		ajaxRequest.open("POST", '/TvHandler', true);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
		return false;
}
function paintDataCacheInfo() {
	if (ajaxRequest.readyState == 4) { 
		if(ajaxRequest.status == 200) {
			var result = ajaxRequest.responseText;
			getCacheData(result);
		} if(ajaxRequest.status == 500) {
			failureInfo();
		}
	}
}

// 
var playChCache = new Array();
//
//var loadCacheSuccessHandler = function(o) {
//	getCacheData(o.responseText);
//} 
// 
function getCacheData(ajaxResponse) {
	 try {
	 	if(ajaxResponse == "recall") {
	 		loadCache();
	 		return;
	 	}
	 	var response  = "";
	 	if(ajaxResponse.length > 0) {
	 		try {
	 		response = ajaxResponse;
			loadNow(globalValue);
			showLoading();
			colorScheme = "black";	
	 		} catch (x) {
//	 			alert("xx at initial : " + x);
	 		}
			var data = response.split('-?#-');
			wrecords = YAHOO.lang.JSON.parse(data[23]);
			countImage = wrecords.wRecords.length-1;
			var count = -1;
			var curCount = -1;
			/**
			 *  cache information by using separator
			 */
		try {
			categoryOrderCache 	= data[0].split('-@#-');
			categoryNameCache 	= data[1].split('-@#-');
			channelIdCache 		= data[2].split('-@#-');
			channelOrderCache 	= data[3].split('-@#-');
			channelNameCache 	= data[4].split('-@#-');
			useGraphicCache 	= data[5].split('-@#-');
			graphicCache 		= data[6].split('-@#-');
			noVideoCache 		= data[7].split('-@#-');
			streamAddressCache 	= data[8].split('-@#-');
			mnemonicCache 		= data[9].split('-@#-');
			transcodeCache		= data[41].split('-@#-'); 
			protocolCache		= data[42].split('-@#-'); 
			securityCache		= data[44].split('-@#-'); 
			guideCache 		= data[10].split('-*$-');
			favoriteCache = data[12].split('-@#-');
			lockedCache = data[13].split('-@#-');
			emailIdCache = data[18];
			phoneNumCache = data[19];
			weatherCodeCache = data[20];
			companyName = data[21];
			companyPhoneNum = data[22];
			fmsServerIp = data[38];
			fmsServerPort = data[39];
//			alert(fmsServerIp + " : " + fmsServerPort);
//			mesgInterval = (data[38] && data[38].length>0 ? data[38] : 5*60);
//			recurrence = (data[39] && data[39].length>0 ? data[39] : 1);
			popUpDuration = (data[40] && data[40].length>0 ? data[40] : 20);
		} catch(x) {
//			alert("exception at content: " + x);
		}
			var currentData = data[24].split('-@#-');
			for(var i =0; i < currentData.length; ++i) {
				var curSchData = YAHOO.lang.JSON.parse(currentData[i]);
				rsStartTime[i] = new Array(curSchData.length);
				for(var j =0; j < rsStartTime[i].length; ++j) {
					rsStartTime[i][j] = new Array(curSchData[j].rsData.length);
					for(var k = 0; k < rsStartTime[i][j].length; k++) {
						try {
							rsStartTime[i][j][k] = curSchData[j].rsData[k].rsStartTime;
							if(rsStartTime[i][j][k].length > 0) {
								var curIndex = ++count;
								playRestoredChTime[curIndex] = rsStartTime[i][j][k];
								currentResChannel[curIndex] = i;
							}
						} catch(exception) {
//							alert("xcption at cache 3: " + exception);
						}
					}
				}
				schStartTime[i] = new Array(curSchData.length);
				for(var j =0; j < schStartTime[i].length; ++j) {
					schStartTime[i][j] = new Array(curSchData[j].chData.length);
					for(var k = 0; k < schStartTime[i][j].length; k++) {
						try {
							schStartTime[i][j][k] = curSchData[j].chData[k].chStartTime;
							if(schStartTime[i][j][k].length > 0) {
								var curIndex = ++curCount;
								playSchChTime[curIndex] = schStartTime[i][j][k];
								playDuration[curIndex] = curSchData[j].chData[k].chDuration;//schDuration[i][j][k];
								currentSchChannel[curIndex] = i;
							}
						} catch(exception) {
//							alert("xcption at cache 2: " + exception);
						}
					}
				}
			}
			/*
			for(var i =0; i < response.data47.jsonArray.length; ++i) {
//				channelIdCache[i] = response.data47.jsonArray[i].id;
//				channelOrderCache[i] 	= response.data47.jsonArray[i].channelOrder;
//				channelNameCache[i] = response.data47.jsonArray[i].channelName;
//				useGraphicCache[i] =  response.data47.jsonArray[i].useGraphic;
				graphicCache[i]	= response.data47.jsonArray[i].graphic;
//				noVideoCache[i]	= response.data47.jsonArray[i].noVideo;
//				streamAddressCache[i] 	= response.data47.jsonArray[i].streamAddress;
//				mnemonicCache[i] 	= response.data47.jsonArray[i].mnemonic;
				rsStartTime[i] = new Array(response.data47.jsonArray[i].schedulerData.length);
				for(var j =0; j < rsStartTime[i].length; ++j) {
					rsStartTime[i][j] = new Array(response.data47.jsonArray[i].schedulerData[j].rsData.length);
					for(var k = 0; k < rsStartTime[i][j].length; k++) {
						try {
							rsStartTime[i][j][k] = response.data47.jsonArray[i].schedulerData[j].rsData[k].rsStartTime;
							if(rsStartTime[i][j][k].length > 0) {
								var curIndex = ++count;
								playRestoredChTime[curIndex] = rsStartTime[i][j][k];
								currentResChannel[curIndex] = i;
							}
						} catch(exception) {
							alert(exception);
						}
					}
				}
				
				
				schStartTime[i] = new Array(response.data47.jsonArray[i].schedulerData.length);
				for(var j =0; j < schStartTime[i].length; ++j) {
					schStartTime[i][j] = new Array(response.data47.jsonArray[i].schedulerData[j].chData.length);
					for(var k = 0; k < schStartTime[i][j].length; k++) {
						try {
							schStartTime[i][j][k] = response.data47.jsonArray[i].schedulerData[j].chData[k].chStartTime;
							if(schStartTime[i][j][k].length > 0) {
								var curIndex = ++curCount;
								playSchChTime[curIndex] = schStartTime[i][j][k];
								playDuration[curIndex] = response.data47.jsonArray[i].schedulerData[j].chData[k].chDuration;//schDuration[i][j][k];
								currentSchChannel[curIndex] = i;
							}
						} catch(exception) {
							alert(exception);
						}
					}
				}
			}
			if(currentSchChannel.length > 0 || currentResChannel.length > 0) {
				playSchedulerEvent = window.setInterval('playScheduledChannel();', 30*1000);
			}
			*/
			try {
				genreCache 			= data[25].split('-@#-');
				titleIdCache 		= data[26].split('-@#-');	
				fullTitleCache 		= data[27].split('-@#-');
				assetNameCache 		= data[28].split('-@#-');
				actorCache 			= data[29].split('-@#-');
				mediumSummaryCache 	= data[30].split('-@#-');
				yearCache 			= data[31].split('-@#-');
				vodUseGraphicCache 	= data[32].split('-@#-');
				genrePatternCache 	= data[33].split('-@#-');
				ratingPatternCache 	= data[34].split('-@#-');
				subtitlePatternCache = data[35].split('-@#-');
				audioTypePatternCache = data[36].split('-@#-');
				vodSecurityCache = data[45].split('-@#-');
				vodDirCache = data[37].split('-@#-'); // vod director information
				audioInfoCache  = data[43].split("-$#-");
//				audioInfoCache = data[43];
				
				vodServer 			= data[14];
				parentalControlPassword = data[15];	
				startPage = "Channel Lineup";
				try {
					refineCache();
				} catch(x) {
//					alert("exception  : " + x);	
				}
				
				uniqCategoryCache = unique(categoryOrderCache);
				uniqCatNameCache = unique(categoryNameCache);
				uniqCatNameCache.sort();
				processDefaultChannel(data[11]);
				cloneLockedCache();					
			} catch (exception) {
//				alert("problem at cache : " + exception);
			}											
			if(lockedCache[nCurrentChannel] == 0) {																
				try {
					startStream();	
//					unloadVideoStream();				
				} catch (exception) {
//					alert("exception is coming here onwards");			
				}						
			}		
			// 
			window.setTimeout('startupDraw();',2*1000);
			tick();
		 	} else {
				document.getElementById("progressBarMsg").innerHTML = "";
				document.getElementById("progressBarMsg").innerHTML = records.key258;
				if(blinkIntervl != null) {
					window.clearInterval(blinkIntervl); // viren changes 
					blinkIntervl = null;
				}
				hideLoadPanel();
				countAjax--;
				window.setTimeout('loadCache();', 15*1000); // change this to 30 sec
			}
	
	 } catch (exception) { 
//	 	alert("xcption at cache 1: " + exception);
	 }
}

var loadCacheFailureHandler = function(o) {
 	showStatusPanel();
	document.getElementById("statusMessagePanel").innerHTML = '';
	document.getElementById("statusMessagePanel").innerHTML = records.key270 +". <br>" + ((companyName != null && companyPhoneNum != null) ? "" + records.key271 + " " + companyName + " " + records.key272 + " " + companyPhoneNum + "." : "");
	window.setTimeout('hideStatusPanel();', 20000);
}

///////////////////////
function refineCache() {
	if(channelIdCache[0] == '') {
		categoryOrderCache[0] == '' ? categoryOrderCache.shift() : '';
		categoryNameCache[0] == '' ? categoryNameCache.shift() : '';
		channelIdCache[0] == '' ? channelIdCache.shift() : '';
		channelOrderCache[0] == '' ? channelOrderCache.shift() : '';
		channelNameCache[0] == '' ? channelNameCache.shift() : '';
		useGraphicCache[0] == '' ? useGraphicCache.shift() : '';
		graphicCache[0] == '' ? graphicCache.shift() : '';
		noVideoCache[0] == '' ? noVideoCache.shift() : '';
		streamAddressCache[0] == '' ? streamAddressCache.shift() : '';
		mnemonicCache[0] == '' ? mnemonicCache.shift() : '';
		guideCache[0] == '' ? guideCache.shift() : '';	
		favoriteCache[0] == '' ? favoriteCache.shift() : '';
		lockedCache[0] == '' ? lockedCache.shift() : '';
		securityCache[0] == '' ? securityCache.shift() : '';
		
	} 
	if(genreCache[0] == '') {
		genreCache[0] == '' ? genreCache.shift() : '';
		titleIdCache[0] == '' ? titleIdCache.shift() : '';					
		fullTitleCache[0] == '' ? fullTitleCache.shift() : '';
		assetNameCache[0] == '' ? assetNameCache.shift() : '';
		actorCache[0] == '' ? actorCache.shift() : '';
		vodDirCache[0] == '' ? vodDirCache.shift() : '';
		mediumSummaryCache[0] == '' ? mediumSummaryCache.shift() : '';
		yearCache[0] == '' ? yearCache.shift() : '';
		vodUseGraphicCache[0] == '' ? vodUseGraphicCache.shift() : '';
		genrePatternCache[0] == '' ? genrePatternCache.shift() : '';
		ratingPatternCache[0] == '' ? ratingPatternCache.shift() : '';
		subtitlePatternCache[0] == '' ? subtitlePatternCache.shift() : '';
		audioTypePatternCache[0] == '' ? audioTypePatternCache.shift() : '';
		vodSecurityCache[0] == '' ? vodSecurityCache.shift() : '';
	}
}

/////////////////////////////////////////////////////////////////////
// ARRAY GETTERS
function getCategory() {
	var name = categoryNameCache[nCurrentChannel];
	/*
	if(name.length > 20)
		name = name.substring(0, 17) + '...';
	*/	
	return name;
}

function getCategoryOrder() {
	return categoryOrderCache[nCurrentChannel];
}

function getMnemonic() {
	return mnemonicCache[nCurrentChannel]; 
}

function getChannelId() {
	return channelIdCache[nCurrentChannel]; 
}

function getSelectedChannelId() {
	return channelIdCache[nSelectedChannel]; 
}

function getChannelName() {
	var name = channelNameCache[nCurrentChannel];
	/*
	if(name.length > 28)
		name = name.substring(0, 24) + '...';
	*/
	return name; 
}

function getChannelNameFor(channelIndex) {
	var name = channelNameCache[channelIndex];
	/*
	if(name.length > 28)
		name = name.substring(0, 24) + '...';
	*/
	return name; 
}

function getSelectedChannelName() {
	return channelNameCache[nSelectedChannel]; 
}

function getNoVideo() {
	return noVideoCache[nCurrentChannel]; 
}

function getStreamAddress() {
	return streamAddressCache[nCurrentChannel];
}

function getSelectedStreamAddress() {
	return streamAddressCache[nSelectedChannel];
}

function getChannelOrder() {
	return channelOrderCache[nCurrentChannel];
}

function getSelectedChannelOrder() {
	return channelOrderCache[nSelectedChannel];
}

function getChannelOrderIndex(chOrdVal) {
	var i= 0;
	for(i = 0; i < channelOrderCache.length; ++i) {
		if(chOrdVal == channelOrderCache[i])
			return i;
	}

	return -1;
}

function getFirstChInCat(catId) {
    var i= 0;
	var index = 0;
	for(i = 0; i < categoryOrderCache.length; ++i) {
		if(catId == categoryOrderCache[i])
			return i;
	}
	return 0; 
}

function isChannelFound(channelId) {
	var i = 0;
	for(i = 0; i < channelIdCache.length; ++i) {
		if(channelId == channelIdCache[i]) {
			nCurrentChannel = nSelectedChannel = nOldChannel = nLastSelectedChannel = i;
			var defaultCategory = getCategoryOrder();   
			nSelectedCategory = nCurrentCategory = getCategoryIndex(defaultCategory);			 
			return true;              
		}
    }
    return false;
}

function processDefaultChannel(defaultChannel) {
	var lastChannel = top.getCookie('lastChannel');
	//alert('processDefaultChannel');
	if(lastChannel && isChannelFound(lastChannel)) {
		//alert("lastChannel: " + lastChannel);
		return;
	} else {
		//alert("defaultChannel: " + defaultChannel);
		isChannelFound(defaultChannel);
	}
}

function getCategoryIndex(defaultCategory) {
	var i = 0;
	for(i = 0; i < uniqCategoryCache.length; ++i) {
		if(defaultCategory == uniqCategoryCache[i])
			return i;
	}
	return 0;
}

function cloneLockedCache() {
	var i;
	for(i=0; i<lockedCache.length; ++i) {
		origLockedCache[i] = lockedCache[i];
	}		
}

/////////////////////////////////////////////////////////////////////
// GUIDE GETTERS
function getGuideIndexStart(selChannelIndex) { // c10
	//return 0; // c12

	var indexChannel = 0;	

	if(selChannelIndex == null) {
		nCurrentChannel = ( nCurrentChannel < 0 ) ? ( channelIdCache.length - 1 ) : ( nCurrentChannel > ( channelIdCache.length - 1 ) ) ? 0 : nCurrentChannel;
	 	indexChannel = nCurrentChannel;
	} else {
		indexChannel = selChannelIndex;
	}	
	
	if(!mnemonicCache[indexChannel]) // a valid mnemonic indicates auto info
		return 0;
	
//	var guidePageSet = guideCache[indexChannel].split('-$#-'); 
	
	var guidePageSet = guideCache[indexChannel].split('-$#-'); 
	//alert(guidePageSet);
	var i = 0;		
	for(i=0; i < guidePageSet.length; ++i) {
		var infoText = guidePageSet[i];
		var infoData = infoText.split('|');
		var nowDate = new Date();
		nowDate = new Date(nowDate.getTime() + (nowDate.getTimezoneOffset()*60*1000));
		var startDate = new Date(infoData[1]);
		var endDate = new Date(infoData[2]);
		if(nowDate >= startDate && nowDate < endDate)
			break;
	}
	
	
//	for(var i=0; i < guideDataCache[indexChannel].guideList.length; ++i) {
//		var nowDate = new Date();
//		nowDate = new Date(nowDate.getTime() + (nowDate.getTimezoneOffset()*60*1000));
//		var startDate = new Date(guideDataCache[indexChannel].guideList[i].startTime);
//		var endDate = new Date(guideDataCache[indexChannel].guideList[i].endTime);
//		if(nowDate >= startDate && nowDate < endDate)
//			break;
//	}
	/*
	for(var i=0; i < guidePageSet.length; ++i) {
		var infoText = guidePageSet[i];
		var infoData = infoText.split('|');
								
		// PROD CODE		
		//MMMM dd, yyyy HH:mm:ss
		var nowDate = new Date();
		var startDate = new Date(infoData[1]);
		var endDate = new Date(infoData[2]);
		if(nowDate >= startDate && nowDate < endDate)
			break;				
	}
*/
//	i = (i >= guideDataCache[indexChannel].guideList.length ? 0 : i);
	i = (i >= guidePageSet.length? 0 : i);
	return i;
}

function resetGuideIndex() {
	nCurrentProgramme = getGuideIndexStart();
}

function getGuideLength() { // index within bounds already
//	return guideCache[nCurrentChannel].split('-$#-').length;
	return guideCache[nCurrentChannel].split('-$#-').length; 
//	return guideDataCache[nCurrentChannel].guideList.length;
	 
}

function plusGuideIndex() { // navigates on the cache
	var guideIndex = nCurrentProgramme + 1;

	// keep in bounds
	guideIndex = (guideIndex > getGuideLength() - 1 ? getGuideIndexStart() : guideIndex);
	
	nCurrentProgramme = guideIndex;
}

function minusGuideIndex() { // navigates on the cache
	var guideIndex = nCurrentProgramme - 1;
	// keep in bounds
	guideIndex = (guideIndex < getGuideIndexStart() ? getGuideLength() - 1 : guideIndex);
	
	nCurrentProgramme = guideIndex;
}

function getGuide() { // always at the first position
//	var guidePageSet = guideCache[nCurrentChannel].split('-$#-'); 
//	var infoText = guidePageSet[getGuideIndexStart()]; // c9

	var guidePageSet = guideCache[nCurrentChannel].split('-$#-'); 
	var infoText = guidePageSet[getGuideIndexStart()]; // c9 
 	return infoText;
//	var infoText = guideDataCache[nCurrentChannel].guideList[getGuideIndexStart()];
//	return infoText;
}

function getGuideAt(curIndex) { // index within bounds already
	var guidePageSet = guideCache[nCurrentChannel].split('-$#-'); 
	var infoText = guidePageSet[curIndex];
	return infoText; // change 4
//	var infoText = guideDataCache[nCurrentChannel].guideList[curIndex];
//	return infoText;
}

function getGuideForChAt(channelIndex, curIndex) { // index within bounds already
	var guidePageSet = guideCache[channelIndex].split('-$#-'); 
	var infoText = guidePageSet[curIndex];
	return infoText;
//	var infoText = guideDataCache[channelIndex].guideList[curIndex];
//	return infoText;
}

function createCacheResponse(params) {
	createAjaxRequest();
	if(ajaxRequest == null) {
		return;
	}
	ajaxRequest.onreadystatechange = function() { paintCacheContent(); };
	ajaxRequest.open("POST", '/TvHandler', true);
	ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
	ajaxRequest.send(params);
	return false;	
}

function paintCacheContent() {
   if (ajaxRequest.readyState == 4) {
    	if(ajaxRequest.status == 200) {
//    		alert(ajaxRequest.responseText);
//    		if((ajaxRequest.responseText).length > 0) {
//    			alert(2);
    			getCacheData(ajaxRequest.responseText);
//    		} else {
//    			loadCache();
//    		}
		} else if(ajaxRequest.status == 500) {
			showStatusPanel();
			document.getElementById("statusMessagePanel").innerHTML = '';
			document.getElementById("statusMessagePanel").innerHTML = records.key270 +". <br>" + ((companyName != null && companyPhoneNum != null) ? "" + records.key271 + " " + companyName + " " + records.key272 + " " + companyPhoneNum + "." : "");
			window.setTimeout('hideStatusPanel();', 20*1000);
		}
	} 
}

//function getWInfo() {
//	return false;
//	var params = 'method=GETWINFO&serial=' + serial;
//	var callbacks = { 
//	    success: function (o) {
//	        try {
//	            wrecords = YAHOO.lang.JSON.parse(o.responseText);
////	            alert(wrecords.wRecords.length);
//			} catch (x) {
//	      	}   
//	    },
//	    failure: function(o) {
//	    	failureInfo();
//	    } 
//	};			
//	YAHOO.util.Connect.asyncRequest(methodType, serverUrl, callbacks, params);
//	return false;
//}


//
/////////////////////////////////
