//some new helper methods for the string class 
String.prototype.trim = function() { return this.replace(/^\s+/, '').replace(/\s+$/,''); };
String.prototype.ltrim = function() { return this.replace(/^\s+/, ''); };
String.prototype.rtrim = function() { return this.replace(/\s+$/,''); };
Number.prototype.toMoney = function () { var v = this.toFixed(2);var t = v.substring(0,v.indexOf('.'));if(t.length > 3){var c = 0;var n = '';var a = t.split('');for(i=(a.length-1);i>-1;i--){if(c == 3){n = ',' + n;c = 0;}n = a[i] + '' + n;c++;}t = n;}v = '$' + t + v.substring(v.indexOf('.'));return v;}


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function newWindow(win) {
	window.open(win);
}

function focusWindow(win) {
	var thisWin = window.open(win);
	thisWin.focus();
}

function helpPopup(page) {
	newPopupWindow("HelpCenter/WebSolutionOverviewWeb.htm#" + page,'Help',650,650,true)
}

function newsletterPopup() {
	newPopupWindow("/Newsletter/Newsletter.htm",'Help',650,900,true);
}

function newsletterTeaserPopup() {
	newPopupWindow("/Newsletter/Teaser/Newsletter.htm",'Help',650,900,true);
}

function ShowFAQ(faqid) {
	newPopupWindow("KnowledgebasePopup.aspx?FaqID=" + faqid,'Help',500,500,true);
	returnValue = false;
}

function newPopupWindow(url,name,height,width,scrollbars){
	return newPopupWindowResizable(url,name,height,width,scrollbars,true);
}

function newPopupWindowNoReturn(url,name,height,width){
	newPopupWindowResizable(url,name,height,width,true,true)
}

function newPopupWindowFullscreen(url,name) {

		var w=screen.availWidth - 20;
		var h=screen.availHeight - 40;
		var l=5;
		var t=5;

		settings='width='+w+',height='+h+',top='+t+',left='+l+',scrollbars=yes,location=no,menubar=no,resizable=yes';
		newPopupWindowResizable(url,name,h,w,false,false);
	}

function newPopupWindowResizable(url,name,height,width,scrollbars,resizable){
	// set initial window options
	var windowOptions = 'menubar=false,locationbar=false,personalbar=false,statusbar=false,toolbar=false';
	
	// grab the current width and height values
	// sets the screen height and width -30 if no values are passed
	
	if (height != '')
		var h = height
	else
		var h=(window.screen.height-30);
		
	if (width != '') 
		var w = width
	else
		var w=(window.screen.width-30);
	
	// add the height/width values to the window options
	windowOptions += ',height=' + h + ',width=' + w;
	
	// find the center of the screen
	var top, left;
	
	top=Math.floor((window.screen.height/2)-(h/2));
	left=Math.floor((window.screen.width/2)-(w/2));
	
	// add the top/left values to the window options
	windowOptions += ',top=' + top + ',left=' + left;
	
	// add scrollbars
	if(scrollbars){windowOptions += ',scrollbars=yes';}
	
	// is resizable
	if(resizable){windowOptions += ',resizable=yes';}
	
	//window.location = windowOptions;
	
	// open the new window
	return window.open(url,name,windowOptions);
}

function addNote(nOrderNo,sDebtorName,sSubject,nBillingCode) {
	/*
	if (bReminder == undefined)
		bReminder = 'false';

	MM_openBrWindow('AddNote.aspx?bOrder='+bOrder+'&bReminder='+bReminder,'Note','scrollbars=yes,width=500,height=500');
	*/
	
	//Check to see if any of the parameters were not passed:
	try{
		if(nOrderNo == undefined){nOrderNo='';}
		if(sDebtorName == undefined){sDebtorName='';}
		if(sSubject == undefined){sSubject='';}
		if(nBillingCode == undefined){nBillingCode='';}
		
		newPopupWindow('AddNote.aspx?OrderNo='+nOrderNo+'&DebtorName='+sDebtorName+'&Subject='+sSubject+'&BillingCode='+nBillingCode,'AddNote',370,500,false)
		returnValue = false;
	}
	catch(e){
		//do nothing
	}
}

function showClipboard() {
	try{
		newPopupWindow('Clipboard.aspx','Clipboard',600,750,true)
		returnValue = false;
	}
	catch(e){
		//do nothing
	}
}

function submitBug() {
	try{
		newPopupWindow('ContactUsWindow.aspx?CreateBug=True','SubmitBug',560,500,true)
		returnValue = false;
	}
	catch(e){
		//do nothing
	}
}

function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function showSpan(bool,span) {
	var thisDiv = document.getElementById("Span"+span);
	if (bool) {
		thisDiv.style.display = "inline";
		document.getElementById("inp"+span).focus();
	}
	else
		thisDiv.style.display = "none";					
}


function BuildStateList(frm, DefaultState, stateList) {

	
	var optStates = stateList.options;
	// empty states combo box
	
	for (var i = optStates.length - 1; i > 0; i--) {
		optStates[i] = null;
	}


// if no default state is specified in the cookie, then
// add the <Select State> option

	if (DefaultState == '') {
		optStates[0] = new Option(' Select State',-2)
		optStates[0].selected = true;
	}
	if (optStates.length <= 1) {
		for (var j = 0; j < arStates.length; j++) {
		//add 1 to the index value since the <Select State> option is at index 0
			optStates[j+1] = new Option(arStates[j].text, arStates[j].id);
			if (arStates[j].text == DefaultState) {


				Form1.State.selectedIndex = j+1;

			} 
		}
	}
	return true;
}

function BuildJurList(frm, DefaultJur, jurisBox, stateBox) {

	var options = jurisBox.options;

	// empty jurisdiction combo box
	for (var i = options.length - 1; i > 0; i--) {
		options[i] = null;
	}

	if (stateBox.selectedIndex == 0) {
		options[0] = new Option(' Select Jurisdiction ',-2);
	}
	else {

		// fill jurisdiction combo box
	    // subtract 1 since the <Select State> option is at index 0
		var curAr = arJur[stateBox.selectedIndex-1];

		if (curAr != null) {
			for (var j = 0; j < curAr.length; j++) {
				options[j] = new Option(curAr[j].text, curAr[j].id);
				if (curAr[j].text == DefaultJur) {
				
					options[j].selected = true;

				}
			}
		}
	}
	return true;
}

function makeOption(text, id) {
  this.text = text;
  this.id = id;

}

function view(description){

	document.getElementById("PageName").value = "DocumentCenter";
	document.getElementById("View").value = description;

}

function showDiv(that) {
	var thatID = that.id + 'div';
	if (that.checked)
		thatID.style.display = 'block'
	else
		thatID.style.display = 'none';
}

function displayDiv(bool,divID) {

	var div = document.getElementById(divID);
	if (div != null) {
		if (bool)
			div.style.display=''
		else
			div.style.display='none';
		}
	}
function showOptions(bool,div) {

	var thatID = document.getElementById(div + 'Options');

	if (bool)
		thatID.style.display = 'block'
	else
		thatID.style.display = 'none';
}
function changeColor(item,color,over){
	item.style.backgroundColor = color;
	/*
	if(over){
		item.children[0].children[0].className = 'MenuText';
	}else{
		item.children[0].children[0].className = 'MenuText MenuTextOut';
	}
	*/
}

function boxHide(id) {
	var thisDiv = document.getElementById(id);
	var thisImg = document.getElementById('Img'+id);
	if (thisDiv.style.display == 'none') {
		thisDiv.style.display='block';
		thisImg.src='../images/minus_white.gif';
		thisImg.alt='Collapse';
	} else {
		thisDiv.style.display='none';
		thisImg.src='../images/plus_white.gif';
		thisImg.alt='Expand';
	}
}

var clickable = true;
var isClicked = false;

function changeStatus(spanID,otherID) {
	if (isClicked == false) {
		var thisSpan = Common.getElement(spanID);
		if(thisSpan != null) {
			Common.coolButton.buttonText[spanID] = thisSpan.innerHTML;
			thisSpan.innerHTML = 'Processing...';
			thisSpan.style.color = 'gray';
			thisSpan.style.cursor='wait';
			isClicked = true;
		}
		
		var thatSpan = Common.getElement(otherID);
		if (thatSpan != null) {
			Common.coolButton.buttonText[otherID] = thisSpan.innerHTML;
			thatSpan.innerHTML = 'Processing...';
			thatSpan.style.color='gray';
			thatSpan.style.cursor = 'wait';
		}
	} else {
		clickable=false;
	}
}

function resetStatus(id,text) {
	var item = Common.getElement(id);
	if(item != null){
		if(Common.coolButton.buttonText[id] != null){
			item.innerHTML = Common.coolButton.buttonText[id];
		} else {
			item.innerHTML = text;
		}
		
		item.style.color = '#000000';
		item.style.cursor = '';
		clickable = true;
		isClicked = false;
	}
}

function matchFieldSelect (field, select) {
  var property = 'text';
  var found = false;

  for (var i = 0; i < select.options.length; i++)
    if ((found = select.options[i][property].indexOf(field) == 0))
      break;
  if (found)
    select.selectedIndex = i;
  else
    select.selectedIndex = -1;
}

function clickButton(theButton){
	document.getElementById(theButton).click();
	return false;
}

/*
function showHide(bool,id) {
var row = document.getElementById(id);

	if (bool) 
		row.style.display = '';
	else
		row.style.display = 'none';
}
*/

function showHide(that) {
	if (!(that == null)) {
	var bool = that.checked;
	for (var i=0; i<valuelist.length;i++) {
		if (valuelist[i][0] == that.id)
			var row = document.getElementById(valuelist[i][1]);
	}
	if (bool) 
		row.style.display = '';
	else
		row.style.display = 'none';
		
	}
}
/*
function expandAll(bool,theForm) {

    for (i=0,n=theForm.elements.length;i<n;i++)
        if (theForm.elements[i].name.indexOf('Selected') !=-1) {
            theForm.elements[i].checked = bool;
            theForm.elements[i].click();
            }
}
*/
function expandAll(bool) {
var formArray = document.forms[0].getElementsByTagName('INPUT');
  for (var i=0; i<formArray.length; i++) {
      if (formArray[i].type == 'checkbox')
		formArray[i].checked = bool;
  }
  updateChecked();
}

function updateChecked(){
//alert ("updated");
	var curItem;
	for (var i=0; i<valuelist.length;i++) {
		curItem = document.getElementById(valuelist[i][0]);
		showHide(curItem);
	}
	
}
function updateVisible(){
//alert ("updated");
	var curItem;
	for (var i=0; i<valuelist.length;i++) {
		curItem = document.getElementById(valuelist[i][0]);
		if ((!(curItem == null)) && (curItem.checked))
			showHide(curItem);
	}
	
}

function expandGroup(id,bool) {
	for (var i=0; i<valuelist.length;i++) {
		if (valuelist[i][0] == id) 
			var ids = valuelist[i][1];
		}
	
	var idList = ids.split(",");
	for (var i=0;i<idList.length;i++) {
		document.getElementById(idList[i]).checked = bool;
		}
	updateVisible();
	
}

//Some methods for triming off white space from the left, right, or both
function Trim(value){
	value = RTrim(value);
	value = LTrim(value);
	return value;
}

function LTrim(value){
	while(value.indexOf(' ') == 0 && value.length > 0){value = value.substr(1);}
	return value;
}

function RTrim(value){
	while(value.lastIndexOf(' ') == (value.length-1) && value.length > 0){value = value.slice(0,-1);}
	return value;
}

function ShowPopup(title, url, width, height ){
	var settings;
	var l=50;
	var t=100;
	
	settings='width='+width+',height='+height+',top='+t+',left='+l+',scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
	
	clipWindow = window.open(url, title,settings);
	clipWindow.focus();
}

// THis method will validate a field with an orgID validator
// The orgID validator must be written to the page with the variable name "orgIDRegEx"
//		and the warning message must be written to the variable name "orgIDMsg"
var orgIDRegEx;

function validateOrg(fldID) {

	if (orgIDRegEx == null) {
		return true;
	} else {
		var fld = document.getElementById(fldID);
		if(fld==null){ return true; }
		
		var accepted = document.getElementById("ValidatorAccepted");
		var txt = fld.value;
			
		if (txt.length>0) {
			var re = orgIDRegEx
			if (re.test(txt) || (accepted != null && accepted.value=='True')) {
				return true;
			} else {
				if (confirm("This state requires Organizational IDs in this format:\n" + orgIDMsg + "\nYour Organizational ID does not match this format.\nDo you wish to continue?"))
				{
					accepted.value="True";
					return true;
				} else {
					fld.focus();
					return false;
				}
			}
		}
	}
}

// This method will validate an array of OrgIDs.  The array must be named orgIDflds
function validateOrgIDs() {
	
	if (orgIDflds != null) {
		var fldID;
		for (i=0;i<orgIDflds.length;i++) {
			fldID = orgIDflds[i];
			if (!validateOrg(fldID)){ return false; }
		}
	}
	return true;
}

// make global variables 
var _highlightSuggestionIndex = -2; 
var _highlightDiv = null;
var _selectedIndex = -1; 
var _divObject = null;

function SearchWord(pressevent,keyValue)
{

    var charCode = (pressevent.which)? pressevent.which : (event.keyCode);
    // alert(charCode);
    // Send to the Server Side Method to get the string
    if(charCode >=48 && charCode <=57 || 
       charCode >= 96 && charCode <=105) {
        QuickUserChanger.Search(keyValue,SearchWord_CallBack);
    }

    // if the backspace key (8) is pressed and 48 is for the delete button
    else if(charCode == 8 || charCode == 48)
    {
        // Reset the count
        _highlightSuggestionIndex = -2;
        QuickUserChanger.Search(keyValue,SearchWord_CallBack);
    }

    // when the down arrow key is pressed
    else if(charCode == 40)
    {
        if((_highlightSuggestionIndex+2) <= 
            document.getElementById("DisplayAccounts").childNodes.length)
        {
            _highlightSuggestionIndex = _highlightSuggestionIndex + 2;
        }

        Highlight(_highlightSuggestionIndex);
    }

    // When the up arrow key is pressed
    else if(charCode == 38)
    {
        if((_highlightSuggestionIndex-2) >= 0) {
            _highlightSuggestionIndex = _highlightSuggestionIndex -2;
        }
        Highlight(_highlightSuggestionIndex);
    }
    
}

function SearchWord_CallBack(response)
{

    var word = response.value;
    if(response != null)
    {
        document.getElementById("DisplayAccounts").style.visibility = "visible";
        document.getElementById("DisplayAccounts").innerHTML = 
                    word.substring(0,word.length - 4);
    }
}

// High lights the selected row of the Div element 
function Highlight(index) 
{
    if(index < 0) return;        
    
    completeList = document.getElementById("DisplayAccounts"); 
    
    if(index > completeList.childNodes.length) return;
    
    _selectedIndex = index; 
        
    if(completeList) 
    {       
        var divValue = document.getElementById("DisplayAccounts").childNodes[index].nodeValue;         
        document.getElementById("MyCenterBox_QuickChange_Container_AccountField").value = divValue;     
    }
 
}

//Functions added by Prashant
function highlightrow(orow,flag)
{
    //alert(orow.id);
    if(flag == 'H')
    {
        //alert(orow.style.backgroundColor);
        orow.style.backgroundColor="#FFFFCC";
    }
    else
    {
        orow.style.backgroundColor="#F5F5F5";
    }
}

function recurringSeachClick(orow,orderID)
{
	var prefix = "ctl00_PageContent_MainBox_";
    var displayType;
	var theImage;
	//alert(orow.id + ' passed val : ' + prefix + "Order" + orderID);
	var theDetailRow = document.getElementById(prefix + "Order" + orderID);
	//alert(theDetailRow);
		
	if (document.getElementById(prefix + "Order" + orderID).style.display == 'none') {
		theImage = "../images/minus_orange.gif";
		displayType = "";
	} else {
		theImage = "../images/plus_orange.gif";
		displayType = "none";
	}
	
	document.getElementById(prefix + "Image" + orderID).src = theImage;
	theDetailRow.style.display = displayType;    
}

function validateDiscontinue(obutton,recurringsearchid)
{
    var sResult;
    var objrecurringsearchid;
    var objcancelflag
    
    sResult = confirm("This will cancel the recurring search.\nDo you wish to continue?");
    //alert(obutton.href);
    //obutton.href = ".";    
    //alert(sResult);
    if(sResult)
    {
        objrecurringsearchid = document.getElementById('recurringsearchid')
        objcancelflag = document.getElementById('cancelflag')
        //alert(objrecurringsearchid.value);
        objrecurringsearchid.value = recurringsearchid
        objcancelflag.value = "yes";
        document.getElementById('postbackforupdate').value = 'YES';//this flas will inform postback logic that postback happened due to some sort of updates
        //alert(objrecurringsearchid.value + ' and ' + objcancelflag.value);
    }
    return sResult;
}

function UpdateHiddenValues(ofreqDD,parentOrderId,recurringsearchid)
{
    var idPrefix;
    var editButton;
    var freqId;
    var freqText;
    var hiddenrecurringsearchid;
    var hiddenfrequencyid;
    var hiddenfrequency;
    
    idPrefix = 'ctl00_PageContent_MainBox_';
    editButton = document.getElementById(idPrefix + 'Button|Update|' + parentOrderId);  
    
    hiddenrecurringsearchid = document.getElementById('recurringsearchid');//this is the record that we have to update the frequency for in DB
    hiddenfrequencyid = document.getElementById('frequencyid');
    hiddenfrequency = document.getElementById('frequency');
    
    freqId = ofreqDD.value;
    var w = ofreqDD.selectedIndex;
    freqText = ofreqDD.options[w].text;
    
    
    hiddenrecurringsearchid.value = recurringsearchid;//assign value to hidden variable
    hiddenfrequencyid.value = freqId;//assign value to hidden variable
    hiddenfrequency.value = freqText;//assign value to hidden variable  
    document.getElementById('postbackforupdate').value = 'YES';//this flas will inform postback logic that postback happened due to some sort of updates
    
    //alert('Searchid' + hiddenrecurringsearchid + ' freqid' + hiddenfrequencyid + ' text ' + hiddenfrequency);
}

function SortColumn(name)
{
    document.getElementById('sortedcolumn').value= name;
}