/* eSpares client namespace */

if (typeof(eSpares) == 'undefined') {
    createNamespace('eSpares');
    eSpares.__namespace = true;
}

/* createNamespace: Creates namespaces */
function createNamespace(namespacePath) {
	var i = 1, a=arguments, ptr = null, l1, l2, pathArr, j = 0, base=namespacePath;
	if (typeof base != "object") {
		i = 0;
		base = window;
	}		
	for(l1=a.length; i<l1; i++){
		pathArr = a[i].split(".");
		ptr = base;
		for(l2=pathArr.length; j<l2; j++){
			if (typeof ptr[pathArr[j]] == 'undefined')
				ptr[pathArr[j]] = {};
			ptr = ptr[pathArr[j]]; 
		}
	}
	return ptr;
}

/* BookmarkPage: Bookmarks page with description and URL */
function BookmarkPage(url, name) {
	var ua=navigator.userAgent.toLowerCase();
	var isSafari=(ua.indexOf('webkit')!=-1);
	var isMac=(ua.indexOf('mac')!=-1);
	var buttonStr=isMac?'Command/Cmd':'CTRL';
	if (document.all && window.external) {
		window.external.AddFavorite(url, name);
	} else if (window.sidebar) {
		window.sidebar.addPanel(name, url, '');
	} else if (window.opera && window.print) {
		var mbm = document.createElement('a');
		mbm.setAttribute('rel','sidebar');
		mbm.setAttribute('href',url);
		mbm.setAttribute('title',name);
		mbm.click();
	} else if (window.home || isSafari)
		alert('You need to press '+buttonStr+' + D to bookmark this site.');
}
/* ExternalLinks: (window.onload) Allows using rel="external" instead of target="_blank" */
function ExternalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}
/* TextBoxString: Sets an initial value for a textbox when the normal value is blank. */
function TextBoxString(textBox, String, State) {
	if (State == 'f') { if (textBox.value == String) textBox.value = ''; }
	if (State == 'b') { if (textBox.value == '') textBox.value = String; }
	if (State == 's') {	if (textBox.value == String) textBox.value = '';}
}
/* DisableRClick: (window.onload) Disables right-click on images for a web page. */
function DisableRClick() {
	if (document.images) {
		for (i = 0; i < document.images.length; i++) {
			document.images[i].onmousedown = ImgRClick;
			document.images[i].oncontextmenu = new Function("return false;")
		}
	}
}
/* ImgRClick: If DisableRightClick has been run, this function alerts user on right click on image. */
function ImgRClick(e) { 
	var msg = 'This content is copyright protected.'; 
	if (navigator.appName == 'Netscape' && e.which == 3) {
		alert(msg); 
		return false; 
	} 
	if (navigator.appName == 'Microsoft Internet Explorer' && event.button==2) {
		alert(msg);	
		return false; 
	} else return true;
}
/* OnLoadFocus: (window.onload) Sets initial focus to the control specified */
function OnLoadFocus(ctrl) {
	var e = document.getElementById(ctrl);
	if (e) e.focus();
}
/* RoundDecimal: Rounds a number to decimal places specified. */
function RoundDecimal(input, decimals) {
	return input.toFixed(decimals);
}

/* switchMenu: Switches backgrounds in left nav menu items */
function SwitchMenu(obj, subMenuOn, subMenuOff, menuOn) {
	var el = document.getElementById(obj);
	if (!HasClassName(el, subMenuOn)) {
		el.className += " " + subMenuOn;
		el.parentNode.className += " " + menuOn;
	}
	else {
		el.className= el.className.replace(new RegExp(subMenuOn + "\\b"), subMenuOff);
		el.parentNode.className = el.className.replace(new RegExp(menuOn + "\\b"), "");
	}
}

/* hasClassName: checks to see if a DOM element has a particular class */
function HasClassName(element, className) {
	if (element.className.indexOf(className) > -1) {
		return true;
	}
	return false;
}

/* LoadMenu: loads the left nav menu only if user agent has javascript - FUNCTION CURRENTLY UNUSED */
function LoadMenu() {
	var objList = document.getElementById("nav").getElementsByTagName("ul");
	for (i=0; i<objList.length; i++ ) {
		objList[i].className = "subMenu";
	}
}

/* eSpares.ClientValues: class that makes server side values accessible on the client */
eSpares.ClientValues = function () {
    var m_Config = null;
    return {
        initialize: function(config) {
            m_Config = config;
        },
        getField: function (serverId) {
            if (!m_Config)
                return null;
            return m_Config[serverId];
        }
    }
}();

/* Class to select all Checkboxes of the form.
 * NOTE: this relies on having the form structure built according to some proprietary specifications, who are however common and pretty much the same thorough the whole BackOffice.
 * NOTE: this method uses ExtJS functionalities
 *
 * DEPRECATED: please use selectAllComboBoxesRow from now on
 */
function selectAllComboBoxes() {
    if (!this.tableClass)
        selectAllComboBoxesFull("orderitemGrid", "checkbox noBorder", "chkSelectAll");
    else
        selectAllComboBoxesFull(this.tableClass, "checkbox noBorder", "chkSelectAll");
}


// Performs the selection of all Checkboxes of a given table, and the row that contains the checkboxes.
//
// Parameters
// tableClass: class of the table where the selection has to take place
// row: the column where the checkboxes are located (1..n)
// checkSelectAll: ID of the checkbox that triggers the select all
function selectAllComboBoxesRow(tableClass, row, checkSelectAll) {

    // We first check if the checkboxClass is INCLUDED in the class of the first span contained in the first cell of the table
    var boxes = Ext.DomQuery.select("table[class='"+ tableClass +"'] tbody td:nth-child("+ row +") span input");
    
    var allChecked = true;
    for (counter = 0; counter < boxes.length; counter++) {
        if (boxes[counter].checked == false && boxes[counter].disabled == false) {
            allChecked = false;
            counter = boxes.length;
        }
    }

    for (counter = 0; counter < boxes.length; counter++) {
        if (boxes[counter].checked == allChecked) {
            boxes[counter].click();
        }
    }

    Ext.get(checkSelectAll).dom.checked = !allChecked;
}

// Performs the selection of all Checkboxes of a given table. Starts looking for the checkboxes in the first row, goes ahead and stops when the table is over or it found the checkboxes.
//
// Parameters
// tableClass: class of the table where the selection has to take place
// checkboxClass: class of the span that contains the checkbox
// checkSelectAll: ID of the checkbox that triggers the select all
function selectAllComboBoxesFull(tableClass, checkboxClass, checkSelectAll) {

    // We first check if the checkboxClass is INCLUDED in the class of the first span contained in the first cell of the table
    var boxes = Ext.DomQuery.select("table[class='"+ tableClass +"'] tbody td:nth-child(1) span");
    var tableColumns = Ext.DomQuery.select("table[class='"+ tableClass +"'] tr:first-child td");
    
    for (counter = 2; counter < tableColumns.length; counter++) {
        if (boxes.length == 0) {
            boxes = Ext.DomQuery.select("table[class='"+ tableClass +"'] tbody td:nth-child("+ counter +") span");
        } else {
            counter = tableColumns.length;
        }
    }
    
    if (boxes[0] != null) {
        if (boxes[0].className.search(checkboxClass) != -1) {
            
            // In this case, we set checkboxClass to this className - so that the next query will automatically match this
            checkboxClass = boxes[0].className;
            
            var boxes = Ext.DomQuery.select("table[class='"+ tableClass +"'] td:first-child span[class='"+ checkboxClass +"'] input");
            
            if (boxes.length == 0) {
                gotTableCells = Ext.DomQuery.select("table[class='"+ tableClass +"'] tr:first-child td");
                if (gotTableCells.length != 0) {
                    for (counter = 2; counter <= gotTableCells.length; counter++) {
                        boxes = Ext.DomQuery.select("table[class='"+ tableClass +"'] tbody td:nth-child("+ counter +") span[class='"+ checkboxClass +"'] input");
                        if (boxes.length != 0) {
                            counter = gotTableCells.length + 1;
                        }
                    }
                }
            }
        }
    }
            
    var allChecked = true;
    for (counter = 0; counter < boxes.length; counter++) {
        if (boxes[counter].checked == false && boxes[counter].disabled == false) {
            allChecked = false;
            counter = boxes.length;
        }
    }

    for (counter = 0; counter < boxes.length; counter++) {
        if (boxes[counter].checked == allChecked) {
            boxes[counter].click();
        }
        //boxes[counter].checked = !allChecked;
    }

    Ext.get(checkSelectAll).dom.checked = !allChecked;
}

function UniqueIDWithDollars(ctrlName)
{
    if (ctrlName == null)
    {
        return null;
    }

    if (ctrlName.search(':') >= 0)
    {
        return ctrlName.replace(':', '$');
    }

    return ctrlName;
}