/**
 * @author VasiliyK
 */

var Helpers = {

}

/*
    Gets login data from params string
*/
Helpers.getLoginData = function (params) {
	return this.getParamsValues(params, ['id', 'pw']);
}

Helpers.setImeLanguage = function (lang) {
	Logger.write("=====Updating IMELang, current: " + _g_ime.IMElang + "; new: " + lang, "Helpers");
	var imePlugin = document.getElementById("pluginObjectIME");
	_g_ime.IMElang = lang;
	_g_ime.OSDlang = lang;
	_g_ime.updateIMElang(lang);
	_g_ime.updateOSD(lang);
	imePlugin.SetLanguage(lang.toUpperCase());
	Logger.write("=====IMELang updated, new: " + _g_ime.IMElang, "Helpers");
}

/*
  Decodes html symbols
*/
Helpers.decodeHtml = function (value) {
    if (value) {
        return jQuery('<div/>').html(value).text(); 
    } else {
        return '';
    }
}

/*
    Get params values from params string
    
    *params - string with params
    *paramNames - array with param names
*/
Helpers.getParamsValues = function (params, paramNames)
{
    if (params.charAt(0) == "?")
    {
        params = params.slice(1, params.length);
    }
    
    params = params.split("&");
    var result = [];
    
    for (var i = 0; i < params.length; i++)
    {
        var data = params[i].split("=");
        if (data.length == 2)
        {
            for (var j = 0; j < paramNames.length; j++)
            {
                if (data[0] == paramNames[j])
                {
                    result[j] = data[1];
                    break;
                }
            }
        }
    }
    
    return result;
}

/*
    Escapes html code
    
    *str - unescaped string
*/
Helpers.escapeHTML = function(str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}

Helpers.unescapeHTML = function (str) {
	var e = document.createElement('div');
	e.innerHTML = str;
	return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

/*
    Remove quotes from string
    
    *str - string with qoutes
*/
Helpers.removeQuotes = function(str)
{
    return str.replace(/'/g, "");
}

/*
    Sorts input array by field name
    
    *array - input array
    *fieldName - sort criteria
    *isAscending - if true - ascending sort, otherwise - descending
*/
Helpers.sortByField = function (array, fieldName, isAscending, subFieldName) {
	Logger.write("===Begin sorting...", "Helpers");
	var fieldExists = !!array && !!array[0] && (!!array[0][fieldName] || array[0][fieldName] === 0);
    if (!fieldExists || (!!subFieldName && !array[0][fieldName][subFieldName])) {
        Logger.write("===Can't sort!", "Helpers");
        return array;
    }
    
    if (!isAscending && isAscending !== false) {
		isAscending = true;
	}
	
    var sortFunc = function (a, b) {
        var aField = !subFieldName ? a[fieldName] : a[fieldName][subFieldName];
        var bField = !subFieldName ? b[fieldName] : b[fieldName][subFieldName];
        if (isAscending) {
            return aField > bField ? 1 : -1;
        } else {
            return aField < bField ? 1 : -1;
        }
        //return 0;
    }
    Logger.write("===Sorting completed...", "Helpers");
    return array.sort(sortFunc);
}


Helpers.showLoading = function () {
	$('#loadingObject').sfLoading('show');
}

Helpers.hideLoading = function () {
	$('#loadingObject').sfLoading('hide');
}

var EpgHelper = {
	tablePadding: 10
}

/*
    Gets html code for channel table
    
    *channelId - Channel ID
    *programsData - array with programs data
    *startTime - EPG start time
    *interval - EPG time interval
*/
EpgHelper.getChannelTableHtml = function ($) {
	var widths, max, theend;
	var tableMaxWidth  = 680;
	var tablePadding = 10;
	var programSpacing = 3;

	var addWidth = function (width, i, length) {
		if (width < 0)
			return 0;
			
		width = Math.ceil(width);
		
		if ((width + tablePadding) >= max)
		{
			widths.push(max);
			theend = true;
			return max;
		}    
		else 
		{
			max -= width + tablePadding + programSpacing;
			widths.push(width);
			return width;
		}
	}

	var empty = function () {
		widths = new Array;
		max = tableMaxWidth;
		theend = false;
	}
	
	/*
		Gets width for program button
		
		*startTime - program start time
		*endTime - program end time
		*interval - EPG interval
	*/
	var getProgramButtonWidth = function(startTime, endTime, interval)
	{
		var result = (endTime.getTime()-startTime.getTime())*100/interval;
		result = result * tableMaxWidth/100;
		return result;
	}
	
	/*
		Gets td HTML code for programs table
		
		*width - td width in percent
		*programData - data for program
	*/
	var getProgramTableTd = function (width, programData) {
		if (width <= 0)
			return "";
			
		var programBtnStyle = "width: 100%;";
		var style = "width: "+width.toString()+"px;padding-right:10px;";
		var tdHtml = "<td style='padding:0px;'>";
		var id = "btnProgram" + programData.id;
		tdHtml += "<div id='" + id + "' style='" + style;
		tdHtml += "' startTime='" + DateHelper.convertToString(programData.startTime) + "' ProgramTvGuideID='" + programData.id;
		tdHtml += "' class='programOuterDiv'>";
		tdHtml += "<div align='left' class='programButton' style='" + programBtnStyle + "'>&nbsp;&nbsp;" 
		tdHtml += Helpers.decodeHtml(Helpers.escapeHTML(programData.name)) + "</div></div>";
		tdHtml += "</td>";
		
		return tdHtml;
	}
	
	return function (channelId, programsData, startTime, interval, currentChannel) {
		var html = "<table class='channelTable' id='tableChannel" + channelId + "' cellpadding='1px' cellspacing='1px'><tr style='padding-bottom:-2px;margin-bottom:-2px;'>";
		var endTime = new Date();
		endTime.setTime(startTime.getTime()+interval);     
	   
		if (!programsData || programsData.length == 0) {
			var unavailableId = "btnUnavail" + channelId;
			var uwidth = tableMaxWidth + tablePadding;
			 html += "<td style='padding:0px;'><div id='"+unavailableId+"' style='width:"+uwidth.toString()+"px;overflow: hidden;' programDescription='Unavailable' class='programOuterDiv'><div class='programButton' style='width:100%;'>&nbsp;&nbsp;Unavailable</div></div></td>";
			currentChannel.push("#"+unavailableId);
		} else {
			var firstAdded = false;
			var width = 0;
			var length = programsData.length;
			empty();
			
			for (var i=0; i < length; i++) {
				var program = programsData[i];
				if (!program.startTime) {
					program.startTime = program.recentAirTime.startTime;
				}
				if (!firstAdded && !theend) {
					if (program.startTime > startTime) {
						width = getProgramButtonWidth(startTime, program.startTime, interval);
					   
						width = addWidth(width, i, length);
						if (i > 0) {
							html += getProgramTableTd(width, programsData[i-1]);
							currentChannel.push("#btnProgram" + programsData[i-1].id);
						} else {
							var unavailableId = "btnUnavail" + channelId;
							html += "<td style='padding:0px;'><div id='"+unavailableId+"' style='width:"+width.toString()+"px;overflow: hidden;padding-right:10px' programDescription='Unavailable' class='programOuterDiv'><div class='programButton' style='width:100%;'>&nbsp;&nbsp;Unavailable</div></div></td>";                       
							currentChannel.push("#"+unavailableId);
						}    
						firstAdded = true;
					} else if (i == (length - 1)) {
						width = getProgramButtonWidth(startTime, endTime, interval);
						width = addWidth(width, i, length);
						html += getProgramTableTd(width, programsData[i]);
						currentChannel.push("#btnProgram" + programsData[i].id);
					}
				}

				if (firstAdded && !theend) {
					var style = "";
					width = 0;
					if (i == (length - 1)) {
						width = getProgramButtonWidth(program.startTime, endTime, interval);
					} else {
						programsData[i+1].startTime = programsData[i+1].recentAirTime.startTime;
						width = getProgramButtonWidth(program.startTime, programsData[i+1].startTime, interval);
					}
					width = addWidth(width, i, length);
					html += getProgramTableTd(width, program);
					currentChannel.push("#btnProgram" + program.id);
				}
			}
		}
		
		html += "</div>";
		return html;
	}
	
}(jQuery);

/*
    Creates channel table
    
    *channelId - Channel ID
    *programsData - array with programs data
    *startTime - EPG start time
    *interval - EPG time interval
*/
EpgHelper.createChannelTable = function (channelId, programsData, startTime, interval, currentChannel)
{
    var table = $(this.getChannelTableHtml(channelId, programsData, startTime, interval, currentChannel));
    return table;
}

var DateHelper = {
    
}

/*
    Parses date from string (example: 2007-11-23T13:11:22)
    
    *dateString - date in services format
*/
DateHelper.parseDate = function(dateString)
{
    if (typeof(dateString)!="undefined")
    {
		if (typeof(dateString) == "object") {
			return dateString;
		}
		var rx = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
		var res = rx.exec(dateString);
		var result = new Date(res[1], res[2]-1, res[3], res[4], res[5], res[6]);
		return result;
    }
    else
    {
		return null;
    }
}

/*
    Converts javascript date to services format
    
    *date - date to convert
*/
DateHelper.convertToString = function (date) {
    return date.toLocaleFormat("%Y-%m-%dT%H:%M:%S");
}

/*
    Getting Date to display in data panel
*/
DateHelper.getArchDate = function (date) {
	 var archDate = DateHelper.getShortDay(date)+", "+DateHelper.getShortMonth(date)+" "+date.getDate().toString();  
	 return archDate;
}

DateHelper.getArchPlusDate = function (date) {
	return date.getDate() + " " + DateHelper.getShortMonth(date) + " " + date.getFullYear();
}

DateHelper.getMessageDateTime = function (date) {
	var result = date.getDate() + " " + DateHelper.getShortMonth(date) + " " + date.getFullYear();
	result += " " + date.toLocaleFormat("%H:%M");
	return result;
}

/*
    Gets short day name from javascript date
    
    *date 
*/
DateHelper.getShortDay = function (date) {
    var day = date.getDay();
    var days = [];
    days[0] = Resources.getResources().Su;
    days[1] = Resources.getResources().Mo;
    days[2] = Resources.getResources().Tu;
    days[3] = Resources.getResources().We;
    days[4] = Resources.getResources().Th;
    days[5] = Resources.getResources().Fr;
    days[6] = Resources.getResources().Sa;
    return days[day];
}

/*
    Gets short month name from javascript date
    
    *date - 
*/
DateHelper.getShortMonth = function(date)
{
    var month = date.getMonth();
    var months = [];
    months[0] = Resources.getResources().Jan;
    months[1] = Resources.getResources().Feb;
    months[2] = Resources.getResources().Mar;
    months[3] = Resources.getResources().Apr;
    months[4] = Resources.getResources().May;
    months[5] = Resources.getResources().Jun;
    months[6] = Resources.getResources().Jul;
    months[7] = Resources.getResources().Aug;
    months[8] = Resources.getResources().Sep;
    months[9] = Resources.getResources().Oct;
    months[10] = Resources.getResources().Nov;
    months[11] = Resources.getResources().Dec;
    
    return months[month];
}

DateHelper.getDateFrom = function (date) {
	var result = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
	
	return result;
}

DateHelper.getDateTill = function (date) {
	var result = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
	
	return result;
}

DateHelper.DateRange = function (dateFrom, dateTill) {
	if (dateFrom && dateTill) {
		this.dateFrom = DateHelper.getDateFrom(dateFrom);
		this.dateTill = DateHelper.getDateTill(dateTill);
	} else if (dateFrom && !dateTill) {
		this.dateFrom = DateHelper.getDateFrom(dateFrom);
		this.dateTill = DateHelper.getDateTill(dateFrom);
	}
}

/*
* Sets backgound image of scene to transparent image
*/
Helpers.setBackgroundOpacity = function(){
    $(".background").css({"backgroundImage":"url(images/player/background-shader.png)"});
    $(".categoriesListBG").addClass("styleWithOpacity");
}

/*
* Removes transparent backgound image
*/
Helpers.removeBackgroundOpacity = function () {
    $(".background").css({"backgroundImage":"url(images/SMC_main_bg.png)"});
    $(".categoriesListBG").removeClass("styleWithOpacity");
}

/*
* Checks client settings for specified service
*/
Helpers.checkServiceStatus = function (service, status, condition) {
    if (typeof(service) == "string") {
		service = JsonServices.ContentType[service];
	}
	if (typeof(status) == "string") {
		status = JsonServices.Status[status];
	}
    for (var i = 0; i < AppContext.ClientSettings.services.length; i++) {
        var oneService = AppContext.ClientSettings.services[i];
        if (condition) {
            if (oneService.serviceContentType == service && oneService.serviceStatus == status) {
				return true;
            }
        } else {
            if (oneService.serviceContentType == service && oneService.serviceStatus != status) {
				return true;
            }
        }
    }
    return false;
}

/*
* Checks client settings for specified scene
*/
Helpers.checkScene = function (scene, checkStatus, condition) {
    scene = scene.toLowerCase();
    if (scene == "livetv") {
        return Helpers.checkServiceStatus("LiveTV", checkStatus, condition);
    } else if ((scene.indexOf("archtv") != -1)) {
        return Helpers.checkServiceStatus("DVR", checkStatus, condition);
    } else if ((scene.indexOf("movies") != -1) || scene == "series") {
        return Helpers.checkServiceStatus("VOD", checkStatus, condition);
    } else if (scene.indexOf("archplus") > -1 || scene.indexOf("programepisodes") > -1) {
		return Helpers.checkServiceStatus("ArcPlus", checkStatus, condition);
	} else if (scene == "radio") {
        return Helpers.checkServiceStatus("Radio", checkStatus, condition);
	} else if (scene.indexOf("favorites") > -1) {
		return Helpers.checkServiceStatus("DVR", checkStatus, condition)
			|| Helpers.checkServiceStatus("VOD", checkStatus, condition)
			|| Helpers.checkServiceStatus("ArcPlus", checkStatus, condition);
    } else {
        return false;
    }

}

/*
* Checks status of scene in settings
*/
Helpers.checkStatus = function (contentType) {
    if (Helpers.checkServiceStatus(contentType, "Enabled", true)) {
        return ServiceStatuses.enabled;
    } else if (Helpers.checkServiceStatus(contentType, "PreviewAvailable", true)) {
        return ServiceStatuses.previewAvailable;
    } else if (Helpers.checkServiceStatus(contentType, "Available", true)) {
        return ServiceStatuses.available;
    } else {
        return ServiceStatuses.na;
    }
}

Helpers.checkAllServices = function () {
	var services = ["LiveTV", "DVR", "VOD", "ArcPlus", "Radio"];
	for (var i = 0; i < services.length; i++) {
		if (Helpers.checkServiceStatus(services[i], "Enabled", true)) {
			return true;
		}
	}
	
	return false;
}

/*
* Converts int time to time in format HH:MM:SS
*/
Helpers.intTimeToString = function (time) {
    if (time < 0)
        return "0:00:00";
    
    var timeHour = Math.floor(time/3600000);
    var timeMinute = Math.floor((time%3600000)/60000);
    var timeSecond = Math.floor((time%60000)/1000);
    var timeHTML = timeHour + ":";
    if(timeMinute == 0) {
        timeHTML += "00:";
    } else if(timeMinute <10) {
        timeHTML += "0" + timeMinute + ":";
    } else {
        timeHTML += timeMinute + ":";
	}
            
    if (timeSecond == 0) {
        timeHTML += "00";
    } else if(timeSecond <10) {
        timeHTML += "0" + timeSecond;
    } else {
        timeHTML +=  timeSecond;
	}
    return timeHTML;
}

/*
* Gets DUID of device
*/
Helpers.getDUID = function(){
    var networkPlugin = document.getElementById("pluginObjectNetwork");
    var nnaviPlugin =document.getElementById("pluginObjectNNavi");
    networkPlugin.CreatePlugin(); 
    var DUID;
    var MAC;
    var activeType = networkPlugin.GetActiveType();
    MAC = networkPlugin.GetMAC(activeType);
    DUID = nnaviPlugin.GetDUID(MAC);
    Logger.write("[Helpers] DUID="+DUID, "Helpers");
    return  DUID;
}

/*
* Loads xml 
*/
Helpers.loadXML = function(url, cb, errorCb){
    $.ajax({
		type: "GET",
		url: url,
		dataType: "xml",
		error: errorCb || function(){},
		timeout: 60000,
		success: cb || function(){}
	});
}

/*
	Return default or user defined buffers
*/
Helpers.loadBuffers = function () {
	Logger.write("Loading current buffers", "Settings", true);
	var fs = new FileSystem();
	
	if (fs.isValidCommonPath(curWidget.id) !== 1) {
		Logger.write("Creating path", "Settings", true);
		fs.createCommonDir(curWidget.id);
	}
	
	var file = fs.openCommonFile(curWidget.id + "/settings_" + AppContext.user.login + ".xml", "r");
	if (!file) {
		file = fs.openFile("defaultSettings.xml", "r");
	}
	var content = file.readAll();
	Logger.write("File Content: " + content, "Settings", true);
	fs.closeCommonFile(file);
	
	var parser = new DOMParser();
	var doc = parser.parseFromString(content, 'text/xml');
	
	var settings = {};
	$(doc).find("settings").each(function () {
		settings.totalBuffer = $(this).find("totalBuffer").text();
		settings.initialBuffer = $(this).find("initialBuffer").text();
		settings.pendingBuffer = $(this).find("pendingBuffer").text();
	});
	
	return settings;
}

Helpers.saveBuffers = function (settings) {
	if (!settings || !settings.totalBuffer || !settings.initialBuffer || !settings.pendingBuffer) {
		throw new Error("Invalid argument");
	}
	
	var fs = new FileSystem();
		
	if (fs.isValidCommonPath(curWidget.id) !== 1) {
		fs.createCommonDir(curWidget.id);
	}
	
	var file = fs.openCommonFile(curWidget.id + "/settings_" + AppContext.user.login + ".xml", "w");
	if (file) {
		var content = '<?xml version="1.0" encoding="UTF-8"?><settings>';
		content += '<totalBuffer>' + settings.totalBuffer + '</totalBuffer>';
		content += '<initialBuffer>' + settings.initialBuffer + '</initialBuffer>';
		content += '<pendingBuffer>' + settings.pendingBuffer + '</pendingBuffer>';
		content += '</settings>';
		
		var writed = file.writeAll(content);
		fs.closeCommonFile(file);
		if (writed) {
			return true;
		}
	}
	
	return false;
}

Helpers.isAdultMovieGenre = function (id) {
	if (id == 10 || id == 137 || id == 138) {
		return true;
	}
	
	return false;
}

Helpers.addTimeStamp = function (obj, ttl) {
	ttl = ttl || 60;
	obj.timeStamp = new Date();
	obj.ttl = ttl; // in minutes
	obj.isExpired = function () {
		var age = (new Date() - this.timeStamp) / 60000;
		if (age > ttl) {
			return true;
		}
		
		return false;
	};
}

Helpers.handleGlobalKeys = function (keyCode) {
	switch (keyCode) {
		case $.sfKey.CH_UP:
			if (ScenePlayer.isPlaying) {
				ScenePlayer.handleChUp();
			}
			return true;
			break;
		case $.sfKey.CH_DOWN:
			if (ScenePlayer.isPlaying) {
				ScenePlayer.handleChDown();
			}
			return true;
			break;
	}
	
	return false;
}

Helpers.getUtcTime = function (time) {
	var utime = new Date(time);
	var utcHours = utime.getUTCHours();
	var utcMinutes = utime.getUTCMinutes();
	var utcDate = utime.getUTCDate();
	var utcMonth = utime.getUTCMonth();
	var utcYear = utime.getUTCFullYear();
	utime.setFullYear(utcYear);
	utime.setMonth(utcMonth);
	utime.setDate(utcDate);
	utime.setHours(utcHours);
	utime.setMinutes(utcMinutes);
	
	return utime;
}
