var pageLock=0;
var preloadDebugMsg = '';

function doDebug(the_message) {
   if (document.debugForm) {
        document.debugForm.debugTextArea.value = the_message + "\n" + document.debugForm.debugTextArea.value;
   }
}


function getEventCoordinates(e) {
    var xCoordinate=0;
    var yCoordinate=0;

    if (document.all) {
        xCoordinate=event.clientX + document.body.scrollLeft;
        yCoordinate=event.clientY + document.body.scrollTop;
    } else if (document.layers) {
        xCoordinate=e.x;
        yCoordinate=e.y;
    } else if (document.getElementById) {
        xCoordinate=e.clientX;
        yCoordinate=e.clientY;
    } else {
        xCoordinate=e.pageX;
        yCoordinate=e.pageY;
    }
    if (xCoordinate < 0){xCoordinate = 0}
    if (yCoordinate < 0){yCoordinate = 0}
    return new objectCoordinates(xCoordinate, yCoordinate);
}

function objectCoordinates(objCoordX, objCoordY, objTrueX, objTrueY) {
    this.objCoordX = objCoordX;
    this.objCoordY = objCoordY;
    this.objTrueX = objTrueX;
    this.objTrueY = objTrueY;
}

function getImageCoordinates(imageObjId, xOffset, yOffset, layer) {
    var theObject;
    if (layer) {
        theObject = parent.document.images[imageObjId];
    } else {
        theObject = document.images[imageObjId];
    }
    if (theObject == null) {
        return null;
    }

    if (imageObjId.indexOf('_right') != -1) {
        xOffset = xOffset - theObject.width;
    }
    theObject.style.position = "absolute"
    var objX = 0;
    var objY = 0;
    var objTX = 0;
    var objTY = 0;
    if (document.layers) {
        objX=theObject.x;
        objY=theObject.y;
        objTX=objX - window.pageXOffset;
        objTY=objY - window.pageYOffset;
    } else if (document.all) {
        objX=theObject.offsetLeft;
        objY=theObject.offsetTop;
        if (layer) {
            objTX=objX - parent.document.body.scrollLeft;
            objTY=objY - parent.document.body.scrollTop;
        } else {
            objTX=objX - document.body.scrollLeft;
            objTY=objY - document.body.scrollTop;
        }
    } else {
        objX=theObject.offsetLeft;
        objY=theObject.offsetTop;
        if (layer) {
            objTX=objX - parent.document.body.scrollLeft;
            objTY=objY - parent.document.body.scrollTop;
        } else {
            objTX=objX - document.body.scrollLeft;
            objTY=objY - document.body.scrollTop;
        }
    }
    objX+=xOffset;
    objY+=yOffset;
    objTX+=xOffset;
    objTY+=yOffset;
    theObject.style.position = "static";
    return new objectCoordinates(objX, objY, objTX, objTY);
}

function getObjectCoordinates(objectId, xOffset, yOffset) {
    var theObject = document.getElementById(objectId);
    if (theObject == null) {
        return null;
    }
    theObject.style.position = "absolute"
    var objX = 0;
    var objY = 0;
    var objTX = 0;
    var objTY = 0;
    if (document.layers) {
        objX=theObject.x;
        objY=theObject.y;
        objTX=objX - window.pageXOffset;
        objTY=objY - window.pageYOffset;
    } else if (document.all) {
        objX=theObject.offsetLeft;
        objY=theObject.offsetTop;
        objTX=objX - document.body.scrollLeft;
        objTY=objY - document.body.scrollTop;
    } else {
        objX=theObject.offsetLeft;
        objY=theObject.offsetTop;
        objTX=objX - document.body.scrollLeft;
        objTY=objY - document.body.scrollTop;
    }
    objX+=xOffset;
    objY+=yOffset;
    objTX+=xOffset;
    objTY+=yOffset;
    theObject.style.position = "static"
    return new objectCoordinates(objX, objY, objTX, objTY);
}

function getAllSheets() {
    //if you want ICEbrowser's limited support, do it this way
    if( !window.ScriptEngine && navigator.__ice_version ) {
        //IE errors if it sees navigator.__ice_version when a window is closing
        //window.ScriptEngine hides it from that
        return document.styleSheets;
    }
    if( document.getElementsByTagName ) {
        //DOM browsers - get link and style tags
        var Lt = document.getElementsByTagName('LINK');
        var St = document.getElementsByTagName('STYLE');
    } else if( document.styleSheets && document.all ) {
        //not all browsers that supply document.all supply document.all.tags
        //but those that do and can switch stylesheets will also provide
        //document.styleSheets (checking for document.all.tags produces errors [WHY?!])
        var Lt = document.all.tags('LINK'), St = document.all.tags('STYLE');
    } else {
        return [];
    } //lesser browser - return a blank array
    //for all link tags ...
    for( var x = 0, os = []; Lt[x]; x++ ) {
        //check for the rel attribute to see if it contains 'style'
        if( Lt[x].rel ) {
            var rel = Lt[x].rel;
        } else if( Lt[x].getAttribute ) {
            var rel = Lt[x].getAttribute('rel');
        } else {
            var rel = '';
        }
        if( typeof( rel ) == 'string' && rel.toLowerCase().indexOf('style') + 1 ) {
            //fill os with linked stylesheets
            os[os.length] = Lt[x];
        }
    }
    //include all style tags too and return the array
    for( var x = 0; St[x]; x++ ) {
        os[os.length] = St[x];
    }
    return os;
}

function changeStyle() {
    for( var x = 0, ss = getAllSheets(); ss[x]; x++ ) {
        //for each stylesheet ...
        if( ss[x].title ) {
            //disable the stylesheet if it is switchable
            ss[x].disabled = true;
        }
        for( var y = 0; y < arguments.length; y++ ) {
            //check each title ...
            if( ss[x].title == arguments[y] ) {
                //and re-enable the stylesheet if it has a chosen title
                ss[x].disabled = false;
            }
        }
    }
    if( !ss.length ) {
        alert( 'Your browser cannot change stylesheets' );
    }
}

function instructionOn(instruction) {
    if (pageLock == 0 && labelAlignObject) {
        try {
            document.getElementById("labelLayerMsg").innerHTML=instruction;
            document.getElementById("labelLayer").style.left=labelAlignObject.objCoordX;
            document.getElementById("labelLayer").style.top=labelAlignObject.objCoordY;
            document.getElementById("labelLayer").style.width="250px";
            document.getElementById("labelLayer").style.height="15px";
            document.getElementById("labelLayer").style.visibility="visible";
        } catch (er) {
            doDebug(er);
        }
        return;
    }
}

function instructionOff() {
    try {
        document.getElementById("labelLayer").style.visibility="hidden";
    } catch (er) {
        doDebug(er);
    }
    return;
}

var balloonHelpTimeout = 1200; // in milliseconds

function balloon(objectId, balloonMsg, messageBoxWidth, messageBoxHeight, balloonXOffset, balloonYOffset) {
    if (messageBoxHeight == null) {
        messageBoxHeight=10;
    }
    if (messageBoxWidth == null) {
        messageBoxWidth=10;
    }
    if (pageLock == 0 && bubbleHelpActive) {
        try {
            var balloonAlignObject = getImageCoordinates(objectId, balloonXOffset, balloonYOffset);
            if (balloonAlignObject == null) {
                balloonAlignObject = getObjectCoordinates(objectId, balloonXOffset, balloonYOffset);
            }
            var balloonX=balloonAlignObject.objCoordX-messageBoxWidth;
            var balloonY=balloonAlignObject.objCoordY;
            document.getElementById("balloonLayerMsg").innerHTML=balloonMsg;
            document.getElementById("balloonLayer").style.left=balloonX;
            document.getElementById("balloonLayer").style.top=balloonY;
            if (messageBoxWidth != null) {
                document.getElementById("balloonLayer").style.width=messageBoxWidth;
            }
            if (messageBoxHeight != null) {
                document.getElementById("balloonLayer").style.height=messageBoxHeight;
            }
            document.getElementById("balloonLayer").style.visibility="visible";
        } catch (er) {
            doDebug(er);
        }
        return;
    }
}

function killBalloon() {
    try {
        document.getElementById("balloonLayer").style.visibility="hidden";
    } catch (er) {
        doDebug(er);
    }
    return;
}

function pause(numberMillis) {
    if (numberMillis != 0) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    } else {
        return;
    }
}

var doItTimer=null;
function doIt(doBool, doAction, waitMS) {
    if(doBool) {
        doItTimer=setTimeout(doAction, waitMS);
    }
}
function undoIt() {
    if (doItTimer) {
        clearTimeout(doItTimer);
        doItTimer=null;
    }
}

/*function showWaitLayer(waitLayerMsg) {
    searchAlignObject = getImageCoordinates("searchImg", -1, 0);
    lastAlignObject = getImageCoordinates("lastImg", 0, 0);
    document.getElementById("waitLayerMsg").innerHTML=waitLayerMsg;
    document.getElementById("waitLayer").style.left=searchAlignObject.objCoordX;
    document.getElementById("waitLayer").style.top=searchAlignObject.objCoordY;
    document.getElementById("waitLayer").style.width=1000;
    document.getElementById("waitLayer").style.height=(lastAlignObject.objCoordY - searchAlignObject.objCoordY);
    document.getElementById("waitLayer").style.visibility="visible";
}*/

function showLoadingLayer(loadingLayerMsg) {
    searchAlignObject = getImageCoordinates("searchImg", -1, 0);
    document.getElementById("waitLayerMsg").innerHTML=loadingLayerMsg;
    document.getElementById("waitLayer").style.left=searchAlignObject.objCoordX;
    document.getElementById("waitLayer").style.top=searchAlignObject.objCoordY;
    document.getElementById("waitLayer").style.width=1000;
    document.getElementById("waitLayer").style.height=(windowheight - searchAlignObject.objCoordY);
    document.getElementById("waitLayer").style.visibility="visible";
}

function preloadImages(thisImgArray) {
    if (document.images) {
        for(var loop = 0; loop < thisImgArray.length; loop++) {
            var an_image = new Image();
            an_image.src = thisImgArray[loop];
        }
    }
}

function toggleImages(thisDivImgStart, thisToggleImg_1, thisToggleImg_2) {
    thisDivImgStartObj = document.images[thisDivImgStart];
    var curImgSrc = thisDivImgStartObj.src;
    if (curImgSrc.indexOf(thisToggleImg_1) > 0) {
        thisDivImgStartObj.src = thisToggleImg_2;
    } else if (curImgSrc.indexOf(thisToggleImg_2) > 0) {
        thisDivImgStartObj.src = thisToggleImg_1;
    }
}

function toggleImagesAll(tableId, rowIdPrefix, state, rowImgIdPrefix, thisToggleImg_1, thisToggleImg_2) {
    var tableObj = document.getElementById(tableId);
    for (var rowNum=0; rowNum<tableObj.rows.length; rowNum++) {
        if(tableObj.rows[rowNum].id.length > rowIdPrefix.length) {
            if (tableObj.rows[rowNum].id.substring(0,rowIdPrefix.length) == rowIdPrefix) {
                var rowImgId = rowImgIdPrefix + tableObj.rows[rowNum].id.substring(rowIdPrefix.length);
                if (state == 1) {
                    document.images[rowImgId].src = thisToggleImg_1;
                } else if (state == 2) {
                    document.images[rowImgId].src = thisToggleImg_2;
                }
            }
        }
    }
}

function toggleVisibility(visId) {

    var visObj = document.getElementById(visId);
    if(visObj){
       if (visObj.style.display=='none') {
            visObj.style.display = ''
        } else {
	   visObj.style.display = 'none'
        }
    }
}

function setVisibility(visId, state) { // state == SHOW OR HIDE
    var visObj = document.getElementById(visId);
    if (visObj.style.display=='none') {
      if (state == 'SHOW') {
            visObj.style.display = ''
        }
    } else {
        if (state == 'HIDE') {
            visObj.style.display = 'none'
        }
    }
}

function toggleVisibilityAll(tableId, rowIdPrefix, state) {
    var visObj = document.getElementById(tableId);
    for (var rowNum=0; rowNum<visObj.rows.length; rowNum++) {
        if(visObj.rows[rowNum].id.length > rowIdPrefix.length) {
            if (visObj.rows[rowNum].id.substring(0,rowIdPrefix.length) == rowIdPrefix) {
                if (state == 'SHOW') {
                    visObj.rows[rowNum].style.display = "";
                } else if (state == 'HIDE') {
                    visObj.rows[rowNum].style.display = "none";
                }
            }
        }
    }
}

var hex=255 // Initial color value.
function fadetext(txtId){
    if(hex>0) { //If color is not black yet
        hex-=11; // increase color darkness
        document.getElementById(txtId).style.color="rgb("+hex+","+hex+","+hex+")";
        setTimeout("fadetext()",20);
    } else {
        hex=255 //reset hex value
    }
}

function confirmEntry(confirmMsg) {
    var confirmInputBox=confirm(confirmMsg);
    if (confirmInputBox==true) {
        return true;
    } else {
        return false;
    }
}

function printWindow(){
    if (is.v >= 4) {
        window.print();
    } else {
        alert('The current computer does not support this print button.  Please use the browser print function from the file menu.');
    }
}

function checkNumber(theNumCandidate){
    if (theNumCandidate.substring(0,1) == '-') {
        theNumCandidate = theNumCandidate.substring(1);
    }
    var anum=/(^\d+$)|(^\d+\.\d+$)|(^\.\d+$)/
    if (anum.test(theNumCandidate)) {
        return true;
    } else {
        return false;
    }
}

function validStringNum(testString) {
    var value = true;
    var notValidChars = /[^a-zA-Z0-9]/;
    return !notValidChars.test(testString);
}

function popupWindow(popupTargetURL, popupProps, windowName) {
    var myPopup=window.open(popupTargetURL, windowName, popupProps);
    if (myPopup == null) {
        alert('Warning : This browser does not allow popup windows.  Please activate popup windows on this browser and try again.');
    } else {
        myPopup.focus();
    }
    return;
}

function popupBlankWindow(popupTargetName, popupProps) {
    var myPopup=window.open('', popupTargetName, popupProps);
    if (myPopup == null) {
        alert('Warning : This browser does not allow popup windows.  Please activate popup windows on this browser and try again.');
    } else {
        myPopup.focus();
    }
    return;
}

function trimWhiteSpace(str) {
    str = this != window? this : str;
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function timedOut( win ) {
    var w = win || ( ( self == top ) ? ( self.dialogArguments || self.opener ) : self.parent ) || top;
    top.location.reload();
}

function getKeyEventCharacterCode(e, returnCharacterType) { // returnCharacterType = 'character' or 'decimal'
    var pressedKey;
    if (document.all)    { e = window.event; }
    if (e.keyCode) {
        pressedKey = e.keyCode;
    } else if (e.which) {
        pressedKey = e.which;
    } else {
        return;
    }
    pressedCharacter = String.fromCharCode(pressedKey);
    // alert(' Character = ' + pressedCharacter + ' [Decimal value = ' + pressedKey + ']');

    if (returnCharacterType == 'character') {
        if (pressedCharacter) {
            return pressedCharacter;
        }
    } else if (returnCharacterType == 'decimal') {
        if (pressedKey) {
            return pressedKey;
        }
    } else {
        alert('getKeyEventCharacterCode() Error : Malformed return character type == ' + returnCharacterType);
    }
    return false;
}

function validCard(CreditCard){
    // Valid Input Syntax:
    // Type1: **************** (16 columns)
    // Type2: **** **** **** **** (19)
    // Type3: ****-****-****-**** (19)
    // Input is a credit card number in the form of a string.
    // Validates numbers which use a "double-add-double MOD 10"
    // check digit Output is False if not valid, True if valid.
    
    var Validity = false;       // Assume invalid card
    var LN = CreditCard.length;      // Get input value length
    if ((15 <= LN) && (LN <= 19)){
        Validity = true;
/* DISABLE JS CC VALIDATION -- MOVE VALIDATION TO SERVER
        if (CreditCard.substring(0, <%= AppConstants.CC_MASK.length() %>) == '<%= AppConstants.CC_MASK %>') {
            return true;
        }

        LN --;
        CheckSum = 0;       // start with 0 checksum
        Dbl = false;        // Start with a non-doubling

        //------------------------------------------------------------
        //  Beginning backward loop through string
        //-------------------------------------------------------------

        for (Idx = LN; Idx >= 0; Idx --){
            Digit = CreditCard.substr(Idx, 1);        // Isolate character
            if (("0" <= Digit && Digit <= "9") || Digit == " " || Digit == "-"){
                if (Digit != " " && Digit != "-"){ // Skip connector
                    Digit -= "0";     // Remove ASCII bias
                    if (Dbl){                 // If in the "double-add" phase
                        Digit += Digit; // Then double first
                        if (Digit > 9){ // Cast nines
                            Digit -= 9;
                        }
                    }
                    Dbl = !Dbl; // Flip doubling flag
                    CheckSum += Digit;  // Add to running sum
                    if (CheckSum > 9){  // Cast tens
                        CheckSum -= 10; // Same as MOD 10, but faster
                    }
                }
            } else {
                return(Validity);   // Invalid
            }
        }
        Validity = (CheckSum == 0) ? true : false; // Must sum to 0
*/
    }
    return(Validity);
}

function Browser() {
        var b=navigator.appName;

        if (b.indexOf('Netscape')!=-1) this.b="ns";
        else if ((b=="Opera") || (navigator.userAgent.indexOf("Opera")>0)) this.b = "opera";
        else if (b=="Microsoft Internet Explorer") this.b="ie";

        ii=navigator.userAgent.toLowerCase();
        if (ii.toLowerCase().indexOf('safari')!=-1) this.b="safari";// added by inkoo
        else if (ii.toLowerCase().indexOf('omniweb')!=-1) this.b="omniweb";// added by inkoo
        else if (ii.toLowerCase().indexOf('webtv')!=-1) this.b="webtv";// added by inkoo
        else if (ii.toLowerCase().indexOf('icab')!=-1) this.b="icab";// added by inkoo
        else if (ii.toLowerCase().indexOf('msie')!=-1) this.b="ie";// added by inkoo
        else if (ii.toLowerCase().indexOf('kopnqueror')!=-1) this.b="konqueror";// added by inkoo

        if (!b) alert('Unidentified browser.\nThis browser is not supported,');
        this.version=navigator.appVersion;
        this.v=parseInt(this.version);
        this.ns=(this.b=="ns" && this.v>=4);
        this.ns4=(this.b=="ns" && this.v==4);
        this.ns6=(this.b=="ns" && this.v==5);
        this.ie=(this.b=="ie" && this.v>=4);
        this.ie4=(this.version.indexOf('MSIE 4')>0);
        this.ie5=(this.version.indexOf('MSIE 5')>0);
        this.ie55=(this.version.indexOf('MSIE 5.5')>0);
        this.ie6=(this.version.indexOf('MSIE 6.0')>0);
        this.opera=(this.b=="opera");
        this.dom=(document.createElement && document.appendChild && document.getElementsByTagName)?true:false;
        this.def=(this.ie||this.dom); // most used browsers, for faster if loops
        this.safari=(this.b=="safari");
        var ua=navigator.userAgent.toLowerCase();

        if (ua.indexOf("win")>-1) this.platform="win32";
        else if (ua.indexOf("mac")>-1) this.platform="mac";
        else if (ua.indexOf("linux")>-1) this.platform="linux";
        else if (ua.indexOf("x11")>-1) this.platform="Unix";
        else this.platform="other";
}
is=new Browser();  


var secondaryLayerWidth = 520;
var secondaryLayerHeight = 500;
var secondaryTitleHeight = 25;

function boxcarSubmodal(targetPage) {
    if (targetPage && targetPage != '') {
        scroll(0,0);
        if (document.getElementById('popupTitle')) {
            document.getElementById('popupTitle').innerHTML = 'Boxcar Add/Edit Toolbox';
            showPopWin(targetPage, secondaryLayerWidth, secondaryLayerHeight);
            changeOpac(0,'popupMask');
            setTimeout("fadeTransparency(0, 10, 250, 70, 'popupMask')", 1000);
        }
    }
}

var tertiaryLayerWidth = 420;
var tertiaryLayerHeight = 420;
function boxcarSubmodal2(targetPage) {
    if (targetPage && targetPage != '') {
        scroll(0,0);
        if (parent.document.getElementById('popupTitle2')) {
            parent.document.getElementById('popupTitle2').innerHTML = 'Boxcar Add/Edit Toolbox';
            showPopWin2(targetPage, tertiaryLayerWidth, tertiaryLayerHeight);
            changeOpac(0,'popupMask2', true);
            setTimeout("fadeTransparency(0, 6, 200, 50, 'popupMask2', 'true')", 1200);
        }
    }
}

function fadeOpacity(counter, steps, total_ms, final_opacity, objectid, level) {
    counter += 1;
    if (counter <= steps) {
        var interval_ms = parseInt(total_ms/steps);
        var interval_opacity = parseInt((100-final_opacity)/steps);
        var current_opacity = 100 - (counter * interval_opacity);
        changeOpac(current_opacity, objectid, level);
        var nextFunction = "fadeOpacity(" + counter + ", " + steps + ", " + total_ms + ", " + final_opacity + ", '" + objectid + "', " + level + ")";
        setTimeout(nextFunction, interval_ms);
    }
}

function fadeTransparency(counter, steps, total_ms, final_opacity, objectid, level) {
    counter += 1;
    if (counter <= steps) {
        var interval_ms = parseInt(total_ms/steps);
        var interval_opacity = final_opacity/steps;
        var current_opacity = (counter * interval_opacity);
        changeOpac(current_opacity, objectid, level);
        var nextFunction = "fadeTransparency(" + counter + ", " + steps + ", " + total_ms + ", " + final_opacity + ", '" + objectid + "', " + level + ")";
        setTimeout(nextFunction, interval_ms);
    }
}

function changeOpac(opacity, objectid, level) {
    var object;
    if (level) {
        object = parent.document.getElementById( objectid ).style;
    } else {
        object = document.getElementById( objectid ).style;
    }
    object.visibility = "visible";
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
    // object.style.filter = "alpha(opacity=" + opacity + ")"; 
}

function launchModuleSubModal(targetAct, userId) {

    boxcarSubmodal(rel_home+'/platemaking/pleaseWait.html');
    var updateModObj = top.document.getElementById("updateModuleFormId");
    updateModObj.targetAction.value = targetAct;
    updateModObj.submodalLevel.value = '1';
    updateModObj.target="popupFrame";
    updateModObj.userId.value = userId;
    setTimeout("submitModuleForm()",100);
}

function launchModuleSubModal2(targetAct, userId) {
    boxcarSubmodal2(rel_home+'/platemaking/pleaseWait.html');
    var updateModObj = top.document.getElementById("updateModuleFormId");
    updateModObj.targetAction.value = targetAct;
    updateModObj.submodalLevel.value = '2';
    updateModObj.target="popupFrame2";
    updateModObj.userId.value = userId;
    setTimeout("submitModuleFormPop()",100);

}

function submitModuleForm() {
    var updateModObj = top.document.getElementById("updateModuleFormId");
    updateModObj.submit();
}

function submitModuleFormPop() {
    var updateModObj = top.document.getElementById("updateModuleFormId");
    updateModObj.submit();
}

function validateEmail(str){
    
        var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		 
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		   
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		   
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		   
		    return false;
		 }

 		 return true;	
}

function validateUpdateForm(formObj){
   var errMsg="";
    if (formObj['username'].value=='') {
        errMsg+="  - email field was left empty.";
    }
    
    
    if(formObj['passwordChanged'].value == 'true'){
    
        
        if (formObj['password'].value=='') {
            errMsg+="\n  - password field was left empty.";
        }else if(formObj['password'].value.length < pwMinLen){
            errMsg+="\n - password cannot be less than "+pwMinLen+" characters long."
        }

         if(formObj["repassword"].value != formObj["password"].value){
               errMsg+="\n - passwords do not match.";

         }

     }
    
    if(formObj['firstName'].value==''){
        errMsg+="\n - first name field left empty.";
    }
    
    if(formObj['lastName'].value ==''){
        errMsg+="\n - last name field left empty."
    }
    
    if(formObj['city'].value == ''){
        errMsg+="\n - city field left empty."
    }
    
    if(formObj['state'].value == ''){
        errMsg+="\n - state field left empty."
    }
    
    if(formObj['zip'].value == ''){
        errMsg+="\n - zip field left empty."
    }
    
    if(formObj['phoneDay'].value == ''){
        errMsg+="\n - day phone field left empty."
    }
    
    if(validateEmail(formObj['username'].value) == false){
        errMsg+="\n - invalid email specified."
    }
    
   /* if($(formObj['editBillingId']).children().length < 2){
        errMsg+="\n - you must add at least one billing method."
    
    }*/

    if (errMsg != '') {
        alert("User login failed due to the following reason(s) : \n" + errMsg);
        return false;
    }
    
    return true;
    
}    



function validateRegisterForm(formObj) {
    var errMsg="";
    if (formObj['user.username'].value=='') {
        errMsg+="  - email field was left empty.";
    }
    if (formObj['user.password'].value=='') {
        errMsg+="\n  - password field was left empty.";
    }else if(formObj['user.password'].value.length < 8){
        errMsg+="\n - password cannot be less than 8 characters long."
    }
    
     if(formObj["repassword"].value != formObj["user.password"].value){
           errMsg+="\n - passwords do not match.";
           
     }
     
     if(formObj['user.password'].value.length < pwMinLen){
        errMsg += "\n- password must be greater than "+pwMinLen+".";
     
     }
         
    
    if(formObj['firstName'].value==''){
        errMsg+="\n - first name field left empty.";
    }
    
    if(formObj['lastName'].value ==''){
        errMsg+="\n - last name field left empty."
    }
    
    if(formObj['city'].value == ''){
        errMsg+="\n - city field left empty."
    }
    
    if(formObj['state'].value == ''){
        errMsg+="\n - state field left empty."
    }

    if(formObj['country'].value == ''){
        errMsg+="\n - country field left empty."
    }
    
    if(formObj['zip'].value == ''){
        errMsg+="\n - zip field left empty."
    }
    
    if(formObj['phoneDay'].value == ''){
        errMsg+="\n - day phone field left empty."
    }
    
    if(validateEmail(formObj['user.username'].value) == false){
        errMsg+="\n - invalid email specified."
    }
    
    
    if (errMsg != '') {
        alert("User login failed due to the following reason(s) : \n" + errMsg);
        return false;
    } else {
        return true;
    }
}

function validateLogonForm(formObj) {
    var errMsg="";
    if (formObj['username'].value=='') {
        errMsg+="  - email field was left empty.";
    }
     if (formObj['password'].value=='') {
        errMsg+="\n  - password field was left empty.";
    }
    
    if (errMsg != '') {
        alert("User login failed due to the following reason(s) : \n" + errMsg);
        return false;
    } else {
        return true;
    }
}

function setSelectOption(objId, optionVal) {
    var selectObj = document.getElementById(objId);
    if (selectObj && selectObj.options) {
        for (var i=0; i<selectObj.options.length; i++) {
            if (selectObj.options[i].value == optionVal) {
                selectObj.options[i].selected = true;
            } else {
                selectObj.options[i].selected = false;
            }
        }
    }
}

function setSelectOptionText(objId, optionVal) {
    var selectObj = document.getElementById(objId);
    if (selectObj && selectObj.options) {
        for (var i=0; i<selectObj.options.length; i++) {
            if (selectObj.options[i].text == optionVal) {
                selectObj.options[i].selected = true;
            } else {
                selectObj.options[i].selected = false;
            }
        }
    }
}

function replaceText(textId, newText) {
    var textObj = document.getElementById(textId);
    if (textObj) {
        textObj.innerHTML=newText;
    }
}


function sizeButtons(bsize){
    //How big do we want our buttons?
    var size = 20; //20 characters, not px or em, etc.
    
    if(bsize && bsize > 0){
        size = bsize;
    }
    
    var textSize = 0;
    var addTo = 0;
    var divAddTo = 0; //The number to add to each side.
    var butTag = null;
    var newString = ""; //Our new value for the tag.
    var tags = document.getElementsByTagName("span");
    
    for(i=0; i < tags.length; i++){
        butTag = tags[i];
        if(butTag.className == "boxcar-button"){
            textSize = butTag.innerHTML.length;
            addTo = size - textSize;

            /* If the button has too much text, we will increase all the buttons to that size */
            if(addTo < 0){
              continue; //for now
            }else{
                if(addTo%2 != 0){
                    addTo -= 1;
                }
                    //Nothing to do now.
                
                
                
                if(addTo == 0 ){
                        continue;
                }
                    
                divAddTo = addTo / 2;
                for(j=0; j < divAddTo; j++){
                     newString += "&nbsp;"
                }

                newString += butTag.innerHTML;

                for(j=0; j < divAddTo; j++){
                     newString += "&nbsp;"
                }

                //Now put the text back
                butTag.innerHTML = newString;
                newString = "";
            }       

                
         }
     }
}

function validateForm(formObj) {
	var uploadFormObj = document.uploadForm;
	if (uploadFormObj.ticketNumber.value == '') {
		alert('You must enter a valid ticket number to upload.  If yo do not have one, please create a ticket by adding an order before uploading.');
		return false;
	}
	if (uploadFormObj.uploadFile.value == '') {
		alert('Please select a file to upload.');
		return false;
	} else if (uploadFormObj.uploadFile.value.indexOf('.') == -1) {
		alert('Files must have an extension to upload (e.g. .jpg, .gif, .pdf, etc.). Please rename the file and try again.');
		return false;
	}
	return true;
}
function uploadPlate() {
	if (validateForm()) {
		//showWaitLayer();
		uploadFiles.loadingDialogBox();
		document.uploadForm.submit();
		if (document.images) {
			document.images['loadingBar'].src = gVariables.imgDir + "/loading.gif";
		}
		document.images['loadingBar'].style.visibility = "visible";
		document.images['loadingBar'].style.display= "inline"; 
	}
}


function viewOrders(){
		location.href = "?page=viewTickets";
 }
 
/*function showWaitLayer() {
	startAlignObject = getImageCoordinates("uploadStartImg", -1, 0);
	stopAlignObject = getImageCoordinates("uploadStopImg", 0, 0);
	document.getElementById("waitLayer").style.left=startAlignObject.objCoordX;
	document.getElementById("waitLayer").style.top=startAlignObject.objCoordY;
	document.getElementById("waitLayer").style.width=(stopAlignObject.objCoordX-startAlignObject.objCoordX);
	document.getElementById("waitLayer").style.height=(stopAlignObject.objCoordY-startAlignObject.objCoordY);
	document.getElementById("waitLayer").style.visibility="visible";
}*/

function objectCoordinates(objCoordX, objCoordY, objTrueX, objTrueY) {
	this.objCoordX = objCoordX;
	this.objCoordY = objCoordY;
	this.objTrueX = objTrueX;
	this.objTrueY = objTrueY;
}

function getImageCoordinates(imageObjId, xOffset, yOffset) {
	var theObject = document.images[imageObjId];
	if (theObject == null) {
		return null;
	}

	if (imageObjId.indexOf('_right') != -1) {
		xOffset = xOffset - theObject.width;
	}
	theObject.style.position = "absolute"
	var objX = 0;
	var objY = 0;
	var objTX = 0;
	var objTY = 0;
	if (document.layers) {
		objX=theObject.x;
		objY=theObject.y;
		objTX=objX - window.pageXOffset;
		objTY=objY - window.pageYOffset;
	} else if (document.all) {
		objX=theObject.offsetLeft;
		objY=theObject.offsetTop;
		objTX=objX - document.body.scrollLeft;
		objTY=objY - document.body.scrollTop;
	} else {
		objX=theObject.offsetLeft;
		objY=theObject.offsetTop;
		objTX=objX - document.body.scrollLeft;
		objTY=objY - document.body.scrollTop;
	}
	objX+=xOffset;
	objY+=yOffset;
	objTX+=xOffset;
	objTY+=yOffset;
	theObject.style.position = "static"
	return new objectCoordinates(objX, objY, objTX, objTY);
}
function swapCurrentTicket() {

//let's make this ajax?
	var curTickNum = document.getElementById("ticketNumber").options[document.getElementById("ticketNumber").selectedIndex].value;

	document.location = gVariables.relHome + '/platemaking/index.php?targetAction=' + gVariables.switchTicket + '&ticketNumber=' + curTickNum;


}

$(document).ready(function () {
	uploadFiles.init();
});

var uploadFiles = {
	init : function () {
		that = this;
		that.bindEvents();
	},
	bindEvents : function () {
		$(".boxcar-button").click(function () {
			if ($(this).attr('data-value') == 'uploadFile') {
				uploadPlate();
			} else if ($(this).attr('data-value') == "viewOrders") {
				viewOrders();
			}
		});
	},
	
	loadingDialogBox : function () {
		$('<span id ="loadingDialogBox"><img src="<!--{$IMG_DIR}-->/loading.gif" width="78" id="loadingBar" height="7" border="0"></span>').dialog({
			width : 200,
			height : 70,
			modal : true,
			closeOnEscape : false,
			resizeable : false,
			//dialogClass : "smack_dab",
			position : "center",
			open : function () {
				$(".ui-dialog-titlebar").hide();
			}
		});	
	}

};
/**
* this object handles change in country value
* It updates the state value based on country code.
* @params : object (country_code, state_selectbox_id, state_textbox_id) to change
* @returns : true on successful completion
*/
var handleCountryData = {
	
	init : function (options) {
		var that = this;
		var defaults = {
			'country_code' :'US',
			'state_select_id' : '#state_dd',
			'state_text_id' : '#alt_state' 
		};
		var optns = $.extend(defaults,options);
		that.updateCountryInfo(optns);
	},
	updateCountryInfo : function (opt) {
		if(opt.country_code != "US" && opt.country_code != "CA" && opt.country_code != "GB") {
			$(opt.state_select_id).hide();
			$(opt.state_text_id).show();
			$(opt.state_text_id).val("");
		} else {
		//Now we need to grab the correct state/prov info
			$.post(opt.home_url+'/platemaking/includes/register.php?targetAction=getstates&country='+ opt.country_code, function(data){
				data = '<option value="">------------------------</options> '+data;
				$(opt.state_select_id).html(data);
							
			});
			$(opt.state_select_id).show();
			$(opt.state_text_id).val("");
			$(opt.state_text_id).hide();
		}
		return false;
	}
	/*updateStateInfo : function (opt) {
		var state = $(this).val();
	
		if(state != "other"){
		$("#state").val(state);
		$("#state_dd").show();
		$("#alt_state").hide();
		}else{
		$("#state_dd").hide();
		$("#alt_state").val("");
		$("#alt_state").show();
		}
		return false;
	}*/
	
}



