/*
File:common.js
Company: IRAcom Co.
Copyright: 2008  (c)

Version  	Author			  Date  		 Comment
---------------------------------------------------------------------------------
0.1         Navid Yousefi     08/06/2008     Created
*/

// This function is used for check if an item is null or not
function isEmpty(item)
{
	var bRet = false;
	item = trim(item);
	if(item == '&nbsp' || item.length == 0)
		bRet = true;

	return bRet;
}

function isListBoxEmpty(listBox)
{
	var booleanReturnValue = false;
	if(listBox.length == 0)
	{
		booleanReturnValue = true;
	}
	return booleanReturnValue;
}

function isOneOfRadioButtonsChecked(radioButtonGroup)
{
	var booleanReturnValue = true;
	if(!radioButtonValidation(radioButtonGroup))
	{
		booleanReturnValue = false;
	}
	return booleanReturnValue;
}

function checkRadioButtonByKey(radioButtonGroup, key)
{
	var numRadios = radioButtonGroup.length ;

	for(var i = 0; i < numRadios; i++)
	{
		if(radioButtonGroup[i].value == key)
		{
			radioButtonGroup[i].checked = true;
		}
	}
}

function isFloatNumber(num)
{
	var numberPattern = /^[+-]?\d*\.?\d*$/;
	return numberPattern.test(trim(num));

}

function validateNumber(num)
{
	var numberPattern = /^[+-]?\d+$/;
	return numberPattern.test(trim(num));

}

//for compare foramt 2 dates  shamsi or miladi
function formatDate(dateString)
{

	var datePattern = /^(\d{4})(\/\d{1,2})?(\/\d{1,2})?$/;

	var year;
	if(!datePattern.test(dateString))
	{
		return false;
	}
	else
	{
		year = RegExp.$1;
		return year > 0 && year < 1700;
	}
}

// this method for the comparing one date with other .

function compareDate(dateString1, dateString2)
{
	return formatDate(dateString1) == formatDate(dateString2);
}

// function isSmallerDate gets two parameters of date string and checks
// that fromDate is smaller than to date or no
// return true if fromDate < toDate or false if fromDate > toDate
function isSmallerDate(fromDate, toDate)
{
	var datePattern = /^(\d{4})(\/\d{1,2})(\/\d{1,2})$/;
	var fromYear, toYear, fromMonth, toMonth, fromDay, toDay;

	datePattern.test(fromDate);
	fromYear = RegExp.$1;
	fromMonth = RegExp.$2;
	fromMonth = fromMonth.length == 3 ? fromMonth.replace("/", "") : fromMonth.replace("/", "0");
	fromDay = RegExp.$3;
	fromDay = fromDay.length == 3 ? fromDay.replace("/", "") : fromDay.replace("/", "0");

	datePattern.test(toDate);
	toYear = RegExp.$1;
	toMonth = RegExp.$2;
	toMonth = toMonth.length == 3 ? toMonth.replace("/", "") : toMonth.replace("/", "0");
	toDay = RegExp.$3;
	toDay = toDay.length == 3 ? toDay.replace("/", "") : toDay.replace("/", "0");

	fromDate = fromYear + fromMonth + fromDay;
	toDate = toYear + toMonth + toDay;

	return fromDate > toDate;
}

function isSmallerTime(time1, time2)
{
	var hour1 , min1 , sec1 , hour2 , min2 , sec2 ;

	var firstIndex = time1.indexOf(':') ;
	var lastIndex = time1.lastIndexOf(':') ;

	if(firstIndex == lastIndex)
		lastIndex = -1;

	if(firstIndex != -1)
	{
		hour1 = parseFloat(time1.substring(0, firstIndex));
		if(lastIndex != -1)
		{
			min1 = parseFloat(time1.substring(firstIndex + 1, lastIndex));
			sec1 = parseFloat(time1.substring(lastIndex + 1, lastIndex + 3));
		}
		else
		{
			min1 = parseFloat(time1.substring(firstIndex + 1, firstIndex + 3));
			sec1 = 0;
		}
	}
	else
	{
		hour1 = parseFloat(time1.substring(0, 2));
		min1 = 0;
		sec1 = 0;
	}

	firstIndex = time2.indexOf(':');
	lastIndex = time2.lastIndexOf(':');

	if(firstIndex == lastIndex)
		lastIndex = -1;

	if(firstIndex != -1)
	{
		hour2 = parseFloat(time2.substring(0, firstIndex));
		if(lastIndex != -1)
		{
			min2 = parseFloat(time2.substring(firstIndex + 1, lastIndex));
			sec2 = parseFloat(time2.substring(lastIndex + 1, lastIndex + 3));
		}
		else
		{
			min2 = parseFloat(time2.substring(firstIndex + 1, firstIndex + 3));
			sec2 = 0
		}
	}
	else
	{
		hour2 = parseFloat(time2.substring(0, 2));
		min2 = 0;
		sec2 = 0;
	}
	if(hour1 == hour2)
	{
		if(min1 == min2)
		{
			return sec1 < sec2;
		}
		else if(min1 < min2)
		{
			return true;
		}
	}
	else if(hour1 < hour2)
	{
		return true;
	}

	return false;
}
// function validateDate gets a string that consists a date and checks to
//  validate its date. If dateStrig have a correct syntax returns true;
//	otherwise returns false. If dateString is null return false.

function validateDate(dateString)
{
	var datePattern = /^(\d{4})(\/\d{1,2})?(\/\d{1,2})?$/;

	if(!datePattern.test(dateString))   // Checks to accomplish date syntax
	{
		return false;
	}

	var year = RegExp.$1;

	var month = RegExp.$2;
	month = month.replace("/", "");

	var day = RegExp.$3;
	day = day.replace("/", "");

	if(month.length > 0)
	{
		if(month > 12 || month <= 0)
		{
			return false;
		}
	}
	var dayCountOfMonth = getDayCountOfMonth(year, month);
	// alert(dayCountOfMonth);
	if(day.length > 0)
	{
		if(day > dayCountOfMonth || day <= 0)
		{
			return false;
		}
	}

	return true;
}


function getDayCountOfMonth(year, month, dateString)
{
	var leap = 0;
	if((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0))
	{
		leap = 1;
	}

	if(!formatDate(year))  //date is AC(ante-Christum)
	{
		// alert("month:"+month+"year:"+year);
		/* Validation  february / day */

		if((month == 2) && (leap == 1))
		{
			return 29;
		}
		if((month == 2) && (leap != 1))
		{
			//alert(" ��� ����� 28 ��� ����");
			return 28;
		}
		if(((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12)))
		{
			return 31;
		}
		if(((month == 4) || (month == 6) || (month == 9) || (month == 11)))
		{
			return 30;
		}
	}
	else
	{
		if((month >= 1) && (month <= 6))
		{
			return 31;
		}
		if((month >= 7) && (month <= 11))
		{
			return 30;
		}
		if((month == 12) && (leap == 1))
		{
			return 30;
		}
		else
		{
			return 29;
		}
	}
	return true;
}

function validateHalfDate(dateString)
{
	var datePattern = /^(\d{1,2})?(\/\d{1,2})?$/;

	if(!datePattern.test(dateString))   // Checks to accomplish date syntax
	{
		return false;
	}

	var month = RegExp.$1;

	var day = RegExp.$2;
	day = day.replace("/", "");

	if(month.length > 0)
	{
		if(month > 12 || month <= 0)
		{
			return false;
		}
	}
	if(day.length > 0)
	{
		if(day > 31 || day <= 0)
		{
			return false;
		}
	}
	return true;
}

// function validateDate gets a string that consists a date and checks to
//  validate its date. If dateStrig have a correct syntax returns true;
//	otherwise returns false. If dateString is null return false.
// This function checkes the complete format YYYY/MM/DD

function validateDateCompletly(dateString)
{

	var datePattern = /^(\d{4})(\/\d{1,2})(\/\d{1,2})$/;

	if(!datePattern.test(dateString))   // Checks to accomplish date syntax
	{
		return false;
	}

	var month = RegExp.$2;
	month = month.replace("/", "");

	day = RegExp.$3;
	day = day.replace("/", "");

	if(month.length > 0)
	{
		if(month > 12 || month <= 0)
		{
			return false;
		}
	}
	if(day.length > 0)
	{
		if(day > 31 || day <= 0)
		{
			return false;
		}
	}

	return validateDate(dateString);
}
// function validateTime gets a string that consists a time and checks to
//  validate its time. If timeStrig have a correct syntax returns true;
//	otherwise returns false. If timeString is null return false.
function validateTime(timeString)
{
	var timePattern = /^((2[0-3])|([0-1]?[0-9]))(:[0-5]?[0-9]?){0,2}$/;
	return timePattern.test(timeString);

}

function isPhoneNumberValid(phoneString)
{
	var phonePattern = /^(\d+[- ]?)*\d+$/;
	return phonePattern.test(phoneString);
}

// This function operates for grid tabs.
//  If in update or insert mode, we remove check from  chkIsConsidered checkbox this function will call.
//function confirmRowWillDeleted ( rowId )
//{
//    if ( document.frmMain.chkIsConsidered [ rowId ].checked )
//   {
//       return true;
//   }
//else
//	{
//		alert('�� ���� ������� ?� ��ʡ ј��� ���� ��� ��� ���');
//		return true;
//	}
//}


// function textAreaLengthValid gets a string that consists a time and checks to
//  valid length in the textarea field. If Strig have a correct syntax returns true;
//	otherwise returns false.

function textAreaLengthValidation(textAreaValue, length)
{
	return textAreaValue.length <= length;
}

// function  radioButtonValidation  for checking of field  radioButton

function radioButtonValidation(radioGroup)
{
	var numRadios = radioGroup.length ;

	for(i = 0; i < numRadios; i++)
	{
		if(radioGroup[i].checked)
		{
			return true;
		}
	}
	return false;
}


// function confirmMessageForDeleteRow  for  method delete  and highLighted current record
function confirmMessageForDeleteRow(item)
{
	var tempClass = document.all[item].className;
	document.all[item].className = 'TableSelectedRow';
	var bRet = confirm('��� ����� ����� �');
	if(! bRet)
		document.all[item].className = tempClass;
	return bRet;
}

function resetForm(formName)
{
	var n = document.all[formName].length;
	for(var i = 0; i < n; i++)
	{
		if(document.all[formName].elements[i].type == 'select-one')
		{
			document.all[formName].elements[i].value = '';
		}
		if((document.all[formName].elements[i].type != 'button') &&
		   (document.all[formName].elements[i].type != 'submit') &&
		   (document.all[formName].elements[i].type != 'reset') &&
		   (document.all[formName].elements[i].name != 'pageAction') &&
		   (document.all[formName].elements[i].name != 'lovProperty') &&
		   (document.all[formName].elements[i].name != 'allowableId' ) &&
		   (document.all[formName].elements[i].name != 'identifierType') &&
		   (document.all[formName].elements[i].name != 'ipidPidsId')
				)
		{

			document.all[formName].elements[i].value = '';
		}
		if((document.all[formName].elements[i].type == 'radio'))
		{

			document.all[formName].elements[i].checked = false;
		}
		if((document.all[formName].elements[i].type == 'checkbox') && (document.all[formName].elements[i].name != 'ipidPidsIdSelect'))
		{

			document.all[formName].elements[i].checked = false;
		}
	}
}

/*
	This method checked that if the d1 and have same format. This method checks number of / in both of them
  */
function haveSameFormat(d1, d2)
{
	intD1SlashNumber = 0;
	intD2SlashNumber = 0;
	newD1 = d1;
	newD2 = d2;
	if(d1 == '' || d2 == '')
	{
		return true;
	}

	while(d1.indexOf('/') != -1)
	{
		d1 = d1.substr(d1.indexOf('/') + 1);
		intD1SlashNumber ++;
	}
	while(d2.indexOf('/') != -1)
	{
		d2 = d2.substr(d2.indexOf('/') + 1);
		intD2SlashNumber ++;
	}
	if(intD1SlashNumber == intD2SlashNumber)
	{
		if(formatDate(newD1) == formatDate(newD2))
			return true;
	}
	else
	{
		return false;
	}

}

function leftTrim(item)
{
	var str = item;
	for(var i = 0; i < item.length; i++)
	{
		if(item.charAt(i) == ' ')
		{
			str = item.substring(i + 1);
		}
		else
		{
			break;
		}
	}
	return str;
}

function rightTrim(item)
{
	var str = item;
	for(var i = item.length - 1; i >= 0; i--)
	{
		if(item.charAt(i) == ' ')
		{
			str = item.substring(0, i);
		}
		else
		{
			break;
		}
	}
	return str;
}

function lrTrim(item)
{
	return leftTrim(rightTrim(item));
}

function trim(item)
{
	var str = '';
	var i = 0 ;
	while(i < item.length)
	{
		if(item.charAt(i) != ' ')
		{
			str += item.charAt(i);
		}
		i++;
	}
	return str;
}


//functions add for farsi input
//utf-8 inputter function :
langCode = 'NaN';
/*
var farKeys = new Array(1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785);
var keys = new Array(49, 50, 51, 52, 53, 54, 55, 56, 57, 58);
*/
var farKeys = new Array(1711, 0, 0, 0, 0, 1608, 0, 0, 0, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 0, 1705, 1572, 0, 1548, 1567, 0, 1588, 1584, 1586, 1740, 1579, 1576, 1604, 1570, 1607, 1578, 1606, 1605, 1574, 1583, 1582, 1581, 1590, 1602, 1587, 1601, 1593, 1585, 1589, 1591, 1594, 1592, 1580, 1688, 1670, 0, 1600, 1662, 1588, 1584, 1586, 1740, 1579, 1576, 1604, 1575, 1607, 1578, 1606, 1605, 1574, 1583, 1582, 1581, 1590, 1602, 1587, 1601, 1593, 1585, 1589, 1591, 1594, 1592);
var keys = new Array(1711, 0, 0, 0, 0, 1608, 0, 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 1603, 0, 0, 0, 1567, 0, 1614, 1573, 1688, 1616, 1613, 1617, 1728, 1570, 93, 1600, 171, 187, 1569, 1571, 91, 92, 1611, 0, 1615, 1548, 44, 1572, 1612, 1610, 1563, 1577, 1580, 1688, 1670, 0, 1600, 1662, 1588, 1584, 1586, 1740, 1579, 1576, 1604, 1575, 1607, 1578, 1606, 1605, 1574, 1583, 1582, 1581, 1590, 1602, 1587, 1601, 1593, 1585, 1589, 1591, 1594, 1592);

function keyConvTextPersian()
{            
	if((event.keyCode > 38) && (event.keyCode < 123))
	{
		event.keyCode = (farKeys[event.keyCode - 39]) ? (farKeys[event.keyCode - 39]) : event.keyCode;
	}
	if(event.keyCode == 1740)
		event.keyCode = 1610;
}

function keyConvTextPersianNum()
{
    switch (intKeyPressed)
    {
        case (48)	:intFKeyCode = 0x06F0; break;
        case (49)	:intFKeyCode = 0x06F1; break;
        case (50)	:intFKeyCode = 0x06F2; break;
        case (51)	:intFKeyCode = 0x06F3; break;
        case (52)	:intFKeyCode = 0x06F4; break;
        case (53)	:intFKeyCode = 0x06F5; break;
        case (54)	:intFKeyCode = 0x06F6; break;
        case (55)	:intFKeyCode = 0x06F7; break;
        case (56)	:intFKeyCode = 0x06F8; break;
        case (57)	:intFKeyCode = 0x06F9; break;
        }
	if(event.keyCode == 1740)
		event.keyCode = 1610;
}

var char0KeyCode = 48;
var char9KeyCode = 57;

var charSlashKeyCode = 47;

var charDotKeyCode = 46;
var charMinusKeyCode = 45;
var charPlusKeyCode = 43;
var charEnterKeyCode = 13;
var charPercentKeyCode = 37;
var charStarKeyCode = 42;


var char_A_KeyCode = 65;
var char_Z_KeyCode = 90;
var char_a_KeyCode = 97;
var char_z_KeyCode = 122;

function keyConvTextEnglish()
{
	//alert("--------->"   + event.keyCode);
	var convertedEventKey = 0;
	for(i = 0; i < 122; i++)
	{
		if(keys[i] != 0)
		{
			if(keys[i] == event.keyCode)
			{
				convertedEventKey = i + 39;
				break;
			}
		}
	}

	if(convertedEventKey != 0)
	{
		event.keyCode = convertedEventKey;
	}
}

function keyConvUpperTextEnglish()
{

	var convertedEventKey = 0;
	for(i = 0; i < 122; i++)
	{
		if(keys[i] != 0)
		{
			if(keys[i] == event.keyCode)
			{
				convertedEventKey = i + 39;
				break;
			}
		}
	}

	if(convertedEventKey != 0)
	{
		event.keyCode = convertedEventKey;
	}
	event.keyCode = String.fromCharCode(event.keyCode).toUpperCase().charCodeAt(0);
}
function keyConvLowerTextEnglish()
{

	var convertedEventKey = 0;
	for(i = 39; i < 122; i++)
	{
		if(keys[i] != 0)
		{
			if(keys[i] == event.keyCode)
			{
				convertedEventKey = i + 39;
				break;
			}
		}
	}

	if(convertedEventKey != 0)
	{
		event.keyCode = convertedEventKey.toLowerCase();
	}
	event.keyCode = String.fromCharCode(event.keyCode).toLowerCase().charCodeAt(0);
}
function switchLang()
{
	if(event.altKey && event.shiftKey)
	{
		langCode = (langCode == 'fa') ? 'en' : 'fa';
	}

}
function changeLang(lang)
{
	if(langCode == 'NaN')
		langCode = lang;

}
function resetLang()
{
	langCode = 'NaN';

}
function keyConvertBasedLanguageSelected()
{
	if(langCode == 'fa')
	{
		keyConvTextPersian();
	}
	else if(langCode == 'en_upper')
	{
		keyConvUpperTextEnglish();
	}
	else if(langCode == 'en_lower')
	{
		keyConvLowerTextEnglish();
	}
	else
	{
		keyConvTextEnglish();
	}
}
function keyConvNumber()
{
	if(((event.keyCode >= char0KeyCode) && (event.keyCode <= char9KeyCode))
			|| (event.keyCode == charDotKeyCode)
			|| (event.keyCode == charMinusKeyCode)
			|| (event.keyCode == charPlusKeyCode)
			|| (event.keyCode == charEnterKeyCode)
			|| (event.keyCode == charStarKeyCode)
			)
	{

	}
	else
	{
		alert('���� ��� ���� ����');
		event.keyCode = 0;
	}
}

function keyConvDate()
{
	if((event.keyCode >= char0KeyCode) && (event.keyCode <= char9KeyCode))
	{
	}
	else if((event.keyCode == charSlashKeyCode)
			|| (event.keyCode == charStarKeyCode)
			|| (event.keyCode == charEnterKeyCode))
	{
	}
	else
	{
		alert('���� ����� ���� ����');
		event.keyCode = 0;
	}
}


//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
//autosearch scripts moving here:
function as_onSelectKeyDown(keyField)
{
	if(window.event.keyCode == 46)
		as_clr(keyField);
}
function as_selectKeyPress(keyField)
{
	var sndr = window.event.srcElement;
	var pre = this.document.all[keyField].value;
	var key = window.event.keyCode;
	var character = String.fromCharCode(key);
	if(sndr.options.selectedIndex >= 0)
	{
		sndr.options[sndr.options.selectedIndex].selected = false;
	}


	try
	{
		var re = new RegExp("^" + pre + character, "i");
	}
	catch(Exception)
	{
		return;
	}
	// "i" -> ignoreCase
	for(var i = 0; i < sndr.options.length; i++)
	{
		if(re.test(sndr.options[i].text))
		{
			sndr.options[i].selected = true;
			document.all[keyField].value += character;
			window.event.returnValue = false;
			break;
		}
	}
}
function as_clr(keyField)
{
	document.all[keyField].value = "";
}

function copyTo(prefix, sourceName, targetName, ovrTarget, ovrEmpty)
{
	var fullSourceName = prefix + sourceName;
	var fullTargetName = prefix + targetName;
	if(!isEmpty(document.all[fullSourceName].value) || ovrEmpty)
	{
		if(isEmpty(document.all[fullTargetName].value) || ovrTarget)
			document.all[fullTargetName].value = document.all[fullSourceName].value;
	}
}
function autofocus(field, limit, next, evt)
{
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
	                                                ((evt.which) ? evt.which : 0));
	if(charCode > 31 && field.value.length == limit)
	{
		field.form.elements[next].focus();
	}
}

function numeralsOnly(evt)
{
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
	                                                ((evt.which) ? evt.which : 0));
	return !(charCode > 31 && (charCode < 48 || charCode > 57));

}
function updateDatebox(itemName)
{
	if(!isEmpty(document.all[itemName + '_y'].value))
		document.all[itemName].value = document.all[itemName + '_y'].value;
	if(!isEmpty(document.all[itemName + '_m'].value))
		document.all[itemName].value += '/' + document.all[itemName + '_m'].value;
	if(!isEmpty(document.all[itemName + '_d'].value))
		document.all[itemName].value += '/' + document.all[itemName + '_d'].value;
}


function validateEmail(email)
{
	var re = /^\w+([\.-_]?\w+)*@\w+([\.-_]?\w+)*(\.[a-z,A-Z]{2,3})+$/;
	return re.test(email);
}

function updatePhonebox(itemName)
{
	if(!isEmpty(document.all[itemName + '_c'].value))
		document.all[itemName].value = '+' + document.all[itemName + '_c'].value;
	if(!isEmpty(document.all[itemName + '_n'].value))
		document.all[itemName].value += '-' + document.all[itemName + '_n'].value;
}

function prevAutoFocus(field, limit, prev, evt)
{
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
	                                                ((evt.which) ? evt.which : 0));
	if(charCode == 8 && field.value.length == limit)
	{
		field.form.elements[prev].focus();
		setCaretToEnd(field.form.elements[prev]);
	}
}

function setCaretToEnd(control)
{
	if(control.createTextRange)
	{
		var range = control.createTextRange();
		range.collapse(false);
		range.select();
	}
	else if(control.setSelectionRange)
	{
		control.focus();
		var length = control.value.length;
		control.setSelectionRange(length, length);
	}
}

function setCaretToStart(control)
{
	if(control.createTextRange)
	{
		var range = control.createTextRange();
		range.collapse(true);
		range.select();
	}
	else if(control.setSelectionRange)
	{
		control.focus();
		control.setSelectionRange(0, 0);
	}
}

function getCaretPosition(oElement)
{
	var oSelection = oElement.ownerDocument.selection;
	var oRange = oSelection.createRange().duplicate();
	var defaultValue = oElement.value;
	var caret = -1;
	var key = "J~!@#$%^A&*()_+{}V|:>?<;)A";
	var lenSelected = oRange.text.length;

	oRange.text = key;
	caret = oElement.value.indexOf(key);

	oElement.value = defaultValue;
	var valLen = defaultValue.length;
	var rangeEnd = (-1 * (valLen - caret));

	// move the caret back
	oRange.moveStart("character", caret);
	oRange.moveEnd("character", rangeEnd + lenSelected);
	oRange.select();

	return( caret );
}

// calculator controller

