//
// Function to Delete a cookie
//
function DelCookie(sName)
{
  document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

//
// Function to Delete a cookie
//
function SetCookie(sName, sValue)
{
	var date = new Date();
	date.setFullYear(2199,1,1);
	document.cookie = sName + "=" + escape(sValue) + "; expires="+date.toUTCString()+";";
}

//
// Pops up a Modal Dialog containing "message", and return 
// Very Similar to the window.alert( message ), except that the 
// Ok button caption is customizable, the style is also cutomizable
// IMPORTANT NOTE: this currently works on ** INTERNET EXPLORER 5+ ONLY ** 
function CustomAlert( message, title, OkCaption, width, height, dialogURL )
{
	if( ! (navigator.appName.indexOf("Microsoft") >= 0) ) { alert( message ); return; };

	// Make sure height and width of dialog are ok.
	var w = parseInt( width );
	var h = parseInt( height );
	if ( isNaN( w ) ) w = 320; if( w < 320 ) w = 320;
	if ( w > screen.width ) w = screen.width;
	if ( isNaN( h ) ) h = 120; if( h < 120 ) h = 120;
	if ( h > screen.height ) h = screen.height;
	
	// Initialize URL
	var sURL = dialogURL ? dialogURL : "CustomDialog.html";
	
	// Initialize Arguments
	var vArguments = Array();
	vArguments["Message"] = message;
	vArguments["OkCaption"] = OkCaption;
	vArguments["Title"] = title;
	vArguments["DialogType"] = "Alert";
	
	// The width, height and other features of the dialog
	var sFeatures = "dialogHeight: "+h+"px; dialogWidth: "+w+"px; edge: Raised; center: yes; help: no; resizable: no; status: no; menu: no";
	
	// Open Dialog and Return 
	// (true if confirmed, false if not or if closed)
	window.showModalDialog(sURL, vArguments, sFeatures);
}


//
// Pops up a Modal Dialog containing "message", and return 
// Very Similar to the window.confirm( message ), except that the 
// Ok and Cancel buttons captions are customizable, the style is also cutomizable
// IMPORTANT NOTE: this currently works on ** INTERNET EXPLORER 5+ ONLY ** 
function CustomConfirm( message, YesCaption, NoCaption, title, width, height, dialogURL )
{
	if( ! (navigator.appName.indexOf("Microsoft") >= 0) ) return confirm( message );

	// Make sure height and width of dialog are ok.
	var w = parseInt( width );
	var h = parseInt( height );
	if ( isNaN( w ) ) w = 320; if( w < 320 ) w = 320;
	if ( w > screen.width ) w = screen.width;
	if ( isNaN( h ) ) h = 120; if( h < 120 ) h = 120;
	if ( h > screen.height ) h = screen.height;
	
	// Initialize URL
	var sURL = dialogURL ? dialogURL : "CustomDialog.html";
	
	// Initialize Arguments
	var vArguments = Array();
	vArguments["Message"] = message;
	vArguments["YesCaption"] = YesCaption;
	vArguments["NoCaption"] = NoCaption;
	vArguments["Title"] = title;
	vArguments["DialogType"] = "Confirm";
	
	// The width, height and other features of the dialog
	var sFeatures = "dialogHeight: "+h+"px; dialogWidth: "+w+"px; edge: Raised; center: yes; help: no; resizable: no; status: no; menu: no";
	
	// Open Dialog and Return 
	// (true if confirmed, false if not or if closed)
	var vReturnValue = window.showModalDialog(sURL, vArguments, sFeatures);
	return vReturnValue;
}

/**
 *  << JavaScript Functions [Utilities] File >>
 *  Please do not distribute
 *
 *  Author: Fadi Chamieh
 *  =======
 */
function trimSpaces ( str ) {

	var trimmed = '';
	var start_edge = 0;
	var end_edge = 0;

	// Detect start edge
	for(var i = 0; i < str.length; i++)
		if (str.charAt(i) != ' ') {
			start_edge = i;
			break;
		}
	// Detect end edge
	for(i = str.length - 1; i > 0; i--)
		if (str.charAt(i) != ' ') {
			end_edge = i;
			break;
		}
	// Get what's between edges
	for(i = start_edge; i <= end_edge; i++)
		trimmed += str.charAt(i);

	if (trimmed == ' ') trimmed = '';

	return trimmed;

} // end function trimSpaces


function areCharsIn( checkStr, validCharsStr ){

	var checkOK = validCharsStr;
	var allValid = true;
	checkStr += '';

	// if empty return false
	if (checkStr == '') return false;

	for (i = 0;  i < checkStr.length;  i++)	{

		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
				break;

		if (j >= checkOK.length) {
			allValid = false;
			break;
		}
	}
	return ( allValid );
}

function isAlphaNumeric( checkStr ) {
	return areCharsIn(checkStr, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_");
}

function isNumeric( checkStr ) {
	return areCharsIn(checkStr, "0123456789.+-,");
}

// Check if an email (string) is a valid email address via a regular expression
function isValidEmail( testEmail ) {
	if (testEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1)
		return false;
	else
		return true;
}

// Check if the string is a valid email list (default is seperated by commas)
function isValidEmailList( emList, seperator ) {
	if (!seperator) seperator = ",";
	var emList = trimSpaces(emList);
	if (emList == '') return false;
	
	var emails = emList.split(seperator);
	for(i = 0; i < emails.length; i++) { 
		if(! isValidEmail(trimSpaces(emails[i]))) return false;
	}
	
	return true;	

}

// Calculate the date difference in millisec
function dateDiff(date1Str, date2Str) {
	var date1, date2, diff, timediff;
	
	date1 = new Date();
	date2 = new Date();
	
	date1.setMilliseconds(Date.parse(date1Str));
	date2.setMilliseconds(Date.parse(date2Str));
	diff = new Date();
	
	window.status = date1.toDateString();
	
	diff.setTime(Math.abs(date1.getTime() - date2.getTime()));
	
	timediff = diff.getTime(); // in milliseconds

	return parseInt(timediff /  1000);

} 
 
 
//////////////////////////////////////////////
function isDate(dateStr, message) 
{
	if(! message) message = "الرجاء ادخال تاريخ صحيح (سنة-شهر-يوم, شهر/يوم/سنة أو شهر-يوم-سنة).";
	
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) {
	    datePat = /^(\d{4})(-)(\d{1,2})(-)(\d{1,2})$/;
		matchArray = dateStr.match(datePat); // is the other format ok?
			if (matchArray == null) {
				CustomAlert( message );
				return false;
			}
			else
			{
				year = matchArray[1]; // parse date into variables
			    month = matchArray[3];
				day = matchArray[5];
			}
	}
    else
    {
        month = matchArray[1]; // parse date into variables
	    day = matchArray[3];
		year = matchArray[5];
    }

    if (month < 1 || month > 12) { // check month range
        CustomAlert(message + "\nالشهر يجب أن يكون بين 1 و 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        CustomAlert(message + "\nاليوم يجب أن يكون بين 1 و 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        CustomAlert(message + "\nشهر "+month+" ليس فيه 31 يوما!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            CustomAlert(message + "\nشباط " + year + " ليس فيه " + day + " يوما!");
            return false;
        }
    }
    return true; // date is valid
}  


 /**
  * Search for an item in a drop down list
  */
 function selectSearcher(theSelectName, theSearchInput)
 {
	var theSelect = (theSearchInput.form.elements[theSelectName]);
	theValue = theSearchInput.value;
	
	if((! theSelect) || (! theValue) ) return;
	
	var bestOption = -1;
	var bestOptionAt = -1;
	
	var lookFor = new String();
	lookFor = "" + theValue;
	lookFor = lookFor.toLowerCase();
	
	// Loop through the Options
	for(var i = 0; i < theSelect.options.length; i++)
	{
		var tested = new String();
		tested = theSelect.options[i].text.toLowerCase();
		var foundAt = tested.indexOf( lookFor );
		if( foundAt >= 0 && ( bestOptionAt == -1 || (bestOptionAt > foundAt) ) )
		{
			bestOption = i;
			bestOptionAt = foundAt;
		}
	}
	theSelect.selectedIndex = bestOption;
 }
 
// Check if a form input is empty, also checks for emails
function isEmptyField( formItem, display )
{
	if(! formItem ) return;
	
	var canFocus = (formItem.type.toLowerCase().indexOf("hidden") >= 0) ? false : true;
	
	if(trimSpaces(formItem.value) == "")
		{
			CustomAlert("الرجاء ادخال " + display);
			if(canFocus) formItem.focus();
			return true;
		}
	else
		if(display.toLowerCase().indexOf("email") >= 0)
		{
			if (! isValidEmail(formItem.value)){
				CustomAlert("الرجاء ادخال بريد الكتروني صالح");
				if(canFocus) formItem.focus();
				return true;
			}
		}
		return false;
}

/*
 * Remove Commas from a string (see formatMoney)
 */
function stripCommas( strValue )
{
	var value = new String();
	value = "" + strValue;
	return value.replace(/[,]/g,"");
}

/**
 * Format a number as money by grouping digits : ex: 123,456,789
 */
function formatMoney( strValue )
{
	var notFormatted = new String();
	notFormatted = stripCommas( strValue );
	
	var value = parseFloat(notFormatted);
	if(isNaN(value)) return "0";
	
	notFormatted = "" + value;
	var formatted = new String();
	
	for(var i = notFormatted.length - 1; i >= 0 ; i-=3)
	{
		var end = i-2;
		if(end < 0) end = 0;
		if(i < notFormatted.length - 1) 
			formatted = notFormatted.substring(end, i+1)+ "," + formatted;
		else	
			formatted = notFormatted.substring(end, i+1);
	}
	return formatted;
}

// #region Used For Spelling
var DigitPlace = new Array( "-", "Thousand", "Million", "Billion", "Trilion" );
var Digits = new Array( "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" );
var FromTenToTwenty = new Array( "Ten", "Eleven", "Twelve", "Thirteen", "Forteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" );
var Tens = new Array( "-", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" );
// #endregion Used For Spelling

// Function that spells a number into words
function spellWordsOf( amount )
{
	amount = parseInt(amount);
	if (isNaN(amount)) return "";
	
	var sb = new String();
	var amountString = new String();
	amountString = "" + amount;

    var amountDigits =  new Array(); 
    var amountDigitValues = new Array();
    for(var i = 0; i < amountString.length; i++ ) {
		amountDigits[i] = amountString.charAt(i);
		amountDigitValues[i] = 0;
	}
			
	// If only a single digit, go back quickly
	if (amount < 10 && amount > -10) 
	{
		if(amount < 0) 
		{
			sb += "Minus ";
			amount = -amount;
		}
		sb += (Digits[amount]);
		
		return sb;

	}
    
	// Loop through digits from most to least significant 			
	for(var i = 0; i < amountDigits.length; i++)
	{
		if( amountDigits[i] != '-' ) amountDigitValues[i] = parseInt(amountDigits[i]);

		var offset = amountDigits.length - i - 1;

		// If Negative sign
		if( amountDigits[i] == '-' )
			sb += ("Minus ");
		else if(amountDigitValues[i] > 0)
		{
			// For Trillions, Millions and Thousands
			if(offset > 2)
			{
				var nextOffset = offset - (offset % 3);
				var chunk = amountString.substring(i, (offset % 3) + 1);
				i = amountDigits.length - nextOffset - 1;
				var digitOffset = parseInt((offset / 3));
				
				sb += ( spellWordsOf( chunk ) );
				sb += (" ");
				sb += ( DigitPlace[ digitOffset ] ); // Append Place (Thousand, Million)
				sb += (" ");
			}

			else if(offset == 2) // hundreds 
			{
				sb += ( Digits[ amountDigitValues[i] ] ); // Append prefix
				sb += (" ");
				sb += ( "Hundred " ); // Append Place (Hundred, Thousand)
			}
			else if(offset == 1) // Tens
			{
				if(amountDigitValues[i] == 1) // From ten to twenty
				{
					amountDigitValues[i + 1] = parseInt(amountDigits[i + 1]);
					sb += ( FromTenToTwenty[ amountDigitValues[i + 1] ] );
					sb += (" ");
					i++;
				}
				else
				{
					sb += ( Tens[ amountDigitValues[i] ] ); // Append prefix
					sb += (" ");
				}
			}
			else if(offset == 0) // Solo Digits
			{
				sb += ( Digits[ amountDigitValues[i] ] ); // Append prefix
				sb += (" ");
			}

		} // end else digit not 0

	} // end for loop on digits 
	
	return trimSpaces(sb);

} // end spellWordsOf


/*
 * Author :  Fadi Chamieh
 * Purpose:  return an arabic representation of current date
 */

function getCurrentDate()
{
	return getCurrentDate(false);
}
function getCurrentDate( language ) {
	

	if( ! language ) language = "arabic";
	
	var _DayNamesArr = new Array();
	var _MonthNamesArr = new Array();
	
	_DayNamesArr["arabic"] = new Array("الأحد","الاثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت");
	_MonthNamesArr["arabic"] = new Array("يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر");

	// _DayNamesArr["english"] = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
	// _MonthNamesArr["english"] = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

	var theString = "";
	var days = _DayNamesArr[ language ];
	var months = _MonthNamesArr[ language ];
	var today = new Date();
	theString += (days[today.getDay()]+" ");
	theString += (today.getDate()+" ");
	theString += (months[today.getMonth()] + " ");
	theString += (today.getFullYear()+" ");//was getYear()
	return theString;
}

function PopRelatedDiv()
{
	var RelatedDetailsTD = document.getElementById("RelatedDetailsTD");
	var RelatedItemsPlusMinus = document.getElementById("RelatedItemsPlusMinus");
	if( RelatedDetailsTD.style.display == "" )
	{
		RelatedDetailsTD.style.display = "none";
		RelatedItemsPlusMinus.innerHTML = "[+]";
	}
	else
	{
		RelatedDetailsTD.style.display = "";
		RelatedItemsPlusMinus.innerHTML = "[-]"
	}
}
