var SelectedAllStatus=false;
var theForm = document.forms['aspnetForm'];

function CheckAllCheckBoxes()
{	
   
    if (!theForm) {
        theForm = document.aspnetForm;  
        }
        
	for (var i=0; i<theForm.elements.length; i++)
		{
		var e = theForm.elements[i];			   
		if (e.type == 'checkbox')
		{			     
			if (SelectedAllStatus==false)
			{
			e.checked = true;
			}
			else if(SelectedAllStatus==true)
			{
			e.checked = false;
			}				 
		}
	}
	
	SelectedAllStatus = !SelectedAllStatus;	 
}

function ActivateSection(divid, imgid, hdnid)
{
	var element = document.getElementById(divid);
	var elementimg = document.getElementById(imgid);
	var elementhdn = document.getElementById(hdnid);
    var imgloc = elementimg.src.substring(0,elementimg.src.lastIndexOf('/'));

	if (element.style.display == 'none') 
	{
		element.style.display = '';
		elementimg.src =  imgloc + '/expandedBtn.gif';
		elementhdn.value = '';
	}
	else
	{
		element.style.display = 'none';
		elementimg.src = imgloc + '/collapsedBtn.gif';
		elementhdn.value = 'Display:none';
	}
}
function ChangeGroupTypeView(selectedValue)
{
	var county = window.document.getElementById('divCounty');
	var postal = window.document.getElementById('divPostal');
	
	if(selectedValue == 1)
	{
		county.style.display = 'block';
		postal.style.display = 'none';
	}
	else if (selectedValue == 2)
	{
		county.style.display = 'none';
		postal.style.display = 'block';
	}
}

/*****************************************************************************************************
 *
 * Function: The function is used to limit the input text's length.
 *           If user press key in textbox and the text's length is beyond the max length  we ignore it.
 * objButton: the default button in the page
 *
 ******************************************************************************************************/
//function LimitInput(length, text)
//{
//	if((text.length>=length && event.keyCode != 8 && event.keyCode != 46) || (event.ctrlKey == true && event.keyCode == 86 && text.length + window.clipboardData.getData('Text').length >=length)) 
//		window.event.returnValue=false;
//}

/******************************************************************************************
 *
 * Function: The function is used to select first item in the dropdownlist or listbox.
 * targetCtrl: The dropdownlist or listbox html control.
 *
 *****************************************************************************************/
function SelectItem(targetCtrl)
{
	if(targetCtrl.length > 0)
	{
		targetCtrl.options[0].selected = true;
	}
}
function LimitInput(length, text)
{
	if((text.length>=length && event.keyCode != 8 && event.keyCode != 46) || (event.ctrlKey == true && event.keyCode == 86 && text.length + window.clipboardData.getData('Text').length >=length)) 
		window.event.returnValue=false;
}
function RemoveOneItemJudgeDdl(sourceCtrl, targetCtrl, dropdownlist, viewCtrl, viewCtrl2, flagIndex)
{	
	var ctrlFrom = window.document.getElementById(sourceCtrl);
	var ctrlTo = window.document.getElementById(targetCtrl);
	var ddl = window.document.getElementById(dropdownlist);
	
	if(ctrlTo.selectedIndex != -1)
	{			
		var selectedValue = ctrlTo.options[ctrlTo.selectedIndex].value;
		var idArray = selectedValue.split(',');
		var stateID = idArray[flagIndex];		
	
		for(var i=0; i<ctrlTo.length; i++)
		{
			var flag = false;
			if(ctrlTo.options[i].selected)
			{			
				if(ddl.value != stateID)
				{
					flag = true;
				}
				for(var j=0; j<ctrlFrom.length; j++)	
				{
					if((ctrlFrom.options[j].value == ctrlTo.options[i].value) || (ddl.value != stateID))
						flag = true;
				}	
				if(!flag)	
				{		
					ctrlFrom.add(new Option(ctrlTo.options[i].text,ctrlTo.options[i].value));				
				}
				ctrlTo.options.remove(ctrlTo.selectedIndex);
				RemoveOneItemJudgeDdl(sourceCtrl, targetCtrl, dropdownlist, viewCtrl, viewCtrl2, flagIndex);
			}
		}			
	}			
	else
	{
		// sort the controls and set value to hidden control
		CompleteIt(ctrlFrom, ctrlTo, viewCtrl, viewCtrl2);
	}
}

/**********************************************************************************************
 *
 * Function: The function is used to add all item from listbox to another.
 *           If the item already exists in another control, we remove it, otherwise, we remove it
 *			 and add this item to another control.
 *           When user remove one item, and the item is not belong to the item in the dropdownlist,
 *           we ignore it too.
 * sourceCtrl: The listbox html control name.
 * targetCtrl: The listbox html control name.
 * viewCtrl: HtmlInputHidden control name which stores the value to server side.
 * viewCtrl2: HtmlInputHidden control name  which stores the value to server side.
 * dropdownlist: The dropdownlist control name, eg: state, group.
 * flagIndex: The selected item in dropdownlist's value. eg: state ID, group ID.
 *
 *********************************************************************************************/
function RemoveAllItemJudgeDdl(sourceCtrl, targetCtrl, dropdownlist, viewCtrl, viewCtrl2, flagIndex)
{
	var ctrlFrom = window.document.getElementById(sourceCtrl);
	var ctrlTo = window.document.getElementById(targetCtrl);
	var ddl = window.document.getElementById(dropdownlist);
	var selectedValue;
	var idArray;
	var stateID;
	
	while(ctrlTo.options.length > 0)
	{
		var flag = false;
		
		selectedValue = ctrlTo.options[0].value;
		idArray = selectedValue.split(',');
		stateID = idArray[flagIndex];
		
		if(ddl.value != stateID)
		{
			flag = true;
		}
	
			for(var j=0; j<ctrlFrom.length; j++)	
			{
				if(ctrlTo.options[0].value == ctrlFrom.options[j].value)
				{
					flag = true;
				}
			}
			
			if(!flag)
			{
				ctrlFrom.add(new Option(ctrlTo.options[0].text,ctrlTo.options[0].value));
			}	
			ctrlTo.options.remove(0);
			
	}
	
	CompleteIt(ctrlFrom, ctrlTo, viewCtrl, viewCtrl2);
}

/**********************************************************************************************
 *
 * Function: The function is used to add all item from listbox.
 * targetCtrl: The listbox html control name.
 * viewCtrl: HtmlInputHidden control name which stores the value to server side.
 * viewCtrl2: HtmlInputHidden control name  which stores the value to server side.
 *
 *********************************************************************************************/
function RemoveAllItem(targetCtrl, viewCtrl, viewCtrl2)
{
	var ctrlTo = window.document.getElementById(targetCtrl);
	while (ctrlTo.options.length>0)
	{
		ctrlTo.options.remove(0);
	}
	SetViewState(ctrlTo, viewCtrl);
	if(viewCtrl2 != '')
	{
		SetViewState(ctrlFrom, viewCtrl2);
	}
}		
function ListTransfer( sourceID, destinationID, selectedOnly, add, remove, allowDuplicates){
	var sourceList = document.getElementById(sourceID);
	var destinationList = document.getElementById(destinationID);

	var itemsForTransfer = new Array();

	var i;
	for(i = 0; i < sourceList.options.length; i++){
		var option = sourceList.options[i];
		if(option.value!="0" && (option.selected || !selectedOnly)){
			itemsForTransfer[itemsForTransfer.length] = new Option(option.text, option.value);
		}
	}
	
	if(remove){
		for(i = 0; i < sourceList.options.length; i++){
			var option = sourceList.options[i];
			if(option.value!="0"  && (option.selected || !selectedOnly)){
				sourceList.options[i] = null;
				i--;
			}
		}
	} 

	for(i = 0; i < itemsForTransfer.length; i++){
		var option = itemsForTransfer[i];
		if(option.value!="0" && add && ( allowDuplicates || !ListContains( destinationList, option))){
			destinationList.options[destinationList.options.length] = option;
		}
	}

	SortList(sourceList, destinationList);
	
	StoreListState(sourceList);
	StoreListState(destinationList);
	
	SelectItem(sourceList);
    SelectItem(destinationList);
}

function ListMove(listID, moveUp){
	var list = document.getElementById(listID);
	if(!moveUp){
		for(i = list.options.length-2; i >= 0; i--){
			if(list.options[i].selected && !list.options[i+1].selected ){
				var option = list.options[i];
				list.options[i] = new Option(list.options[i+1].text, list.options[i+1].value);
				list.options[i+1] = new Option(option.text, option.value);
				list.options[i+1].selected = true;
			}
		}
	} else {
		for(i = 1; i < list.options.length; i++){
			if(list.options[i].selected && !list.options[i-1].selected ){
				var option = list.options[i];
				list.options[i] = new Option(list.options[i-1].text, list.options[i-1].value);
				list.options[i-1] = new Option(option.text, option.value);
				list.options[i-1].selected = true;
			}
		}
	}
	StoreListState(list);
}

function ListContains(list, option){
	var i;
	for(i = 0; i < list.options.length; i++){
		if(list.options[i].value == option.value){
			return true;
		}
	}
}
function StoreListState(list){

	var i;
	var state = "";
	for(i = 0; i < list.options.length; i++){
		state += list.options[i].value + "^" + list.options[i].text + "|";
	}
	document.getElementById(list.id + "_State").value = state;	
}
function SortList(fbox, tbox){
    var arrFbox = new Array();
    var arrTbox = new Array();
    var arrLookup = new Array();
    var i;
    for (i = 0; i < tbox.options.length; i++)
    {
        arrLookup[tbox.options[i].text] = tbox.options[i].value;
        arrTbox[i] = tbox.options[i].text;
    }
    var fLength = 0;
    var tLength = arrTbox.length;
    for(i = 0; i < fbox.options.length; i++)
    {
        arrLookup[fbox.options[i].text] = fbox.options[i].value;
//        if (fbox.options[i].selected && fbox.options[i].value != "")
//        {
//            arrTbox[tLength] = fbox.options[i].text;
//            tLength++;
//        }
//        else
//        {
            arrFbox[fLength] = fbox.options[i].text;
            fLength++;
//        }
    }
    arrFbox.sort();
    arrTbox.sort();
    fbox.length = 0;
    tbox.length = 0;
    var c;
    for(c = 0; c < arrFbox.length; c++)
    {
        var no = new Option();
        no.value = arrLookup[arrFbox[c]];
        no.text = arrFbox[c];
        fbox[c] = no;
    }
    for(c = 0; c < arrTbox.length; c++)
    {
        var no = new Option();
        no.value = arrLookup[arrTbox[c]];
        no.text = arrTbox[c];
        tbox[c] = no;
    }
}

var dlgWindow; 

function ShowWindow(docLoc, winName, w, h, listboxId, action, showScrollbars)
{
    var lb = window.document.getElementById(listboxId);
	CloseDlgWindow();
	docLoc = AddRegionId(docLoc, listboxId);
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+showScrollbars+',resizable=yes';
	if(lb.selectedIndex != -1 || action == 'ADD'){
	    dlgWindow = window.open(docLoc,winName,winprops);
	    if (dlgWindow != null) dlgWindow.focus();
	}
}
function CloseDlgWindow() 
{
	if (dlgWindow != null)
	{
		dlgWindow.close();
	}
}
function AddRegionId(loc, lbId)
{
    var ctrl = window.document.getElementById(lbId);
    var selectedValue='';
	if(ctrl.selectedIndex != -1)
	{			
		selectedValue = ctrl.options[ctrl.selectedIndex].value;
    }
    
    var newDocLoc = loc + '&id=' + selectedValue;
    return newDocLoc;
}

function textCounter(field, countfield, maxlimit, message) 
{  
    var messageField = window.document.getElementById(field);
    var counterField = window.document.getElementById(countfield);

//    if (messageField.value.length > maxlimit)
//    {
//        //messageField.value = messageField.value.substring(0, maxlimit);
//        counterField.value = messageField.value.length;
//        alert(message);
//    }
//    else

      counterField.value = messageField.value.length;    
}

function ValidateCheckBoxes()
{	
    var isChecked = false;
    
    if (!theForm) {
        theForm = document.aspnetForm;  
        }
        
	for (var i=0; i<theForm.elements.length; i++)
    {
	
		var e = theForm.elements[i];

		if (e.type == 'checkbox')
		{			     
			if (e.checked)
			{
			    isChecked = true;
			}				 
		}
	}
	return isChecked;
}

//Callback method for retrieving counties for the specified state id value  
function GetCountiesForState(dropdownId, stateId) {
    SetLoadingText(dropdownId);
    PageMethods.GetCountiesForState(dropdownId, stateId, OnSucceeded, OnFailed);
}

//Callback method for retrieving states/provinces for the specified country id value  
function GetStatesForCountry(dropdownId, countryId) 
{
    SetLoadingText(dropdownId);
    PageMethods.GetStatesForCountry(dropdownId, countryId, OnSucceeded, OnFailed);
} 

function SetLoadingText(dropdownId)
{
    var childOptions = document.forms[0].elements[dropdownId];
    
    if (!childOptions){
            return;
    }
    
    childOptions.disabled = true;
    childOptions.length = 0;
    var option = document.createElement("OPTION");
    option.value = "-1";
    option.innerHTML = "[Loading ...]";
    childOptions.appendChild(option);
}

// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "GetStatesForCountry" || methodName == "GetCountiesForState")
    {
        if (!result){
            return;
        }  

        var results = result.split('[^]');
        
        if(!results.length==2){
            return;
        }
        
        var controlId = results[0];       
        var childOptions = document.forms[0].elements[controlId];

        if (!childOptions){
            return;
        }
        
        childOptions.length = 0;
         
        var rows = results[1].split('|'); 
        for (var i = 0; i < rows.length; ++i){
            var values = rows[i].split('^');
            var option = document.createElement("OPTION");
            option.value = values[0];
            option.innerHTML = values[1];     
            childOptions.appendChild(option);
        }
        
        if(childOptions.length>1){
            childOptions.disabled=false;
        }
        else{
          childOptions.disabled = true;
        }
    }
}

// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) 
{
    if (methodName == "GetStatesForCountry")
    {
        alert("There was a problem loading the State/Province selections.");
    }
    else if (methodName == "GetCountiesForState") {
        alert("There was a problem loading the County selections.");
    }
}

function OpenIconWindow(docLoc, winName)
{
    OpenWindow(docLoc,winName,'750','350','yes','yes');
}

function OpenWindow(docLoc, winName, w, h, showScrollbars, resizable)
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+showScrollbars+',resizable='+resizable+'';
    dlgWindow = window.open(docLoc,winName,winprops);
    if (dlgWindow != null) dlgWindow.focus();
}

function selectAllListItems(listID) {
    var oList = document.getElementById(listID);
    for (var i = 0; i < oList.options.length; i++) {
        oList.options[i].selected = true;
    }
}
function clearAllListItems(listID) {
    var oList = document.getElementById(listID);
    for (var i = 0; i < oList.options.length; i++) {
        oList.options[i].selected = false;
    }
}