/* 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;
}

/* 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 = '';}
}
/* OnLoadFocus: (window.onload) Sets initial focus to the control specified */
function OnLoadFocus(ctrl) {
	var e = document.getElementById(ctrl);
	if (e) e.focus();
}
/* eSpares.ClientValues: class that makes server side values accessible on the client */
eSpares.ClientValues = function () {
    var m_Config = null;
    return {
        initialize: function(config) {
            if (m_Config == null)
                m_Config = new Object();
                
            for (attrname in config)
                m_Config[attrname] = config[attrname];
        },
        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;
}

// This function will find how far the window has scrolled vertically
function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

var Popup;

// Uses JQuery to show the passed object in a modal screen;
// its parameter are the HTML object (or its JQuery wrapper) that are going to be contained in the Modal screen, and a boolean value that is true if a fading animation is to be played.
// The modal screen will be turned off by clicking anywhere on the modal screen itself, or by invoking the closeModalPopup() method.
function modalPopup(object, anim) {

    if (typeof(object.jquery) == "undefined")
        object = $(object);
        
    if (typeof(object.jquery) == "undefined")
        return;
        
    Popup = object;

    //Get the screen height and width  
    var maskHeight = $(document).height();  
    var maskWidth = $.browser.opera && $.browser.version > "9.5" && $.fn.jquery <= "1.2.6" ? document.documentElement["clientWidth"] : $(window).width();
    
    if ($("#Mask").length == 0) {
        $("#wrapper").before('<div id="Mask" style="position:absolute; z-index:9000; opacity: 0.3; background-color:#000; left: 0; top: 0; display:none;"></div>');
        //$('<div id="Mask" style="position:absolute; z-index:9000; opacity: 0.3; background-color:#000; left: 0; top: 0; display:none;"></div>').appendTo("body");
    }

    //Set height and width to mask to fill up the whole screen  
    $('#Mask').css({'width':maskWidth,'height':maskHeight});
    $('#Mask').click(function() { $('#Mask, .window').hide(); object.hide(); });

    if (anim) {
        //transition effect       
        $('#Mask').fadeIn(400);      
        $('#Mask').fadeTo("fast",0.3);
    } else {
        $('#Mask').show();
        $('#Mask').css("opacity", 0.3);
    }

    //Get the window height and width  
    var winH = $(window).height();  
    var winW = $.browser.opera && $.browser.version > "9.5" && $.fn.jquery <= "1.2.6" ? document.documentElement["clientWidth"] : $(window).width();
         
    //Set the popup window to center  
    object.css('top',  winH/2-$(object).height()/2 + getScrollY());  
    object.css('left', winW/2-$(object).width()/2);  
    object.css('z-index', 9001);
    object.css('position', 'absolute');
    object.css('display', 'none');

    if (anim) {
        //transition effect  
        object.fadeIn(400);
    } else {
        object.show();
    }
}

// this method closes the modal popup created by the previous function
function closeModalPopup() {
    $('#Mask, .window').hide();
    Popup.hide();
    if (typeof(object) != "undefined")
        object.hide();
}

