// ----------------------------------------------------------
// Copyright (c) 2010, Edooni Solutions Pvt. Ltd.
// All rights reserved.
// ----------------------------------------------------------

// ----------------------------------------------------------
// eUtil: common utility package
//
//     o Const
//     o data
//     o ajax
//     o combo
//     o date
//     o jdate
//     o div
//     o img
// ----------------------------------------------------------

var eUtil = new function() {};

// ----------------------------------------------------------
// eUtil.Const
// ----------------------------------------------------------

eUtil.Const = new function() {
	this.JSLinkStr = 'javascript::void(0)';
};

// ----------------------------------------------------------
// eUtil.data
//
//     o isSet
//     o isDefined
//     o isString
//     o isInteger
//     o isFloat
//     o nl2br
// ----------------------------------------------------------

eUtil.data = new function(){

	/*
         * eUtil.data.isSet
         *
         * returns 0 if input is undefined, null or empty
         */

	this.isSet = function(str) {
		if(str === undefined) return 0;
		if(str === null) return 0;

		// convert to string
		str += "";

		if(str.match(/^\s*$/)) return 0;
		return 1;
	};

	/*
         * eUtil.data.isDefined
         *
         * returns 0 if input is undefined or null
         */

	this.isDefined = function(input_object) {
		if(input_object === undefined) return false;
		if(input_object === null) return false;
		return true;
	};

	/*
         * eUtil.data.isString
         *
         * returns 1 if input is a valid string
         */

	this.isString = function(str) {
		return isset(str);
	};

	/*
         * eUtil.data.isInteger
         *
         * returns 1 if input is a valid integer
         */

	this.isInteger = function(int_value) {
		if(int_value == undefined) return false;
		if(int_value == 0) return true;
		if(!int_value.match(/^\d+$/)) return false;
		return true;
	};

	/*
	 * eUtil.data.isFloat
	 *
	 * returns 1 if input is a valid float
	 */

	this.isFloat = function(float_value) {
		if( (float_value == undefined) || (float_value == null)) return false;
		if(!float_value.match(/^\d+(.\d+)?$/)) return false;
		return true;
	};

	/*
         * eUtil.data.nl2br
         *
	 * useful when using textarea data in an HTML element
	 *
         * replaces newlines with <br>
         */

	this.nl2br = function(str) {
		if(!this.isString(str))
			return;

		var is_xhtml = false;
		var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';
		return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
	};
};

// ----------------------------------------------------------
// eUtil.combo
//
//     o getValue
//     o setValue
//     o removeOptions
//     o addOption
//     o createNewOptions
//     o createNewKeysAndOptions
//
//     o getValueById
//     o setValueById
//     o removeOptionsById
//     o addOptionById
//     o createNewOptionsById
//     o createNewKeysAndOptionsById
// ----------------------------------------------------------

eUtil.combo = new function() {

	this.defaultValue = "Select";

	/*
	 * eUtil.combo.getValue
	 *
	 * returns selected option
	 */
	
	this.getValue = function (combo) {
		if(combo == null) return false;
		return combo.options[combo.selectedIndex].value;
	};

	this.getText = function (combo) {
		if(combo == null) return false;
		return combo.options[combo.selectedIndex].text;
	};
	/*
	 * eUtil.combo.setValue
	 *
	 *	Input params: combo_id, combo_value
	 *	Return value: true if value is set/false if value not set
	 *	Procedure:
	 *		=> go over the combo options one by one and get the index of combo_value
	 *		=> set selected index to that value
	 */

	this.setValue = function(combo, combo_value) {

		if(!document.getElementById(combo)) return false;
		var len = combo.options.length;
		for(var i = 0; i < len; i++) {
			if(combo.options[i].value == combo_value) {
				combo.selectedIndex = i;
				return true;
			}
		}

		return false;
	};

	/*
	 * eUtil.combo.removeOptions
	 *
	 *	Input params: combo
	 *	Return value: none
	 */
	
	this.removeOptions = function(combo) {
		//remove current elements from combo_name
		if(combo == null) return false;
		var len = combo.options.length;
		for(i = len-1; i >= 0; i--) {
			combo.remove(i);
		}
	};

	this.addOption = function(combo, value, text) {
		if(combo == null) return false;
		combo.options.add(new Option(value, text));
	};

	this.createNewKeysAndOptions = function(combo, options, keys, addDefault) {
		if(combo == null) return false;
		this.removeOptions(combo);
		if(addDefault) this.addOption(combo, this.defaultValue, this.defaultValue);
		for(var i = 0; i < options.length; i++) {
			this.addOption(combo, options[i], keys[i])
		}
	};

	this.createNewOptions = function(combo, options, sort, addDefault) {
		if(combo == null) return false;
		if(sort) options.sort();
		this.createNewKeysAndOptions(combo, options, options, addDefault);
	}

	/*
	 * DOM varient's
	 */

	this.getValueById = function(comboId) {
		if(!document.getElementById(comboId)) return false;
		var combo = document.getElementById(comboId);
		return this.getValue(combo);
	};

	this.getTextById = function(comboId) {
		if(!document.getElementById(comboId)) return false;
		var combo = document.getElementById(comboId);
		return this.getText(combo);
	};

	this.setValueById = function(comboId, combo_value) {
		if(!document.getElementById(comboId)) return false;
		var combo= document.getElementById(comboId);
		this.setValue(combo, combo_value);
	};
 
	this.removeOptionsById = function(comboId) {
		if(!document.getElementById(comboId)) return false;
		var combo = document.getElementById(comboId);
		this.removeOptions(combo);
	};

	this.addOptionById = function(comboId, value, text) {
		if(!document.getElementById(comboId)) return false;
		var combo = document.getElementById(comboId);
		this.addOption(combo, value, text);
	};

	this.createNewKeysAndOptionsById = function(comboId, options, keys, addDefault) {
		if(!document.getElementById(comboId)) return false;
		var combo = document.getElementById(comboId);
		this.createNewKeysAndOptions(combo, options, keys, addDefault);
	};

	this.createNewOptionsById = function(comboId, options, sort, addDefault) {
		if(!document.getElementById(comboId)) return false;
		var combo = document.getElementById(comboId);
		this.createNewOptions(combo, options, sort, addDefault);
	};
};

// ----------------------------------------------------------
// eUtil.div
//
//     o toggle
// ----------------------------------------------------------

eUtil.div = new function() {

	this.show = function (divId) {
		document.getElementById(divId).style.display = 'block';
	};

	this.hide = function (divId) {
		document.getElementById(divId).style.display = 'none';
	};

	/*
	 * eUtil.div.toggle
	 *
	 * toggles the div
	 */
	
	this.toggle = function(divId) {

		var disp = document.getElementById(divId).style.display;
		document.getElementById(divId).style.display = (disp == "block") ? "none" : "block";
	};
};

// ----------------------------------------------------------
// eUtil.ajax
//
//     o getJsonData
//     o getData
// ----------------------------------------------------------

eUtil.ajax = new function(){

	this.getJsonData = function(url) {

		try {
			xml_http = new XMLHttpRequest();
		} catch(e) {
			xml_http = new ActiveXObject("Msxml2.XMLHTTP");
		}

		var d1 = new Date();
		if(url.match(/\?.*\=.*$/)) url = url + "&time=" + d1.getTime();
		else if(url.match(/\?$/)) url = url + "time=" + d1.getTime();
		else url = url + "?time=" + d1.getTime();

		xml_http.open("GET", url, false);
		xml_http.send(null);

		return xml_http.responseText;
	};

	this.getData = function(url) {

		//alert("url: " + url)
		var json_data = this.getJsonData(url);
		//alert(json_data);

		if(!eUtil.data.isSet(json_data))
		{
			alert("No valid response from server");
			return "invalid";
		}

		var json_resp = eval('(' + json_data + ')');
		if(eUtil.data.isSet(json_resp['error']))
		{
			alert("Error from server: " + json_resp['error']);
			return 'error';
		}

		return json_resp;
	};
};

// ----------------------------------------------------------
// eUtil.date (works on php db date string)
//
//     o getDate
//     o getTime
//     o getDay
//     o getMonth
//     o getYear
//     o getMonthYear
// ----------------------------------------------------------

eUtil.date = new function() {

	this.months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

	this.getDate = function(dateStr) {
		var vals = dateStr.split(' ');
		return vals[0];
	};

	this.getTime = function(dateStr) {
		var vals = dateStr.split(' ');
		return vals[1];
	};

	this.getDay = function(dateStr) {
		var vals = dateStr.split('-');
		return (vals[2] * 1);
	};

	this.getMonth = function(dateStr) {
		var vals = dateStr.split('-');
		vals[1] *= 1;
		return vals[1] ? this.months[vals[1] - 1] : '';
	};

	this.getMonthYear = function(dateStr) {
		var vals = dateStr.split('-');
		vals[1] *= 1;
		return vals[1] ? (this.months[vals[1] - 1] + ' ' + vals[0]) : vals[0];
	};
};

// ----------------------------------------------------------
// eUtil.jdate (works on javascript date variable)
//
//     o getStrInHHMM
// ----------------------------------------------------------

eUtil.jdate = new function() {

	this.getStrInHHMM = function(d) {
		var hours = d.getHours();
		var mins = d.getMinutes();
		var AP = (hours > 11) ? "PM" : "AM";

		if(hours > 11) hours -= 12;
		if(hours < 10) hours = "0" + hours;
		if(mins < 10) mins = "0" + mins;

		return (hours + ":" + mins + " " + AP);
	};
};

// ----------------------------------------------------------
// eUtil.win
//
//     o getWidth
//     o getHeight
//     o getDimension
// ----------------------------------------------------------

eUtil.win = new function() {

	this.getDimension = function() {

		var width, height;

		// std browsers e.g. mozilla/netscape/opera/IE7
		if(typeof window.innerWidth != 'undefined')
		{
			width = window.innerWidth;
			height = window.innerHeight;
		}
		// IE6 in std compliant mode (i.e. with a valid doctype as the first line in document)
		else if(typeof document.documentElement != 'undefined' &&
				typeof document.documentElement.clientWidth != 'undefined' &&
				document.documentElement.clientWidth != 0)
		{
			width = document.documentElement.clientWidth;
			height = document.documentElement.clientHeight;
		}
		// older versions of IE
		{
			width = document.getElementsByTagName('body')[0].clientWidth;
			height = document.getElementsByTagName('body')[0].clientHeight;
		}

		var dm = new Array();
		dm['width'] = width;
		dm['height'] = height;

		return dm;
	};

	this.getWidth = function() {
		var dm = this.getDimension();
		if(dm === false) return false;
		return dm['width'];
	};

	this.getHeight = function() {
		var dm = this.getDimension();
		if(dm === false) return false;
		return dm['height'];
	};

	this.getMouseXY = function(ev) {

		var xy = new Array();
		var e = ev ? ev : window.event;

		xy[0] = e.clientX;
		xy[1] = e.clientY;

		return xy;
	};
};

// ----------------------------------------------------------
// eUtil.img
//
//     o fixPNG
// ----------------------------------------------------------

eUtil.img = new function() {

	/*
	 * eUtil.img.fixPNG
	 *
	 *	correctly handle PNG transparency in Win IE 5.5 & 6.
	 */
	
	this.fixPNG = function() {
		var arVersion = navigator.appVersion.split("MSIE");
		var version = parseFloat(arVersion[1]);
		if ((version >= 5.5) && (document.body.filters)) {
			for(var i=0; i<document.images.length; i++) {
				var img = document.images[i];
				var imgName = img.src.toUpperCase();
				if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
					var imgID = (img.id) ? "id='" + img.id + "' " : "";
					var imgClass = (img.className) ? "class='" + img.className + "' " : "";
					var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
					var imgStyle = "display:inline-block;" + img.style.cssText;
					if (img.align == "left") imgStyle = "float:left;" + imgStyle;
					if (img.align == "right") imgStyle = "float:right;" + imgStyle;
					if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
					var strNewHTML = "<span " + imgID + imgClass + imgTitle;
					+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";";
					+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader";
					+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"; 
					img.outerHTML = strNewHTML;
					i = i-1;
				}
			}
		}    
	};
};

function eduSetNextPrevLinks(divId, func, min, max, maxIndex, cur, maxPerPage)
{
	// alert("min: " + min + " max: " + max + "  maxIndex: " + maxIndex + " cur: " + cur + " maxPerPage: " + maxPerPage);
	var ip = new Array();
	ip["min"] = min;
	ip["max"] = max;
	ip["maxIndex"] = maxIndex;
	ip["cur"] = cur;
	ip["maxPerPage"] = maxPerPage;
	eduSetNextPrevDiv(ip, divId, func);
}

function eduSetNextPrevDiv(ip, divId, func)
{
	var min = parseInt(ip["min"]);
	var max = parseInt(ip["max"]) + 1;
	var cur = parseInt(ip["cur"]);
	var maxIndex = parseInt(ip["maxIndex"]); // total indices to be shown
	var maxPerPage = parseInt(ip["maxPerPage"]);

	var numIdx = (max - min - ((max - min) % maxPerPage)) / maxPerPage;
	if((max - min) % maxPerPage != 0) numIdx++;

	var firstIdx = 1;
	var lastIdx = firstIdx + maxIndex - 1;
	if(cur > (maxIndex / 2))
	{
		var tmp = parseInt(maxIndex / 2);
		firstIdx = cur - tmp;
		lastIdx = cur + tmp;
		if(maxIndex % 2 == 0) lastIdx--;
	}
	if(lastIdx > numIdx) lastIdx = numIdx;
	if(lastIdx - firstIdx < (maxIndex - 1)) firstIdx -= (maxIndex - 1 - (lastIdx - firstIdx));
	if(firstIdx < 1) firstIdx = 1;
	// alert("firstIdx: " + firstIdx + " lastIdx: " + lastIdx + " numIdx: " + numIdx);

	var str = "";
	str += "<table class='no_border'> <tr>";
	// str += "<table > <tr>";
	// str += "<td width=20%> </td>";
	for(var i = -4, idx = firstIdx; idx <= (lastIdx + 4); i++, idx++)
	{
		var nidx;
		var disp;
		var align = "center";
		var link = 1;
		var width = 5;

		if(idx == (lastIdx + 4))
		{
			// if(lastIdx == cur) link = 0;
			if(lastIdx == numIdx)
			{
				// continue;
				disp = '<img src="/data/images/common/site/all/last_inactive.gif">';
				link = 0;
			}
			else {
			nidx = numIdx;
			// disp = "Last >>";
			disp = '<img src="/data/images/common/site/all/last_active.gif">';
			// align = "left";
			width = 10;
			}
		}
		else if(idx == (lastIdx + 1))
		{
			if(lastIdx + 10 > numIdx) continue;
			nidx = lastIdx + 10;
			// disp = "Next";
			disp = nidx;
			// align = "left";
		}
		else if(idx == (lastIdx + 2))
		{
			if(lastIdx + 60 > numIdx) continue;
			nidx = lastIdx + 60;
			// disp = "Next";
			disp = nidx;
			// align = "left";
		}
		else if(idx == (lastIdx + 3))
		{
			if(lastIdx == cur)
			{
				disp = '<img src="/data/images/common/site/all/next_inactive.gif">';
				link = 0;
				// continue;
			}
			else {
			nidx = cur + 1;
			// disp = "Next";
			// disp = ">";
			disp = '<img src="/data/images/common/site/all/next_active.gif">';
			// align = "left";
			}
		}
		else if (i == -3)
		{
			idx--;
			if(cur <= 1)
			{
				// continue;
				disp = '<img src="/data/images/common/site/all/prev_inactive.gif">';
				link = 0;
			}
			else {
			nidx = cur - 1;
			// disp = "Previous";
			// disp = "<";
			disp = '<img src="/data/images/common/site/all/prev_active.gif">';
			// align = "right";
			}
		}
		else if (i == -4)
		{
			idx--;
			if(firstIdx <= 1)
			{
				// continue;
				disp = '<img src="/data/images/common/site/all/first_inactive.gif">';
				link = 0;
			}
			else {
			nidx = 1;
			// disp = "Previous";
			// disp = "<< First";
			disp = '<img src="/data/images/common/site/all/first_active.gif">';
			// align = "right";
			width = 10;
			}
		}
		else if (i == -1)
		{
			idx--;
			if(firstIdx <= 10) continue;
			nidx = firstIdx - 10;
			// disp = "Previous";
			disp = nidx;
			// align = "right";
		}
		else if (i == -2)
		{
			idx--;
			if(firstIdx <= 60) continue;
			nidx = firstIdx - 60;
			// disp = "Previous";
			disp = nidx;
			// align = "right";
		}
		else
		{
			if(idx == cur) link = 0;
			nidx = idx;
			disp = idx;
		}

		if(idx != numIdx && 
				(((idx == lastIdx) && (lastIdx + 10 > numIdx)) ||
				 ((idx == lastIdx + 1) && (lastIdx + 10 < numIdx && lastIdx + 60 > numIdx)) ||
				 (idx == lastIdx + 2 && (lastIdx + 60 < numIdx))))
			disp += "...";

		// str += "<td width=" + width + "% align=" + align + ">";
		str += "<td class=" + (link ? "navigation_active_td" : "navigation_inactive_td" )+ " align=" + align + ">";
		// str += "<td align=" + align + ">";
		if(link)
		{
			str += "<a style='text-decoration:none' href=\"\" onclick=\"" + func + "(" + nidx  + "); return false;\">";
			str += disp;
			str += "</a>";
		}
		else str += "<b>" + disp + "</b>";
		str += "</td>";
	}
	// str += "<td width=20%> </td>";
	str += "</tr> </table>";

	document.getElementById(divId).innerHTML = str;
}

// TODO no need of this function; remove it asap
function getAjaxResponse(url)
{
	return eUtil.ajax.getData(url);
}

/* getInitials()
 *
 * abbreviates the input string
 *
 * returns
 *     . the string itself if it has only one word
 *     . else concatenates the initials after ignoring
 *     . words with 3 or less characters
 */
function getInitials(s)
{
	var retStr = '';
	var str = s.toUpperCase();
	var words = str.split(' ');
	if(words.length == 1) return s;
	for(var i = 0; i < words.length; i++)
	{
		if(words[i].length <= 3) continue;
		retStr += words[i].charAt(0);
	}

	return retStr;
}

function htmlspecialchars (string, quote_style, charset, double_encode) {
    // Convert special characters to HTML entities  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/htmlspecialchars    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'
		if(string == null) return "";
    var optTemp = 0,
        i = 0,        noquotes = false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
     var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
	    if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            } else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }
     return string;
}

