/*
 * 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 EXPRESS 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.
 */
 
/////////////////////////////////////////////
// ajaxCom.js - all ajax communication logic
/////////////////////////////////////////////
var serverUrl = "/MobiHandler";
var ajaxRequest = null;
var stbTypeId = 7;
var pinTimer = null;
var fmsServerPort = "";
var fmsServerIp = "";
///////////////////////////////////////////
// function to create ajaxRequest using AJAX

function createAjaxRequest() {
	try {
		ajaxRequest = new XMLHttpRequest();
	} catch (trymicrosoft) {
   		try {
    		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   		} catch (othermicrosoft) {
	 		try {
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
    	    	ajaxRequest = null;
    		}
  		}
	}
	if (ajaxRequest == null) {
//		alert("Error creating ajaxRequest object!");
	}
}
function detectIphone() { 
   var uagent = navigator.userAgent.toLowerCase();
   if (uagent.search("iphone") > -1 || uagent.search("nokia") > -1)
      return true;
   else
      return false;
}
function getValidation() {
	var uagent = navigator.userAgent.toLowerCase();
	if(detectIphone()) { 
		stbTypeId = 9;
  	} else {
  		stbTypeId = 7;
  	}
	var params = "method=getValidation" + "&serial=" + serial + "&mac=" + macAddress + "&ip=" + ipAddress + "&model=" + stbTypeId + "&version=" + version; // setStbType is replaced with model
	createAjaxRequest();
	if(ajaxRequest == null) {
		return;
	}
	ajaxRequest.onreadystatechange = function() { 
		if(ajaxRequest.readyState == 4) {
			if(ajaxRequest.status == 200) {
				var response = ajaxRequest.responseText;
				var responseResult = response.split("|");
				serial = responseResult[2];
				if((responseResult[0]).indexOf("newbox") >= 0) {
					boxLocked = true;
					document.getElementById("progressBarMsg").innerHTML = "enter password";
					document.getElementById("pinKeyPanel").style.visibility = "visible";
				} else {
					if(pinTimer != null) { 
						window.clearTimeout(pinTimer);
						pinTimer = null;
					}
					try {
				   		var validate = YAHOO.util.Cookie.get('validate');
				   		if(validate != null && validate.indexOf("true") >= 0) {
						   YAHOO.util.Cookie.set("validate", true, { expires: new Date("January 12, 2025") });
//						   document.getElementById("progressBarMsg").innerHTML = "successful";
						   document.getElementById("pinKeyPanel").style.visibility = "hidden";
						   boxLocked = false;
						    start();
					  	 } else { 
						    YAHOO.util.Cookie.set("validate", false, { expires: new Date("January 12, 2025") });
						    document.getElementById("progressBarMsg").innerHTML = "enter password";
							document.getElementById("pinKeyPanel").style.visibility = "visible";
							boxLocked = true;
					  	 }
				  	 } catch(x) {
		//				alert("4.0 : " + x);
					}
				}

			} else if(ajaxRequest.status == 500) {
				
			}
		}
	};
	ajaxRequest.open("POST", '/MobiHandler', true);
	ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
	ajaxRequest.send(params);
	return false;	
	
}
function checkPin(pin) {
	var params = "method=checkpin"+"&data=" + pin + "&serial=" + serial + "&mac=" + macAddress + "&ip=" + ipAddress + "&model=" + model + "&version=" + version;
	createAjaxRequest();
	if(ajaxRequest == null) {
		return;
	}
	keyStr = "";
	document.getElementById("progressBarMsg").innerHTML = "authenticating"; // + " with pin " + keyStr;	
	ajaxRequest.onreadystatechange = function() { 
		if(ajaxRequest.readyState == 4) {
			if(ajaxRequest.status == 200) {
				var response = ajaxRequest.responseText;
				if(response == -1) {
					document.getElementById("progressBarMsg").innerHTML = "wrong password"; // newbox
					if(pinTimer == null) {				
						pinTimer = window.setTimeout('document.getElementById("progressBarMsg").innerHTML = "enter password";pinCheckStart = true;boxLocked = true;', 3*1000);
					}
				} else {
					if(pinTimer != null) { 
						window.clearTimeout(pinTimer);
						pinTimer = null;
					}
					YAHOO.util.Cookie.set("validate", true, { expires: new Date("January 12, 2025") });
					boxLocked = false;
					document.getElementById("pinKeyPanel").style.visibility = "hidden";
					 start();
				}
			} else if(ajaxRequest.status == 500) {
				alert("failure");
			}
		}
	};			
	ajaxRequest.open("POST", serverUrl, true);
	ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
	ajaxRequest.send(params);	
}

// After Getting Response


function triggerPageReload() {	
	if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
		var response = ajaxRequest.responseText;	    	
    	if(response != "0") {   		    		
    		reloadPage();
    	} else {
	    	window.setTimeout('checkChannelCount();', 15*1000);	
    	}
    }
}

////////////////////////////////////
// check channel count

// function to check channel entitlement 
function checkChannelCount() {

	var data = "";
	
	createAjaxRequest();
	
	if(ajaxRequest == null)
		return;
		
	ajaxRequest.onreadystatechange = triggerPageReload;
	ajaxRequest.open("POST", serverUrl, false);
	ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
	ajaxRequest.send("method=getcount" + "&serial=" + serial + "&data=" + data);
}

////////////////////////////////////
// GET HTML LOADED

function loadPanels() {	
	createAjaxRequest();
	
	if(ajaxRequest == null){
		return;
	}
	var data = "method=loadhtml";	
	ajaxRequest.onreadystatechange = function() {
		if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
			var result = ajaxRequest.responseText;
		
			document.getElementById("guiPanel").innerHTML = result;
//			startupDraw();
//			window.setTimeout('startupDraw();',5000);
			//window.setTimeout('loadCache();', 1000);
			loadChannelCache();
		}		
	};
	ajaxRequest.open("POST", serverUrl, true);
	ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
	ajaxRequest.send(data);
}




var channelLogoCache	= new Array();
var categoryOrderCache	= new Array();
var categoryNameCache   = new Array();
var useGraphicCache     = new Array();
var graphicCache        = new Array();
var mnemonicCache      	= new Array();
var guideCache         	= new Array();
var favoriteCache		= new Array();
var lockedCache 		= new Array();
var origLockedCache 	= new Array();

var guideDataCache;
var surveyQuestionsCache = 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 wTitle = new Array();
var wDescription = new Array();

var vodDirCache = new Array();

var uniqCategoryCache  	= new Array();
var uniqCatNameCache	= new Array();
var catNameCache	= 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;

var countAjax = -1;

function getWanIp() {
	try {
		var params = "method=getwanip";
		var data = "";
		createAjaxRequest();
		if(ajaxRequest == null)
			return;
			
		ajaxRequest.onreadystatechange = function() {
			if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
				wanIp = ajaxRequest.responseText;
			}		
		};
		ajaxRequest.open("POST", serverUrl, false);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
	} catch(exception) {
		//alert("exception: " + exception);
	}
}



var playChCache = new Array();
var channelIdCache      = new Array();
var channelOrderCache   = new Array();
var channelNameCache    = new Array();
var noVideoCache        = new Array(); 
var streamAddressCache  = new Array();
var securityCache		= new Array();


function loadWidgetsCache(){
//	alert(index);
//	var currImage = 0;
	var params = "method=loadWidgetsCache" + "&serial=" + serial;
//	if(index == 0){
//		currImage = 0;
//	} else {
//		currImage = index;
////		alert("kkkkkkkkkkkkkkkkk"+currImage);	
//	}
		createAjaxRequest();
		if(ajaxRequest == null)
			return;
		ajaxRequest.onreadystatechange = function() {  
			if (ajaxRequest.readyState == 4) { 
				if(ajaxRequest.status == 200) {
					var result = ajaxRequest.responseText;
					updateWidgetsPanel(result);
				} if(ajaxRequest.status == 500) {
					alert("failirure");
					//failureInfo();
				}
			}
		};
		ajaxRequest.open("POST", serverUrl, true);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
	return false;
	
	
}

function loadTagCache(){
	var params = "method=loadTagCache" + "&serial=" + serial;
		createAjaxRequest();
		if(ajaxRequest == null)
			return;
		ajaxRequest.onreadystatechange = function() {  
			if (ajaxRequest.readyState == 4) { 
				if(ajaxRequest.status == 200) {
					var result = ajaxRequest.responseText;
					var data = result.split('-?#-');
					categoryOrderCache	= data[0].split('-@#-');
					categoryNameCache = data[1].split('-@#-');
					catNameCache = unique(categoryOrderCache);					
					catNameCache = unique(categoryNameCache);
					catNameCache.sort();					
					uniqCatNameCache[0]="ALL CHANNELS";
					for(var i=0 ;i < catNameCache.length ;i++ ){
						uniqCatNameCache[i+1]=catNameCache[i];
					}					
					expandCategoryPanel();
				} if(ajaxRequest.status == 500) {
					alert("failirure");
					
				}
			}
		};
		ajaxRequest.open("POST", serverUrl, true);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
	return false;
	
}


function unique(a) {
	tmp = new Array(0);
	for(i=0; i<a.length; i++){
		if(!contains(tmp, a[i])) {
			tmp.length += 1;
			tmp[tmp.length-1]=a[i];
		}
	}
	return tmp;
}

function contains(a, e) {
	for(j=0;j<a.length;j++)
		if(a[j] == e)
			return true;
	return false;
}


function getCatChannels(index){
	var tagName = uniqCatNameCache[tagCurrentIndex];
	if(tagName =="ALL CHANNELS"){
		var params = "method=loadChannelCache" + "&serial=" + serial;
	}else{
		var params = "method=getTagChannels" + "&serial=" + serial + "&tagName=" + encodeURIComponent(tagName); 	
	}
	createAjaxRequest();
	 if(ajaxRequest == null)
			return;		
			
	ajaxRequest.onreadystatechange = function() {  
			if (ajaxRequest.readyState == 4) { 
				if(ajaxRequest.status == 200) {
					var result = ajaxRequest.responseText;
					if(result.length > 0) {
					var data = result.split('-?#-');
					var count = -1;
			        var curCount = -1;
					channelIdCache = new Array();
					channelOrderCache = new Array();
					noVideoCache  = new Array(); 
                    streamAddressCache  = new Array();
                   	useGraphicCache = new Array();
                   	channelNameCache =new Array();
                   	securityCache =new Array();
                    try {					
						channelIdCache 		= data[0].split('-@#-');
						channelOrderCache 	= data[1].split('-@#-');
						channelNameCache 	= data[2].split('-@#-');
						noVideoCache 		= data[3].split('-@#-');
						streamAddressCache 	= data[4].split('-@#-');	
						useGraphicCache     = data[6].split('-@#-');
						securityCache		= data[9].split('-@#-'); 
	//					channelNameCache = trim(channelNameCache);
						selLiveTv();
                    } catch(x) {
						alert("exception at content: " + x);
					}
			} else {
				document.getElementById("progressBarMsg").innerHTML = "";
				document.getElementById("progressBarMsg").innerHTML = "no contents available";
				countAjax--;
			//window.setTimeout('loadChannelCache();', 15*1000); // change this to 30 sec
			}
				} if(ajaxRequest.status == 500) {
					alert("failirure");
					//failureInfo();
				}
			}
		};
		ajaxRequest.open("POST", serverUrl, true);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
	return false;
	
}
function getChannelInfo(index){
	var chName = selChannelNameCache[channelCurrentIndex];
		selectedChannel	 =	selChannelNameCache[channelCurrentIndex];	
		headerSelectedCh = selChannelNameCache[channelCurrentIndex];
		currentCh = selChannelNameCache[channelCurrentIndex];						
		currentChOrder = selChannelOrderCache[channelCurrentIndex];
		selChOrder = selChannelOrderCache[channelCurrentIndex];
		headerSelectedChId = selChannelOrderCache[channelCurrentIndex];						
		selChId = selChannelIdCache[channelCurrentIndex];
		selChGraphics = selUseGraphicCache[channelCurrentIndex];	
	var params = "method=getChannelInfo" + "&serial=" + serial + "&chName=" + chName; 	
	createAjaxRequest();
	 if(ajaxRequest == null)
			return;		
			
		  ajaxRequest.onreadystatechange = function() {  
			if (ajaxRequest.readyState == 4) { 
				if(ajaxRequest.status == 200) {
					var result = ajaxRequest.responseText;					
					if(result.length > 0) {
					var data = result.split('-?#-');
					var count = -1;
			        var curCount = -1;
					channelIdCache = new Array();
					channelOrderCache = new Array();
					noVideoCache  = new Array(); 
					streamAddressCache  = new Array();
					streamAddressCache =new Array();
					useGraphicCache = new Array();
					transcodeCache =new Array();
				
                    try {						
						selectedCategory 	= data[0].split('-@#-');
						channelIdCache 		= data[1].split('-@#-');
						channelOrderCache 	= data[2].split('-@#-');
						channelNameCache 	= data[3].split('-@#-');
						noVideoCache 		= data[5].split('-@#-');
						streamAddressCache 	= data[6].split('-@#-');	
						useGraphicCache     = data[7].split('-@#-');
						transcodeCache		= data[8].split('-@#-');
						try {
							if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {								
								callLinkCh();
							} else {
								launchViewer();
							}
						} catch (x) {
							alert("exception at content: " + x);
						}				
                    }
                    catch(x) {
				
					}
			}else{
			document.getElementById("progressBarMsg").innerHTML = "";
			document.getElementById("progressBarMsg").innerHTML = "no contents available";
			countAjax--;
			//window.setTimeout('loadChannelCache();', 15*1000); // change this to 30 sec
		}
				} if(ajaxRequest.status == 500) {
					alert("failiure");
					//failureInfo();
				}
			}
		};
		ajaxRequest.open("POST", serverUrl, true);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
	return false;
	
}

function getCacheData(ajaxResponse) {
	 try {
	 	if(ajaxResponse == "recall") {
	 		loadChannelCache();
	 		return;
	 		}
	 		var response  = "";	 	
 			response = ajaxResponse;
			var data = response.split('-?#-');
			var count = -1;
			var curCount = -1;		
			try {
//				alert(data.length + " : " + data);
				if(data.length > 7) {
					channelIdCache 		= data[0].split('-@#-');
					channelOrderCache 	= data[1].split('-@#-');
					channelNameCache 	= data[2].split('-@#-');
					noVideoCache 		= data[3].split('-@#-');
					streamAddressCache 	= data[4].split('-@#-');
					categoryNameCache   = data[6].split('-@#-');	
					fmsServerIp			= data[7].split('-@#-');
					fmsServerPort		= data[8].split('-@#-');			
					startupDraw(); 
				} else {
					
					document.getElementById("progressBarMsg").innerHTML = "no contents available";
				}
				} catch(x){
					alert("exception at content: " + x);
				}
	 	}catch(x) {
				alert("exception at content: " + x);
			}
}	
	
function loadChannelCache() {	
		var params = "method=loadChannelCache" + "&serial=" + serial;
		createAjaxRequest();
		if(ajaxRequest == null)
			return;
		ajaxRequest.onreadystatechange = function() {  
			paintDataCacheInfo();
		};
		ajaxRequest.open("POST", serverUrl, 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) {
			alert("failirure");
			//failureInfo();
		}
	}
}
var titleIdCache	= new Array();
var fullTitleCache	= new Array();
var assetNameCache	= new Array();
var actorCache	= new Array();
var mediumSummaryCache	= new Array();
var yearCache	= new Array();
var vodUseGraphicCache	= new Array();
var genrePatternCache	= new Array();
var ratingPatternCache	= new Array();
var subtitlePatternCache	= new Array();
var audioTypePatternCache	= new Array();
var genreCache	= new Array();

function stopStreammm(){	
	alert("hiii");
	var params ="method=stopStream" + "&serial=" + serial;	
	createAjaxRequest();
	 if(ajaxRequest == null)
			return;				
		  ajaxRequest.onreadystatechange = function() {  
				if (ajaxRequest.readyState == 4) { 
					if(ajaxRequest.status == 200) {
						var result = ajaxRequest.responseText;
						alert(result);	
//						if(result.length > 0) {
//							var data = result.split('-?#-');						
//							titleIdCache 		= data[0].split('-@#-');	
//							fullTitleCache 		= data[1].split('-@#-');
//							assetNameCache 		= data[2].split('-@#-');
//							actorCache 			= data[3].split('-@#-');
//							mediumSummaryCache 	= data[4].split('-@#-');
//							yearCache 			= data[5].split('-@#-');
//							vodUseGraphicCache 	= data[6].split('-@#-');
//							genrePatternCache 	= data[7].split('-@#-');
//							ratingPatternCache 	= data[8].split('-@#-');
//							subtitlePatternCache = data[9].split('-@#-');
//							audioTypePatternCache = data[10].split('-@#-');
//							genreCache 			= data[11].split('-@#-');
////							alert(genreCache + ", - ," + genrePatternCache);
//							updateVodPanel();
//						} else {
//							document.getElementById("progressBarMsg").innerHTML = "";
//							document.getElementById("progressBarMsg").innerHTML = "no contents available";
//							countAjax--;
//						}
					} if(ajaxRequest.status == 500) {
						alert("failirure");
						
					}
				}
			};
		ajaxRequest.open("POST", serverUrl, true);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
	return false;
	
}

function getVodInfo(){	
//	alert("qrewrhejgwkg");
	var params ="method=getVodInfo" + "&serial=" + serial;	
	createAjaxRequest();
	 if(ajaxRequest == null)
			return;				
		  ajaxRequest.onreadystatechange = function() {  
				if (ajaxRequest.readyState == 4) { 
					if(ajaxRequest.status == 200) {
						var result = ajaxRequest.responseText;	
						if(result.length > 0) {
							var data = result.split('-?#-');						
							titleIdCache 		= data[0].split('-@#-');	
							fullTitleCache 		= data[1].split('-@#-');
							assetNameCache 		= data[2].split('-@#-');
							actorCache 			= data[3].split('-@#-');
							mediumSummaryCache 	= data[4].split('-@#-');
							yearCache 			= data[5].split('-@#-');
							vodUseGraphicCache 	= data[6].split('-@#-');
							genrePatternCache 	= data[7].split('-@#-');
							ratingPatternCache 	= data[8].split('-@#-');
							subtitlePatternCache = data[9].split('-@#-');
							audioTypePatternCache = data[10].split('-@#-');
							(data[11].length ? genreCache = data[11].split('-@#-') : "") ;
//							alert(genreCache + ", - ," + genrePatternCache);
							updateVodPanel();
						} else {
							document.getElementById("progressBarMsg").innerHTML = "";
							document.getElementById("progressBarMsg").innerHTML = "no contents available";
							countAjax--;
						}
					} if(ajaxRequest.status == 500) {
//						alert("failirure");
					}
				}
			};
		ajaxRequest.open("POST", serverUrl, true);
		ajaxRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
		ajaxRequest.send(params);	
	return false;
	
}

function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

function trim( value ) {
	return RTrim(LTrim(value));
} 

//////////////////////////////
