// Cancel Event
function fncPreventAction(e)
{
	if (window.event)
	{//IE
		window.event.returnValue = null;
	}
	else //Firefox
	{
		e.preventDefault();
	}
}

function getObject(objectId) {
	if (document.getElementById && document.getElementById(objectId)) 
	{
		return document.getElementById(objectId);
	} 
	else if (document.all && document.all(objectId)) 
	{
		return document.all(objectId);
	} 
	else 
	{
		return false;
	}
}	

function SetEnabled(objectId, isEnabled)
{
    var obj = getObject(objectId);
    if(obj == null) return;
    if(isEnabled == true)
        obj.disabled = "disabled";
    else
        obj.disabled = "";    
}

function fncValidDate(pDateValue)
{    
	if (pDateValue == "") return false;
	
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = pDateValue.match(datePat); // is the format ok?
	if (matchArray == null) {
		return false;
	}

	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[5];

	if (month < 1 || month > 12) { // check month range
		return false;
	}

	if (day < 1 || day > 31) {
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==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)) {
			return false;
		}
	}
	return true; // date is valid		
}

//=============== Prototype ===========================
String.prototype.replaceAll = function( 
    strTarget, // The substring you want to replace
    strSubString // The string you want to replace in.
    ){
    var strText = this;
    var intIndexOfMatch = strText.indexOf( strTarget );
     

    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1){
    // Relace out the current instance.
    strText = strText.replace( strTarget, strSubString )
     

    // Get the index of any next matching substring.
    intIndexOfMatch = strText.indexOf( strTarget );
    }
     

    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return( strText );
}

String.prototype.checkOwnerFrame = function()
{
    if(window.parent.frames.length <= 0) window.location = this;
}

String.prototype.checkOwnerFrameDialog = function()
{
    if(window.parent.parent.frames.length <= 0) window.location = this;
}

String.prototype.checkOwnerDialog = function()
{
    
    if(typeof(window.dialogArguments) == 'undefined' || window.dialogArguments == 'undefined') 
    {
        window.location = this;        
    }
}

//=============== End Prototype ===========================

function dateToStringYYYYMMDD(dateStr)
{
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		return "";
	}
	month = matchArray[1]; // p@rse date into variables
	day = matchArray[3];
	year = matchArray[5];
	
	var strReturn = "" + year;
	
	if (month <10) {
		strReturn += "0" + month;
	}else {
		strReturn += month;
	}
	if (day <10) {
		strReturn += "0" + day;
	}else {
		strReturn += day;
	}
	return 	strReturn;
}


// Email
function IsValidEmail(Str)
{
	if (! Str || Str == 'undefined')
	{
		return false;
	}
	if (Str.length == 0)
	{
		return false;
	}
	var szFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9_\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
	
	if (szFilter.test(Str)) 
	{
		return true;
	}
	return false;
}

function fncRemoveAllOptions(listObject)
{	
	if (listObject)
	{
		if (listObject.options)
		{
			for (var iInd2=0; iInd2 < listObject.options.length; iInd2++)
			{									
				listObject.remove(iInd2);			
				iInd2 -=1;
			}
		}
	}
	return;	
}

function fncAddOptions(listObject, text, value)
{	
	if (listObject)
	{
		var oOption = document.createElement("OPTION");
		oOption.text = text;
		oOption.value = value;							
		listObject.add(oOption);
		listObject.options[listObject.options.length-1].selected = true;		
	}
	return;
}

function fncRemoveOptions(listObject, index)
{		
	if (listObject && listObject.options)
	{
	    if (index<listObject.options.length)		
		{									
			listObject.remove(index);			
		}
	}
	return;
}
//======================================== Menu ============================================
	var last_expanded = ''; 
	var curActivedMenuItem = null;

    function showHide(id) 
    { 
		
        var obj = document.getElementById(id); 
        var status = obj.className; 
       
        if (status == 'hide') 
        { 
            if (last_expanded != '') 
            { 
                var last_obj = document.getElementById(last_expanded); 
                last_obj.className = 'hide'; 
            } 
            obj.className = 'show'; 

            last_expanded = id; 
        } 
        else 
        { 
            obj.className = 'hide'; 
        } 
    }
    
   
    

    function updateTime()
    {
        var date = document.getElementById('date');
        var label = document.getElementById('currentTime');
        var dateValue = new Date();
       
        if (date)
        {
            date.innerHTML = dateValue.getDate() + "/"+ (dateValue.getMonth() + 1) + "/" + dateValue.getFullYear();
        }
       
        if (label) 
        {
            var time = (new Date()).toLocaleTimeString();
            time = time.match(/^(\s*\d{1,2}\s*\:\s*\d{1,2}\s*\:\s*\d{1,2}\s*[A-Za-z]{2}).*$/)[1];
            label.innerHTML = time;
        }
    }   
             
    updateTime();
    window.setInterval(updateTime, 1000);
    
    function GoToPage(pagePath)
    {
        window.navigate(pagePath);
        return false;
    }

   // var prm = Sys.WebForms.PageRequestManager.getInstance();
   // prm.add_beginRequest(BeginRequest);
    function BeginRequest(sender, args) 
    {
        var updateProgress = $get("ctl00_updateProgress");  
        if (updateProgress)
        {
            updateProgress.style.position = "absolute";
            updateProgress.style.top = window.document.body.offsetHeight / 2;
            updateProgress.style.left = screen.width / 2;
        }
    }
    function changeImageSource(ojb,imgSrc)
    {
		ojb.src = "../Images/"+ imgSrc;
    }
    //========= Show/Hide Div =======================
    function fncVisibleDiv(DivId, ImgId, CollapseImagePath, ExpandImagePath)
	{
		var DivObj = getObject(DivId);
		var ImgObj = getObject(ImgId);
		
		if(DivObj.style.display == 'none')
		{
			DivObj.style.display = "block";
			ImgObj.src  = ExpandImagePath;
		}
		else
		{
			DivObj.style.display = "none";
			ImgObj.src  = CollapseImagePath;
		}
	}
//================================Validate Control ==================================

function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}


function isEmpty(ObjID)
{
	var Obj = getObject(ObjID);
	if(Obj == false)
	{ 	return true;
	}
	else 
	{
		if(Obj.value ==null || trim(Obj.value)=="")
		{
			 return true;
		}
		else 
		{	
			return false;
		}
	}
	
}
/*function isEmptyText(ObjID, ErrMsgObjID)
{
	var Msgobj = getObject(ErrMsgObjID);
	if(isEmpty(ObjID))
	{
		Msgobj.innerHTML = "*";
		return true; 
	}else 
	{
		Msgobj.innerHTML = "";
		return false;
	}
}
function InValidEmail(ObjID,ErrMsgObjID)
{
	var Msgobj = getObject(ErrMsgObjID);
	if(isEmpty(ObjID))
	{
		Msgobj.innerHTML = "*";
		return true;
	}else {
		if (!IsValidEmail(getObject(ObjID).value)){
			Msgobj.innerHTML = "*";
			return true;
		}
		else {
			Msgobj.innerHTML = "";
			return false;
		}
	}
}

function isUnSelected(ObjID,ErrMsgObjID,initValue)
{
	var obj = getObject(ObjID);
	var Msgobj = getObject(ErrMsgObjID);
	if(obj.selectedIndex == initValue)
	{
		Msgobj.innerHTML = "*";
		return true;
	}
	else{
		Msgobj.innerHTML = "";
		return false;
	}
}*/

function DeleteConfirm(e,message)
{
	if(!confirm(message))
	{
		fncPreventAction(e);
	}
}
//============================================ Check box event ===============================================
function checkAll(id)
{
	var cbCheckAll = document.getElementById(id);
	
	for(var i = 0; i < clientIdCollection.length ; i++)
	{
		var cbClientId = document.getElementById(clientIdCollection[i]);
		if(cbCheckAll.checked)
		{
			if(!cbClientId.checked)
				cbClientId.checked = true;
		}
		else
		{
			if(cbClientId.checked)
				cbClientId.checked = false;
		}
	}
	
}
function confirmDelete()
{
	return confirm("Are you sure you want to delete this information?");
}

function validateDate(fld) 
{
	var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
//	var errorMessage = 'Please enter valid date as mm/dd/yyyy.';
	if ((fld.match(RegExPattern))) 
	{
		return true; 
	}
	else 
	{
		if(fld == '')
			return true;
		return false;
	}
}
function validateDateAll(dateFrom,dateTo)
{
	var fromDate = document.getElementById(dateFrom);
	var toDate = document.getElementById(dateTo);
	
	if(!validateDate(fromDate))
		return false;
	if(!validateDate(toDate))
		return false;
	
	var fromDateValue = Date.parse(fromDate.value);
	var toDateValue = Date.parse(toDate.value);
	
	if((fromDateValue - toDateValue) > 0)
	{
		alert('Invalid date. From Date value is more lagrer than To Date value');
		return false;
	}
	
	return true;
}
function validateSelected(arrSelected,arrErrorMessage)
{
	var arrControl = arrSelected.split(',');
	var arrMessage = arrErrorMessage.split(',');
	for(var i= 0 ; i < arrControl.length ; i++)
	{
		var objSelect = document.getElementById(arrControl[i]);
		
		if(objSelect.selectedIndex == 0)
		{
			//alert('Selected value can not be null or zero');
			if(i < arrMessage.length)
			{
				alert(arrMessage[i]);
			}
			return false;
		}	
	}
}
function validBeforeRemove()
{
	var isCheck = false;
	for(var i = 0; i < clientIdCollection.length ; i++)
	{
		var cbClientId = document.getElementById(clientIdCollection[i]);
		if(cbClientId.checked)
		{
			isCheck = true;
			break;
		}		
	}
	if(!isCheck)
	{
		alert("Please choose any items before click remove button");
		return false;
	}
	
	if(!confirmDelete())
		return false;
	
}
function validBeforeChangeStatus()
{
	var isCheck = false;
	for(var i = 0; i < clientIdCollection.length ; i++)
	{
		var cbClientId = document.getElementById(clientIdCollection[i]);
		if(cbClientId.checked)
		{
			isCheck = true;
			break;
		}		
	}
	if(!isCheck)
	{
		alert("Please choose any items before change status");
		return false;
	}
}

/*
===============================================================================================================
*/

function buttonMouseOut(imgsrc,Id)
{
	var button = document.getElementById(Id);
	
	button.src = imgsrc;
}

function buttonMouseOver(imgsrc,Id)
{
	var button = document.getElementById(Id);
	
	button.src = imgsrc;
}

/* **** Check Validate Phone Number ***** */

	// Declaring required variables
	var digits = "0123456789";
	// non-digit characters which are allowed in phone numbers
	var phoneNumberDelimiters = "()- ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	var minDigitsInIPhoneNumber = 10;

	function isInteger(s)
	{   var i;
		for (i = 0; i < s.length; i++)
		{   
			// Check that current character is number.
			var c = s.charAt(i);
			if (((c < "0") || (c > "9"))) return false;
		}
		// All characters are numbers.
		return true;
	}

	function stripCharsInBag(s, bag)
	{   var i;
		var returnString = "";
		// Search through string's characters one by one.
		// If character is not in bag, append to returnString.
		for (i = 0; i < s.length; i++)
		{   
			// Check that current character isn't whitespace.
			var c = s.charAt(i);
			if (bag.indexOf(c) == -1) returnString += c;
		}
		return returnString;
	}
	function checkInternationalPhone(strPhone)
	{
		s = stripCharsInBag(strPhone,validWorldPhoneChars);
		return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
	}
/* **** Check Validate Phone Number ***** */


/* ******** Marquee *************** */

var timer;           
var amount = 3;      
var stoped = false;

function initMarquee(marId){
	if(document.getElementById(marId)){
		if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 3)){		
		   document.getElementById(marId).scrollAmount=document.getElementById(marId).clientWidth;
		 }
		 else{
		   document.getElementById(marId).scrollAmount=amount;
		 }		 
	}
}

function startMarquee(marId){
    var marObj = document.getElementById(marId);
    marObj.scrollAmount = amount;
    marObj.start(); 
    clearTimeout(timer);  
    stoped = true;
    marObj.onscroll=function(){scrolling(this);};
}
function scrollMarquee(marObj, waitTime){	
	if(!stoped && marObj.scrollLeft <= marObj.clientWidth){
	   marObj.stop();	     
	   timer = setTimeout("startMarquee('"+marObj.id+"')", waitTime);
	}
}
function scrolling(marObj){	 
	marObj.stop();
	marObj.scrollAmount = amount;
	marObj.start();
 
}
//================================================================================

function CheckAll(IsCheck , ArrayObj)
{
    if(ArrayObj == null) return;
    for(var i = 0; i < ArrayObj.length ; i++)
    {
	    var cbClientId = document.getElementById(ArrayObj[i]);
	    cbClientId.checked = IsCheck;
    }
    fncPreventAction(event);
    return;
}

function CheckClick(CheckObj, ArrayObj)
{
    if(ArrayObj == null) return;
    for(var i = 0; i < ArrayObj.length ; i++)
    {    
	    var cbClientId = document.getElementById(ArrayObj[i]);
	  
	    if(cbClientId != undefined && CheckObj.id != cbClientId.id)
	        cbClientId.checked = false;
	    //else alert(cbClientId.checked);
	    
    }
   // fncPreventAction(event);
    return;
}

function IsChecked(ArrayObj)
{
    if(ArrayObj == null) return;
    for(var i = 0; i < ArrayObj.length ; i++)
    {
	    var cbClientId = document.getElementById(ArrayObj[i]);
	    if(cbClientId.checked == true) 
	        return true;   
    }    
    return false;
}


function OpenDialog(URLPath, width, height, features) 
{
    if(typeof(features) == 'undefined' || features == '') 
        features = 'status=no;help=no;resizable=no;close=no;scroll=yes;toolbar=0;location=0;personalbar=no;menubar=0;unadorned=yes';
    return OpenDialogTarget(URLPath, 'tmp', width, height,features); 
}

function OpenDialogTarget(URLPath, pTarget, width, height, pfeatures) 
{    
    try{
        var w = width;
        var h = height;
        var l = (screen.width - width)/2;
        var t = (screen.height - height)/2;
        var OffHeightForFireFox = 35;
        var sFeatures = "";
        if(width == 'screen.width')
        {
            w = screen.width;
            l = w /2;
        }
        if(height == 'screen.height')
        {
            h = screen.height;
            t = h/2;
        }
        
        if(navigator.userAgent.indexOf('Firefox/3') >=0 || navigator.userAgent.indexOf('MSIE 8.0') >=0 || navigator.userAgent.indexOf('MSIE 7.0') >=0)
        {
            h = h -  OffHeightForFireFox;
            t = t - OffHeightForFireFox;
        }
        
        if(window.showModalDialog)
        {           
            sFeatures = 'dialogWidth=' + w + 'px;dialogHeight=' + h + 'px;dialogLeft:' + l + 'px;dialogTop:' + t + ';' + pfeatures ;
            return window.showModalDialog(URLPath , pTarget, sFeatures);
        }
        else
        {     
            sFeatures = "Width=" + w + "px, Height=" + h + "px,center=yes,location=no,toolbar=no,status=no,help=no,resizable=no,modaless=false,personalbar=no,dialog=yes,menubar=no";
            
            
            window.open(URLPath , '_blank', sFeatures);
            //alert('Only support Internet explorer');
        }
    }
    catch(err)
    {
    }
}

function isKeyNumber(e)
{
    if(e.keyCode < 46 || e.keyCode > 57 || e.keyCode == 47) 
    { 
        return false;
    }
    return true;
}

function TabEnter(e)
{        
    try
    {
        if(window.event)
        {
            if(event.keyCode==13)    
            {
                event.keyCode=9; 
                return event.keyCode ;
            }
        }
        else    
        {                   
            if(e.which == 13)    
            {
                e.which = 9; 
                e.preventDefault();
            }
        }
    }catch(ex){}
}

function IgnoreCharacter()
{   
    if (window.event && event.keyCode==186) 
    {        
        window.event.returnValue = null;
        event.keyCode = null;
    }
}

function setHourglass()
{
    document.body.style.cursor = 'wait';
}

function setNormalCursor()
{
    document.body.style.cursor = 'default';
}
/*
    if (self.innerHeight) // all except Explorer
    {	
	    alert('self: ' + self.innerHeight + 'Win:');
    }
    else if (document.documentElement && document.documentElement.clientHeight)
	    // Explorer 6 Strict Mode
    {	
	    alert('IE: ' + document.documentElement.clientHeight);
    	
    }
    else if (document.body) // other Explorers
    {
    	
	    alert('other:' + document.body.clientHeight);
    }

*/

function CheckPageAuthenicate(Page)
{
    Page.checkOwnerFrame();
}
function FocusFirst() {      
      var bFound = false;
      //for each form
      for (f=0; f < document.forms.length; f++) {
            //for each form element
            for (i=0; i < document.forms[f].length; i++) {
                  el = document.forms[f][i]
                  if (el.disabled != true) {
                        if (el.type != undefined) {
                              switch (el.type.toLowerCase()) {
                                    case "text" : el.focus(); bFound = true; break;
                                    case "textarea" : el.focus(); bFound = true; break;
                                    case "checkbox" : el.focus(); bFound = true; break;
                                    case "radio" : el.focus(); bFound = true; break;
                                    case "file" : el.focus(); bFound = true; break;
                                    case "password" : el.focus(); bFound = true; break;
                                    case "select-one" : el.focus(); bFound = true; break;
                                    case "select-multiple" : el.focus(); bFound = true; break;
                              } // switch el.type
                        } //if (el.type != undefined) 
                  } //if (el.disabled != true)
                  if (bFound == true) break;
            } //for each form element
            if (bFound == true) break;
      } //for each form
}

