/**

@Author: Munjal Amit------------Amit Munjal
@Functionality: LIBRARY FUNCTIONS

**/

/**
*
Function for Numeric Check
*
**/
function chkNumeric(strString)
//  check for valid numeric strings	
{
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;
	
	if (strString.length == 0) return false;
	 //  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	  {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 {
		 blnResult = false;
		 }
	  }
	return blnResult;
}

/**
*
Fucntion to check the Phone number is numeric or not
*
**/
function chkPhoneNumber(strString)
//  check for valid numeric strings	
{
	var strValidChars = "0123456789-";
	var strChar;
	var blnResult = true;
	
	if (strString.length == 0) return false;
	 //  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	  {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 {
		 blnResult = false;
		 }
	  }
	return blnResult;
}
/**
*
Function for Email Check
*
**/
function echeck(str) {

 		var at="@";

 		var dot=".";

 		var lat=str.indexOf(at);

 		var lstr=str.length;

 		var ldot=str.indexOf(dot)

 		if (str.indexOf(at)==-1){

 		   //alert("Invalid Email address");

 		   return false;
 		}

 		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){

 		   //alert("Invalid Email address !");

 		   return false;
 		}

 		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){

 		    //alert("Invalid Email address !");

 		    return false;
 		}

 		 if (str.indexOf(at,(lat+1))!=-1){

 		    //alert("Invalid Email address !");

 		    return false;
 		 }

 		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){

 		    //alert("Invalid Email address !");

 		    return false;
 		 }
 		 if (str.indexOf(dot,(lat+2))==-1){

 		    //alert("Invalid Email address !");

 		    return false;
 		 }

 		 if (str.indexOf(" ")!=-1){

 		    //alert("Invalid Email address !");

 		    return false;
 		 }

  		 return true;
}

/**
*
A Small Library
@Amit Munjal
*
**/
function $V(fieldId)
{
	return document.getElementById(fieldId).value;
}

function $F(fieldId)
{
	return document.getElementById(fieldId).focus();
}

function $HTML(fieldId)
{
	return document.getElementById(fieldId).innerHTML;	
}

function $Id(fieldId)
{
	return document.getElementById(fieldId);
}
/**
*
Convert the Time into the Database Acceptable Format
*
**/
function convertTimeFormatForDatabase(currentTimeFormat)
{
	splitTime = currentTimeFormat.split(":");
	
	Hour = parseInt(splitTime[0]);
	if(Hour == 0) {
		Hour = splitTime[0];
	}
	
	splitMinuteTime = splitTime[1].split(' ');
	Minute = parseInt(splitMinuteTime[0]);
	if(Minute == 0) {
		Minute = splitMinuteTime[0];
	}
	AmPm = splitMinuteTime[1];
	if((AmPm.toUpperCase() == "AM") && (Hour == 12))
		Hour = 0;
	if((AmPm.toUpperCase() == "PM") && (Hour < 12))
		Hour = Hour + 12;
	
	timeFormatForDatabase = Hour + ':' + Minute + ':' + '00';
	return timeFormatForDatabase;
}
/**
*
Convert the Date into the Database Acceptable Format
*
**/
function convertDateFormatForDatabase(currentDateFormat)
{
	var splitDate = currentDateFormat.split("/");
		
	Month = splitDate[0];
	Day = splitDate[1];
	Year = splitDate[2];
	
	dateFormatForDatabase = Year + '-' + Month + '-' + Day;
	
	return dateFormatForDatabase;
}
/**
*
Convert Time Format for users as per our TimePicker
*
**/
function convertTimeFormatForUsers(currentDateTimeFormat)
{
			//Split the Date(Database) in Date and Time
			splitDateAndTime = currentDateTimeFormat.split(' ');
			//Split the Time in Hours and Mins
			splitTime = splitDateAndTime[1].split(':');

			//Hour = parseInt(splitTime[0]);
			//Minute = parseInt(splitTime[1]);
			
			Hour = splitTime[0];
			Minute = splitTime[1];
			
			if(Hour == 0) {
				
				AmPm = 'AM';
				Hour = 12;
			} else if(Hour > 12) {
				
				AmPm = 'PM';
				Hour = Hour - 12;
			} else if(Hour == 12){
				
				AmPm = 'PM';	
			} else
				AmPm = 'AM';
				
			/*if(Hour > 0 && Hour < 10)	
				Hour = '0' + Hour;
				
			if(Minute >= 0 && Minute < 10)
				Minute = '0' + Minute;*/
			timeFormatForUsers = Hour + ':' + Minute + ' ' + AmPm;
			return timeFormatForUsers;
}
/**
*
Convert Date Format for users as per our DatePicker
*
**/
function convertDateFormatForUsers(currentDateTimeFormat)
{
	//Split the Date(Database) in Date and Time
	splitDateAndTime = currentDateTimeFormat.split(' ');

		splitDate = splitDateAndTime[0].split('-');	
		splitYear = splitDate[0];
		splitMonth = splitDate[1];
		splitDay = splitDate[2];
		
		dateFormatForUsers = splitMonth + '/' + splitDay + '/' + splitYear;

		return dateFormatForUsers;
}
/**
*
Fill the options in the dropdown(named with attendeeBindWithSession) on the Attendee form 
*
**/
//function addOptions(sessionID, sessionName)
function addOptions(dropDownValue, dropDownText, dropDownId)
{
	var newOtion = document.createElement('option');
	
	//Fill the text field of dropdown in the Attendee form.
	newOtion.text = dropDownText;
	
	//Fill the value field of option of dropdown in Attendee form
	newOtion.value = dropDownValue;
	
	//var dropDownId = $Id('attendeeBindWithSession');
	dropDownId.options.add(newOtion);
}
/**
*
Remove the pre-populated options from the dropdown(named with attendeeBindWithSession) on the Attendee form
*
**/
function removeOptions(dropDownId)
{
//var dropDownId = $Id('attendeeBindWithSession');

	for(i=dropDownId.options.length - 1;i>=1;i--)
	{
		//if(dropDown.options[i].selected)//If you want to remove the selected option in dropdown
			dropDownId.remove(i)
	}
}
/**
*
Change the Value of Legend in Fieldset
Set the InnerHTML of Legend Tag----------------Not Working
*
**/
function changeLegendValue()
{
	$Id('logisticsLegend').innerHTML = 'Add logistics';
}
/**
*
Function for Create A Div Block in The Session Form(Dynamically Created Div Blocks).
*
**/
function createABlock(hiddenInputFieldId,hiddenInputElementName,containerId)
{
	
	var newDiv = document.createElement('div');
		//newDiv.setAttribute("class","dragbox");
		newDiv.setAttribute("id","block-" + hiddenInputFieldId);
		newDiv.style.margin = "5px 2px";
		newDiv.style.background = "#fff";
		newDiv.style.position = "relative";
		newDiv.style.border = "1px solid #ddd";
		
	//var hiddenInputElementName = $V('hiddenElementForName-' + hiddenInputFieldId);
	var h1Element = document.createElement('h2');
		h1Element.appendChild(document.createTextNode(hiddenInputElementName));
		
		h1Element.style.fontSize = "12px";
		h1Element.style.padding = "7px";
		h1Element.style.background = "#f0f0f0";
		h1Element.style.color = "#000";
		h1Element.style.margin = "0";
		//h1Element.style.border = "0 0 0 1px solid #eee";
		h1Element.style.cursor = "move";
		h1Element.style.fontFamily = "Tahoma,Verdana";
		
		newDiv.appendChild(h1Element);
	
	var hiddenInputElementForId = document.createElement('input');
		hiddenInputElementForId.setAttribute('type', 'hidden');
		hiddenInputElementForId.setAttribute('value', hiddenInputFieldId);
		hiddenInputElementForId.setAttribute('id','hiddenElementForId-' + hiddenInputFieldId);
		newDiv.appendChild(hiddenInputElementForId);
	
	var hiddenInputElementForName = document.createElement('input');
		hiddenInputElementForName.setAttribute('type', 'hidden');
		hiddenInputElementForName.setAttribute('value', hiddenInputElementName);
		hiddenInputElementForName.setAttribute('id','hiddenElementForName-' + hiddenInputFieldId);
		newDiv.appendChild(hiddenInputElementForName);
		
		containerId.appendChild(newDiv);
}
/**
*
Function for Create A Div Block in The Attendee Form(Dynamically Created Div Blocks).
*
**/
function createABlockForAttendeeBindingWithSessions(hiddenInputFieldId,hiddenInputElementName,containerId)
{
	var newDiv = document.createElement('div');
		//newDiv.setAttribute("class","dragbox");
		newDiv.setAttribute("id","blockSession-" + hiddenInputFieldId);
		newDiv.style.margin = "5px 2px";
		newDiv.style.background = "#fff";
		newDiv.style.position = "relative";
		newDiv.style.border = "1px solid #ddd";
		
	//var hiddenInputElementName = $V('hiddenElementForName-' + hiddenInputFieldId);
	var h1Element = document.createElement('h2');
		h1Element.appendChild(document.createTextNode(hiddenInputElementName));
		
		h1Element.style.fontSize = "12px";
		h1Element.style.padding = "7px";
		h1Element.style.background = "#f0f0f0";
		h1Element.style.color = "#000";
		h1Element.style.margin = "0";
		//h1Element.style.border = "0 0 0 1px solid #eee";
		h1Element.style.cursor = "move";
		h1Element.style.fontFamily = "Tahoma,Verdana";
		
		newDiv.appendChild(h1Element);
	
	var hiddenInputElementForId = document.createElement('input');
		hiddenInputElementForId.setAttribute('type', 'hidden');
		hiddenInputElementForId.setAttribute('value', hiddenInputFieldId);
		hiddenInputElementForId.setAttribute('id','hiddenElementSessionId-' + hiddenInputFieldId);
		newDiv.appendChild(hiddenInputElementForId);
	
	var hiddenInputElementForName = document.createElement('input');
		hiddenInputElementForName.setAttribute('type', 'hidden');
		hiddenInputElementForName.setAttribute('value', hiddenInputElementName);
		hiddenInputElementForName.setAttribute('id','hiddenElementSessionName-' + hiddenInputFieldId);
		newDiv.appendChild(hiddenInputElementForName);
		
		containerId.appendChild(newDiv);
}



/**
*
Impromptu Alert Box For Validation
*
**/
function alertBoxForValidation(fieldName, fieldId)
{
		$.prompt('Please fill the '+fieldName,{ 
				 						show:'slideDown', 
										prefix: 'impromptu', 
										callback: function(v,m,f){
													$F(fieldId);
												} 
											}); 
}
/**
*
Impromptu Alert Box For Message
*
**/
function alertBoxForMessage(alertMessage)
{
	$.prompt(alertMessage, { prefix: 'impromptu' });
}

/**
*
JSON ENCODER
*
**/

JSON = {
  encode : function(input) {
    if (!input) return 'null'
    switch (input.constructor) {
      case String: return '"' + input + '"'
      case Number: return input.toString()
      case Array :
        var buf = []
        for (i in input)
          buf.push(JSON.encode(input[i]))
            return '[' + buf.join(', ') + ']'
      case Object:
        var buf = []
        for (k in input)
          buf.push(k + ' : ' + JSON.encode(input[k]))
            return '{ ' + buf.join(', ') + '} '
      default:
        return 'null'
    }
  }
}

/**
*
Returns the given string wrapped at the specified column.
*
**/

function wordwrap( str, width, brk, cut ) {
 
  return str; // rommy - return string as it is... because some times it gives error.
 
    brk = brk || '\n';
    width = width || 75;
    cut = cut || false;
 
    if (!str) { return str; }
 
    var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
 
    return str.match( RegExp(regex, 'g') ).join( brk );
 
}


function json_decode(str_json) {
    // Decodes the JSON representation into a PHP value  
    // 
    // version: 901.2515
    // discuss at: http://phpjs.org/functions/json_decode
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');
    // *     returns 1: ['e', {pluribus: 'unum'}]
    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;

    var walk = function(holder, key) {
        // The walk method is used to recursively walk the resulting structure so
        // that modifications can be made.
        var k, v, value = holder[key];
        if (value && typeof value === 'object') {
            for (k in value) {
                if (Object.hasOwnProperty.call(value, k)) {
                    v = walk(value, k);
                    if (v !== undefined) {
                        value[k] = v;
                    } else {
                        delete value[k];
                    }
                }
            }
        }
        return reviver.call(holder, key, value);
    }

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
    if (/^[\],:{}\s]*$/.
        test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.

        j = eval('(' + text + ')');

        // In the optional fourth stage, we recursively walk the new structure, passing
        // each name/value pair to a reviver function for possible transformation.

        return typeof reviver === 'function' ?
        walk({
            '': j
        }, '') : j;
    }

    // If the text is not JSON parseable, then a SyntaxError is thrown.
    throw new SyntaxError('json_decode');
}

//Trim function
function trim(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

function asort (inputArr, sort_flags) {

    var valArr=[], keyArr=[], k, i, ret, sorter, that = this, strictForIn = false, populateArr = {};

    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {
                return that.strnatcmp(a, b);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6)
            var loc = this.i18n_loc_get_default();
            sorter = this.php_js.i18nLocales[loc].sorting;
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return (a - b);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                var aFloat = parseFloat(a),
                    bFloat = parseFloat(b),
                    aNumeric = aFloat+'' === a,
                    bNumeric = bFloat+'' === b;
                if (aNumeric && bNumeric) {
                    return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0;
                }
                else if (aNumeric && !bNumeric) {
                    return 1;
                }
                else if (!aNumeric && bNumeric) {
                    return -1;
                }
                return a > b ? 1 : a < b ? -1 : 0;
            };
            break;
    }

    var bubbleSort = function (keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i >= 0; i--) {
            for (j = 0; j <= i; j++) {
                ret = sorter(inputArr[j+1], inputArr[j]);
                if (ret < 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }
        }
    };

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && 
                    this.php_js.ini['phpjs.strictForIn'].local_value !== 'off';
    populateArr = strictForIn ? inputArr : populateArr;

    // Get key and value arrays
    for (k in inputArr) {
        if (inputArr.hasOwnProperty(k)) {
            valArr.push(inputArr[k]);
            keyArr.push(k);
            if (strictForIn) {
                delete inputArr[k];
            }
        }
    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);
    } catch (e) {
        return false;
    }

    // Repopulate the old array
    for (i = 0; i < valArr.length; i++) {
        populateArr[keyArr[i]] = valArr[i];
    }

    return strictForIn || populateArr;
}

function deleteAllBlocks(containerId) {

	while (containerId.hasChildNodes()) {
		containerId.removeChild(containerId.lastChild);
	}
}
