/*  
 Author: Chelsea Fenton 
 Date  : 20090521
  
 Purpose: Tools for use with the bulk quote pages on the alfa.com website 
*/
jQuery(document).ready(function () {
    capitalizeDrop('statedrop');
    capitalizeDrop('statedrop_s');

	// KAB 20100217 - added default ajax settings so cache=false is forced
    jQuery.ajaxSetup({
        type: "GET",
        cache: false
    });
	

    // set up the change/blur events that update UOM, Qty and notes
    setupEvents();


});

// this function sets up the onchange/blur events; useful to have them in a function in case you need to run them again
function setupEvents() {

    jQuery(".QTY").blur(function () {
        var that = this;
        var thatval = jQuery(that).val();
        var thatname = jQuery(that).attr("name");
        thatname = thatname.substr(3, 6);
        var theline = jQuery(that).attr("id");
        theline = theline.substr(1, 3);
        
        jQuery.get("gb100w.pgm", {task: "BULKQTY", DSSTK: thatname, QTY: thatval, BTLIN: theline} );
    });
    
    jQuery(".UOM").change(function () {
        var that = this;
        var thatval = jQuery(that).val();
        var thatname = jQuery(that).attr("name");
        thatname = thatname.substr(3, 6);
        var theline = jQuery(that).attr("id");
        theline = theline.substr(1, 3);
        
        jQuery.get("gb100w.pgm", {task: "BULKQTY", DSSTK: thatname, UOM: thatval, BTLIN: theline} );
    });
    
    jQuery(".notes").blur(function () {
        var that = this;
        var thatval = jQuery(that).val();
        var thatname = jQuery(that).attr("name");
        thatname = thatname.substr(5, 6);
        var theline = jQuery(that).attr("id");
        theline = theline.substr(1, 3);
        
        jQuery.get("gb100w.pgm", {task: "BULKQTY", DSSTK: thatname, BTNOTE: thatval, BTLIN: theline} );
    });
        
}


String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};

// Function name: getcounty
// Purpose: determines weather the county should be displayed
// Parms:
//        countryid - id of the country drop down
//      displayid - id of the row containing the county input
function getcounty(countryid, displayid, state) {    
    var country = jQuery('#' + countryid).val();
    
    
    if (country != "GB") {
        if (state == "state") {
            jQuery('#countyreq_s').html('<span class="msg">* </span>');
        }  else {
            jQuery('#countyreq').html('<span class="msg">* </span>');
        }
        
    } else {    
        if (state == "state") {
            jQuery('#countyreq_s').html('');
        } else {
            jQuery('#countyreq').html('');
        }
    }
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        type: "GET",
        url: "gb100w.pgm",
        data: {
            task: 'GETCOUNTY',
            country: country
        },           
        success: function (msg) {
            jQuery('#'+displayid).css('display', msg);
            if (msg == "") {
                if (state == "state") {
                    jQuery('#statedisp_s').css('display', 'none');
                    jQuery('#statedrop_s').val('');
                    jQuery('#state_s').val('');
                    
                } else {
                    jQuery('#statedisp').css('display', 'none');
                    jQuery('#statedrop').val('');
                    jQuery('#state').val('');
                }
                
            } else {
                if (state == "state") {
                    jQuery('#statedisp_s').css('display', '');
                    jQuery('#county_s').val('');
                    
                } else {
                    jQuery('#statedisp').css('display', '');
                    jQuery('#county').val('');
                }
            }
            
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
//            alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });                
    
}

// Function name: changestatedrop
// Purpose: when the country is changed get new state dop down list / or text input
// Parms:
//        state - the state to be selected
//      countryid - the id of the country drop down
//      statedopid - id of the state drop down
//      stateid - if of the plain text state input
function changestatedrop(state, countryid, statedopid, stateid) {
    var country = jQuery('#'+countryid).val();
    
    if (country == "CA" || country == "US") {

		// ajax call to get drop down box
		// KAB 20100217 - changed type from POST to GET for performance improvement
       jQuery.ajax({
            type: "GET",
            url: "gb100w.pgm",
            data: {
                task: 'dropstate',
                country: country
            },           
            success: function (msg) {
                jQuery('#'+statedopid).html(msg);
               
                capitalizeDrop(statedopid);
                
                jQuery('#'+statedopid).css('display', '');
                jQuery('#'+statedopid).attr('disabled', '');
                
                jQuery('#'+stateid).css('display', 'none');
                jQuery('#'+stateid).attr('disabled', 'disabled');
                
                if (state != "") {
                    jQuery('#'+statedopid).val(state);
                }
                
                jQuery('#'+statedopid);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
            }
        });
        
    } else {
        jQuery('#'+statedopid).css('display', 'none');
        jQuery('#'+statedopid).attr('disabled', 'disabled');
        
        jQuery('#'+stateid).css('display', '');
        jQuery('#'+stateid).attr('disabled', '');
        jQuery('#'+stateid).val();
        
        jQuery('#'+stateid);
    }         
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        type: "GET",
        url: "gb100w.pgm",
        cache: false,
        data:"task=staterequire&country=" + country,
        success: function (data) {
            jQuery('.staterequired').removeClass("hideit");
            jQuery('.staterequired').addClass(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}

// Function name: submitform
// Purpose: Perform error checking and submit the form data
function submitform() {
    jQuery('#task').val('submit');
    
    var data = "";
    data = xl_BuildURLWithFormElements("bulkquote", data, false);
    data = data.substr(1, data.length - 1);

	// KAB 20100217 - changed type from POST to GET for performance improvement
	jQuery.ajax({
        url: "gb100w.pgm",
        type: "GET",
        dataType: "json",
        data: data,
        cache: false,
        success: function (rtnmsg) {
            
            if (rtnmsg.valid == "T") {
                window.location = rtnmsg.redirect;
                
            } else {            
                var msg = "";
                var key = "";
                var valid = "T";
                //DK rewritten this part to avoid the same code 25 times!
                for (key in rtnmsg) {
                    if (key != "valid" && key != "redirect" && key != "bulkname") {
                        if (rtnmsg[key]["msg"] != "") {
                            jQuery(rtnmsg[key]["fieldid"]).addClass('error');
                            msg+= rtnmsg[key]["msg"] + "<br />";
                            valid = "F";
                            
                        } else {
                            jQuery(rtnmsg[key]["fieldid"]).removeClass('error');
                        }                        
                    }
                }
                
                jQuery('.QTY').each(function () {
                    if (jQuery(this).val() == "") {
                        jQuery(this).addClass('error'); 
                    } else {
                        jQuery(this).removeClass('error');
                    }
                });
                jQuery('.UOM').each(function () {
                    if (jQuery(this).val() == "") {
                        jQuery(this).addClass('error'); 
                    } else {
                        jQuery(this).removeClass('error');
                    }
                });
                jQuery("#bulkmsg").html(msg);
                tran_SwitchLang(curLang, "#bulkmsg");
                window.scrollTo(0, 0);
                contentheight();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });           
}

// Function name: savequote
// Purpose: Perform error checking and save the quote
function savequote(clear) {                        
    if (typeof clear === "undefined") {
        clear = false;
    }
    
    jQuery('#task').val('save'); 
    
    var data = "";
    data = xl_BuildURLWithFormElements("bulkquote", data, false);
    data = data.substr(1,data.length-1);
    
    data+= "&clearcart=" + clear;
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        url: "gb100w.pgm",
        type: "GET",
        dataType: "json",
        data: data,
        cache: false,
        success: function (rtnmsg) {
            var msg, key, valid;
            if (rtnmsg.valid == "T")
            {
                window.location = rtnmsg.redirect;
            }
            else
            {        
                if (rtnmsg.bulkname != "")
                {
                    msg = rtnmsg.bulkname;
                    msg+= "<br /><input type=\"image\" src=\"images/Yes.gif\" alt=\"Yes\" onclick=\"savequote(true);\" alttxt=\"yesbtn\" /> ";
                    msg+= "<span lang=\"Y\" key=\"Yes\" class=\"hideit yesbtn\">Yes</span>";
                    msg+= "<input type=\"image\" src=\"images/No.gif\" alt=\"No\" onclick=\"disablePopup();\" alttxt=\"nobtn\" />";
                    msg+= "<span lang=\"Y\" key=\"No\" class=\"hideit nobtn\">No</span>";
                    
                    loadPopup(msg);
                }
                else
                {
                    disablePopup();
                    msg = "";
                    //DK rewritten this part to avoid the same code 25 times!
                    for (key in rtnmsg)
                    {
                        if (key != "valid" && key != "redirect" && key != "bulkname")
                        {
                            if (rtnmsg[key]["msg"] != "")
                            {
                                jQuery(rtnmsg[key]["fieldid"]).addClass('error');
                                msg+= rtnmsg[key]["msg"] + "<br />";
                                valid = "F";
                            }
                            else
                            {
                                jQuery(rtnmsg[key]["fieldid"]).removeClass('error');
                            }
                        }
                    }
                    
                    jQuery('.QTY').each(function () {
                        if (jQuery(this).val() == "")
                        {
                            jQuery(this).addClass('error'); 
                        }
                        else
                        {
                            jQuery(this).removeClass('error');
                        }
                    });
                    jQuery('.UOM').each(function () {
                        if (jQuery(this).val() == "")
                        {
                            jQuery(this).addClass('error'); 
                        }
                        else
                        {
                            jQuery(this).removeClass('error');
                        }
                    });        
                    
                    jQuery("#bulkmsg").html(msg);
                    tran_SwitchLang(curLang , "#bulkmsg");
                    window.scrollTo(0, 0);
                    contentheight();
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}

// Function name: addcustom
// Purpose: Take the user to the add custom item screen
function addcustom(rrn) {
    var type;
    if (typeof rrn == "undefined") {
        rrn = 0;
    }
    
    rrn = parseInt(rrn, 10);
    
    type = jQuery('#custom_item').val();
    if (type == "Custom Pt Labware") {
        window.location = "gp150w.pgm?rrn=" + rrn;
    } else {
        window.location = "gb110w.pgm?type=" + type + "&rrn=" + rrn;
    }
}


// Function name: addcustom
// Purpose: populate address fields with profile address
function usercontaddr() {    
    // if the checkbox has been checked
    if (jQuery('#use_cont_addr').attr('checked'))
    {        
        // get stored profile address
        var company = jQuery('#company').val();
        var addr2 = jQuery('#address2').val();
        var addr1 = jQuery('#address1').val();
        var city = jQuery('#city').val();
        var state = jQuery('#state').val();
        var zip = jQuery('#zip').val();
        var country = jQuery('#country').val();
        var county = jQuery('#county').val();
        
        
        // populate fields
        jQuery('#company_s').val(company);
        jQuery('#attention_s').val("");
        jQuery('#address1_s').val(addr1);
        jQuery('#address2_s').val(addr2);
        jQuery('#city_s').val(city);        
        jQuery('#zip_s').val(zip);
        jQuery('#country_s').val(country);        
        jQuery('#state_s').val(state);
        jQuery('#county_s').val(county);        
        
        changestatedrop(state,'country_s','statedrop_s','state_s');
        
        jQuery('#popship').val('');
    }    
    else
    {
        // populate fields
        jQuery('#company_s').val('');
        jQuery('#attention_s').val("");
        jQuery('#address1_s').val('');
        jQuery('#address2_s').val('');
        jQuery('#city_s').val('');
        jQuery('#zip_s').val('');
        jQuery('#country_s').val('');
        jQuery('#state_s').val('');
        jQuery('#county_s').val('');
        
        changestatedrop('','country_s','statedrop_s','state_s');
        
        jQuery('#popship').val('');        
    }        
}

function addbulklab(type, stock) {
    //qty = jQuery('#quantity').val();
    //metal = jQuery('#metal').val();    
    //var data = "task=addcustomlab&quantity="+qty+"&metal="+metal+"&stock="+stock;
    
    var data = "";
    data = xl_BuildURLWithFormElements("customlab", data, false);
    data = data.substr(1,data.length-1);
    
    
    ajaxaddbulk(data, type, stock, "customlab");
}

function addbulklablid(type, stock) {
    var data = "";
    data = xl_BuildURLWithFormElements("customlablid", data, false);
    data = data.substr(1, data.length - 1);
    
    jQuery("#quantity_lid").val("");
    
    ajaxaddbulk(data, type, stock, "customlablid");
}

function ajaxaddbulk(data, type, stock, formid) {
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        url: "gb110w.pgm",
        type: "GET",
        dataType: "json",
        data: data,
        cache: false,        
        success: function (rtnmsg) {
            if (rtnmsg.valid == "T") {                
                //window.location = "gb100W.pgm";
                if (jQuery("#quantity_lid").val() > 0) {
                    stock = jQuery('#customlablid input[name="stock"]').val();
                    addbulklablid(type, stock);

                } else {
                    getminibulk();
                    getbulkitems();
                }
            } else {    
                var field = "";
                if (formid == "customlablid") {
                    field="_lid";
                }
                
                if (formid == "customlab") {
                    if (jQuery("#quantity_lid").val() > 0) {
                        jQuery('#metal').removeClass('error');
                        jQuery('#quantity').removeClass('error'); 
                        stock = jQuery('#customlablid input[name="stock"]').val();
                        addbulklablid(type, stock);
                        
                    } else {
                        checkfields(field, rtnmsg);
                    }
                } else {
                    checkfields(field, rtnmsg);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });    
}

function checkfields(field, rtnmsg) {
    var valid;
    if (rtnmsg.BTQTY != "") {
        jQuery('#quantity' + field).addClass('error'); 
        valid = "F"; 
    } else {    
        jQuery('#quantity' + field).removeClass('error'); 
    }
    if (rtnmsg.BTMTL != "") { 
        jQuery('#metal' + field).addClass('error'); 
        valid = "F"; 
    } else {    
        jQuery('#metal' + field).removeClass('error'); 
    }
}

// Function name: submitcustom
// Purpose: do error checking and allow form submision of custom item
function submitcustom(type) {    
    var data = "";
    data = xl_BuildURLWithFormElements("bulkquotecust", data, false);
    data = data.substr(1, data.length - 1);
    data = data + "&submittype=" + type;

	// KAB 20100217 - changed type from POST to GET for performance improvement
	jQuery.ajax({
        url: "gb110w.pgm",
        type: "GET",
        dataType: "json",
        data: data,
        cache: false,
        success: function (rtnmsg) {
            var key;
            jQuery("#errmsgs").css("color", "").html("");
            if (rtnmsg.valid == "T") {
                window.location = "gb100W.pgm";
            } else {                    
                //DK rewritten whole part to avoid unnecessary duplicated code
                jQuery("input").removeClass("error");
                jQuery("select").parent("span").removeClass("error");
                
                var msg = "";
                
                for (key in rtnmsg) {
                    if (key != "valid") {
                        msg += rtnmsg[key] + "<br />";
                        if (key.substr(0, 3) != "UOM" || jQuery("#" + key).attr("type") == "text") {
                            jQuery("#" + key).addClass("error");
                            
                        } else {
                            jQuery("#" + key).parent(".dropborder").addClass("error");
                        }
                        jQuery('input[name="' + key + '"]').addClass("error");
                        jQuery('select[name="' + key + '"]').parent(".dropborder").addClass("error");
                    }
                }
                // JEL 20091116
                jQuery("#errmsgs").css({"color": "#FF0000", "margin-left": "40px"}).html(msg);
                tran_SwitchLang(curLang , "#errmsgs");
                window.scrollTo(0, 0); 
                
                /*
                if (type == "customlab")
                {
                    if (rtnmsg.BTDESC != "") { jQuery('#description').addClass('error'); valid = "F"; }
                    else {    jQuery('#description').removeClass('error'); }
                    
                    if (rtnmsg.BTQTY != "") { jQuery('#quantity').addClass('error'); valid = "F"; }
                    else {    jQuery('#quantity').removeClass('error'); }
                    
                    if (rtnmsg.CATTYPE != "") { jQuery('#type').addClass('error'); valid = "F"; }
                    else {    jQuery('#type').removeClass('error'); }
                    
                    if (rtnmsg.CATEGORY != "") { jQuery('#category').addClass('error'); valid = "F"; }
                    else {    jQuery('#category').removeClass('error'); }
                    
                    if (rtnmsg.BTMTL != "") { jQuery('#metal').addClass('error'); valid = "F"; }
                    else {    jQuery('#metal').removeClass('error'); }
                    
                }
                else
                {                
                    numuom = parseInt(jQuery('#numuom').val(), 10);
                    x = 1;
                    while (x <= numuom)
                    {
                        if (rtnmsg["BTSIZ"+x] && rtnmsg["BTSIZ"+x] != "") {jQuery('#UOM'+x).addClass('error');}
                        else{jQuery('#UOM'+x).removeClass('error');}
                        
                        if (rtnmsg["BTQTY"+x] && rtnmsg["BTQTY"+x] != "") {jQuery('#quantity'+x).addClass('error');}
                        else{jQuery('#quantity'+x).removeClass('error');}
                        
                        x++;    
                    }
                    
                    if (rtnmsg.BTDESC != "") { jQuery('#description').addClass('error'); valid = "F"; }
                    else {    jQuery('#description').removeClass('error'); }
                    
                    if (rtnmsg.BTDDTE != "") { jQuery('#delivery').addClass('error'); valid = "F"; }
                    else {    jQuery('#delivery').removeClass('error'); }
                    
                }
                */
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
//            alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}

// Function name: deletecust
// Purpose: delete a custom item
/*function deletecust(seqno, rrn, line) {
    if (typeof rrn == "undefined") {
        rrn = 0;
    }
    
    if (typeof line == "undefined") {
        line = 0;
    }
    
    rrn = parseInt(rrn, 10);
    line = parseInt(line, 10);
    
    var sequence = seqno;
    jQuery.ajax({
        type: "POST",
        url: "gb100w.pgm",
        data: {
            task: 'deletecust',
            seqno: sequence,
            rrn: rrn,
            line: line
        },       
        success: function (msg) {
            window.location = "GB100W.pgm";
            //id = ".custom"+sequence;
            //jQuery(id).css('display','none');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}
*/

// allow for adding more of the same item to a bulk order
function add_more(dsstk, line) {
	
	jQuery.ajax({
		url: "gb100w.pgm",
		type: "GET",
		cache: false,
		data: "task=addexbulk&dsstk=" + dsstk,
		success: function (msg) {
			
			jQuery("[name=LINE"+parseInt(line, 10)+"]").parents("tr").next().after(msg);            
            getminibulk();
            getbulkitems();
            setupEvents();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
	});
}

// Function name: deleteitem
// Purpose: delete a regular item
function deleteitem(itemno, rrn, line) {
    jQuery("body").css("cursor", "wait");
    if (typeof rrn == "undefined" || rrn === "") {
        rrn = 0;
    }
    
    if (typeof line == "undefined") {
        line = 0;
    }
    
    rrn = parseInt(rrn, 10);
    line = parseInt(line, 10);
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        type: "GET",
        url: "gb100w.pgm",
        data: {
            task: 'deleteitem',
            rrn: rrn, 
            DSSTK: itemno,
            BTLIN: line
        },       
        success: function (msg) {
            window.location = "GB100W.pgm";
            //id = ".item"+seqno;                
            //jQuery(id).css('display','none');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
            jQuery("body").css("cursor", "auto");
        }
    });
}

// Function name: editcust
// Purpose: take the user to the page to edit a custom item
function editcust(line, type, rrn) {
    if (typeof rrn == "undefined" || rrn === "") {
        rrn = 0;
    }
    
    rrn = parseInt(rrn, 10);
    line = parseInt(line, 10);
    
    if (type == "customlab") {
        window.location.href = "gb110w.pgm?task=edit&type=customlab&BTLIN=" + line + "&rrn=" + rrn;    
    } else {
        window.location.href = "gb110w.pgm?task=edit&BTLIN=" + line + "&rrn=" + rrn + "&type=" + type;    
    }
}

function setheight() {
    jQuery('#container').css('height','');
}

function deletesaved(rrn, clear) {
    if (typeof clear === "undefined") {
        clear = false;
    }
    
    if (clear === false) {
        var msg = "<span lang=\"Y\" key=\"confirm_delete_bulk\">Are you sure you want to delete this Bulk Quote?</span>";
        msg+= "<br /><input type=\"image\" src=\"images/Yes.gif\" alt=\"Yes\" onclick=\"deletesaved(" + rrn + ", true);\" alttxt=\"yesbtn\" /> ";
        msg+= "<span lang=\"Y\" key=\"Yes\" class=\"hideit yesbtn\">Yes</span>";
        msg+= "<input type=\"image\" src=\"images/No.gif\" alt=\"No\" onclick=\"disablePopup();\" alttxt=\"nobtn\" />";
        msg+= "<span lang=\"Y\" key=\"No\" class=\"hideit nobtn\">No</span>";
        
        loadPopup(msg);
    } else {
        disablePopup();

		// KAB 20100217 - changed type from POST to GET for performance improvement
		jQuery.ajax({
            type: "GET",
            url: "gb120w.pgm",
            data: {
                task: 'deletesaved',
                rrn: rrn
            },       
            success: function (msg) {
                var id = "#saved"+rrn;
                jQuery(id).css('display','none');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
            }
        });    
    }    
}

function editsaved(rrn) {
    window.location = "gb100W.pgm?task=editsaved&rrn="+rrn;
}

function viewsaved(rrn) {
    window.location = "gb100W.pgm?task=viewsaved&rrn="+rrn;
}

function viewcustsaved(quotenum, linenum, rrn) {
    window.location = "gb110W.pgm?task=viewcustsaved&quote="+quotenum+"&line="+linenum+"&rrn="+rrn;
}

function repeatsaved(rrn) {
    window.location = "gb100W.pgm?task=repeatsaved&rrn="+rrn;
}

function addsavequote() {
    var quote = jQuery('#savedquote').val();
    jQuery('#task').val('addsavedquote');
    jQuery('#quote').val(quote);
    
    var data = "";
    data = xl_BuildURLWithFormElements("bulkquote", data, false);
    data = data.substr(1,data.length-1);

	// KAB 20100217 - changed type from POST to GET for performance improvement	
	jQuery.ajax({
        url: "gb100w.pgm",
        type: "GET",
        dataType: "json",
        data: data,
        cache: false,
        success: function (rtnmsg) {
            if (rtnmsg.valid == "T") {
                window.location = rtnmsg.redirect;
            } else {
                
                jQuery('.QTY').each(function () {
                    if (jQuery(this).val() == "") {
                        jQuery(this).addClass('error'); 
                    } else {
                        jQuery(this).removeClass('error');
                    }
                });
                jQuery('.UOM').each(function () {
                    if (jQuery(this).val() == "") {
                        jQuery(this).addClass('error'); 
                    } else {
                        jQuery(this).removeClass('error');
                    }
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}

function populateship() {
    var value = jQuery('#popship').val();
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        type: "GET",
        url: "gb100w.pgm",       
        data: {
            task: 'populateship',
            seqno: value
        },       
        success: function (msg) {
            // Create the JSON response as a javascript object
            var responseObj = eval('(' + msg + ')');
            
            jQuery('#company_s').val(responseObj.BHSCO);
            jQuery('#attention_s').val(responseObj.BHSAN);
            jQuery('#address1_s').val(responseObj.BHSA1);
            jQuery('#address2_s').val(responseObj.BHSA2);
            jQuery('#city_s').val(responseObj.BHSCI);
            jQuery('#county_s').val(responseObj.BHSCN);
            jQuery('#zip_s').val(responseObj.BHSZP);
            jQuery('#country_s').val(responseObj.BHSCY);
            jQuery('#state_s').val(responseObj.BHSST);
            changestatedrop(responseObj.BHSST,'country_s','statedrop_s','state_s');
            
            jQuery('#use_cont_addr').attr('checked',false);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}

function addmoreUOM() {
    var numuom = parseInt(jQuery('#numuom').val(), 10);
    numuom = numuom + 1;
    jQuery('#numuom').val(numuom);
    
    var elem = jQuery('.dubrow:last').clone();
    elem.find("select").attr("id", "UOM" + numuom);
    elem.find("input").attr("id", "quantity" + numuom);
    
    jQuery(".dubrow:last").children(".plus").html("");
    
    jQuery('#uomqtytbl').append(elem);
    
    jQuery('select[name="BTSIZ"]').unbind("change").bind("change", function () {
        dspinput(this);
    });
    
    contentheight();
}

function getcategory() {
    var type = jQuery('#type').val();
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        type: "GET",
        url: "gb110w.pgm",
        data: {
            task: 'getcategory',
            type: type
        },       
        success: function (msg) {
            jQuery('#category').html(msg);
            jQuery('#description').html("");
            jQuery('#attributes').slideUp("fast", function () {
                contentheight();
            });
            jQuery('#attributes').html("");
            
            jQuery('#type').removeClass('error');
            jQuery('#category').removeClass('error');
            jQuery('#description').removeClass('error');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}

function getdescription() {
    var category = jQuery('#category').val();
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        type: "GET",
        url: "gb110w.pgm",
        data: {
            task: 'getdescription',
            category: category
        },       
        success: function (msg) {
            jQuery('#description').html(msg);
            
            jQuery('#type').removeClass('error');
            jQuery('#category').removeClass('error');
            jQuery('#description').removeClass('error');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
//            alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });    
}

function getattributes() {
    jQuery('#attributes').slideUp("fast", function () {
        contentheight();
    });
    
    var type = jQuery('#type').val();
    var category = jQuery('#category').val();
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    if (category != "") {    
        jQuery.ajax({
            type: "GET",
            url: "gb110w.pgm",
            data: {
                task: 'getattributes',
                category: category,
                type: type
            },       
            success: function (msg) {
                jQuery('#attributes').html(msg);                
                tran_SwitchLang(curLang , "#attributes");                
                jQuery('#attributes').slideDown("slow", function () {
                    contentheight();
                });

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
            }
        });
    } else {
        jQuery('#attributes').slideUp("fast", function () {
            contentheight();
        });
        jQuery('#attributes').html("");
    }
}

function bulkquote(rrn) {
    rrn = parseInt(rrn, 10);
    if (rrn > 0) {
        
        jQuery(".QTY, .UOM, .notes").blur(function () {
            var row = jQuery(this).parents("tr").attr("class");
            var qty = jQuery("." + row + " .QTY").val();
            var uom = jQuery("." + row + " .UOM").val();
            var item, data;
            
            if (qty !== "" && uom !== "" && typeof qty !== "undefined" && typeof uom !== "undefined") {
                item = row.replace(/item/g, "");
                data = "task=updateitem&rrn=" + rrn + "&seq=" + item;
                
                data += "&qty=" + qty;
                data += "&uom=" + uom;
                data += "&notes=" + jQuery("." + row).find(".notes").val();
                data += "&line=" + jQuery("." + row).find(".line").val();
                
                jQuery.ajax({
                    url: "gb100w.pgm",
                    data: data,
                    cache: false,
                    success: function (msg) {
                        if (msg == "0") {
                            jQuery("#bulkmsg").html("<span lang=\"Y\" key=\"product_updated\">Product has been updated.</span>");
                            timermsg = window.setTimeout("hidemsgbox()", 5000);
                            tran_SwitchLang(curLang , "#bulkmsg");
                            window.scrollTo(0, 0);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
                    }
                });
            }
        });
    }
}

function hidemsgbox() {
    window.clearTimeout(timermsg);
    jQuery("#bulkmsg").html("");
}

function addcustombulk() {
    
    jQuery("#btndrawtool").click(function () {
        var height = jQuery(window).height();
        var width = jQuery(window).width();
        
        var top = (height - 425) / 2;
        var left = (width - 450) / 2;
        
        var smiles = jQuery('input[name="BTSML"]').val();
        var possmiles = smiles.lastIndexOf(".");
        smiles = smiles.substr(0, possmiles);
        smiles = smiles.replace(/%25/g, "%");
        smiles = unescape(smiles);
        
        var port = window.location.port;
        
        if (port > 80){
            port = ":" + port;
        } else {
            port = "";
        }
        
        var url = "http://newsearch.chemexper.com/misc/hosted/alfaGlobal/structureOnDemand.shtml?returnTo=http://www.alfa.com" + port + "/" + ulang;
        if (window.location.protocol == "https:") {
            url = "https://www.chemexper.com/misc/hosted/alfaGlobal/structureOnDemand.shtml?returnTo=https://www.alfa.com" + port + "/" + ulang;
        }
        jQuery("#iframedrawing iframe").attr("src", url + "/gb110w.pgm&smiles=" + smiles);
        //jQuery("#iframedrawing iframe").attr("src", "gb110w.pgm?task=drawing&smiles=" + smiles);
        jQuery("#iframedrawing").css({
            display: "block",
            top: top,
            left: left,
            opacity:"1",
            filter:"alpha(opacity=100)"
        });
        
        var options = {
            element: "body",
            opacity: 40,
            background: true
        };
        
        backgroundoverlay(options);
    });
    
    jQuery("#iframeclose").click(function () {
        jQuery("#iframedrawing").hide(1);
        backgroundoverlayhide();
    });
    
    jQuery("select").change(function () {
        dspinput(this);
    });
    
    capitalizeDrop('form');
    capitalizeDrop("mtelementalloy select");
}

function dspinput(obj) {
    var selname = jQuery(obj).attr("name");
    var seltext = jQuery(obj).children("option:selected").text();
    seltext = jQuery.trim(seltext.toLowerCase());
    
    if (seltext === "other") {
        var pel = jQuery(obj).parent("span");
        jQuery(obj).attr("name", selname + "tmp");
        jQuery(pel).after("<input type=\"text\" name=\"" + selname + "\" />");

        } else {
        selname = selname.replace(/tmp/g, "");
        jQuery(obj).attr("name", selname);
        jQuery('input[name="' + selname + '"]').remove();
    }
}

function closedrawing(smilesurl) {
    var test = "";
    var pos = smilesurl.lastIndexOf("/");
    var smilestr = smilesurl.substr(pos + 1, smilesurl.length - pos);
    pos = smilestr.
    test = smilestr.substr(2, 1);
    //alert(smilestr.charCodeAt(2));
    jQuery("#iframedrawing, #iframebackground, #iframeoverlay").hide(1);
    jQuery("select").attr("disabled", "");
    jQuery("#smileimg .boxcontent img").attr("src", smilesurl);
    jQuery('input[name="BTSML"]').val(smilestr);
    jQuery("#smileimg").show(1);
}


function selmaterial(material) {

	// KAB 20100217 - changed type from POST to GET for performance improvement
	jQuery.ajax({
        type:"GET",
        url:"gb110w.pgm",
        data: "task=dspmaterial&material=" + material,
        cache: false,
        success: function (rtnhtml) {
            jQuery("#mtelementalloy").html(rtnhtml);
            capitalizeDrop("mtelementalloy select");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}

function selform(form, formtype) {
    //form = form.replace(/\s/g, "");
    form = form.toUpperCase();
    formtype = formtype.toUpperCase();
    
	// KAB 20100217 - changed type from POST to GET for performance improvement
    jQuery.ajax({
        type:"GET",
        url:"gb110w.pgm",
        data: "task=dspform&form=" + form + "&formtype=" + formtype,
        cache: false,
        success: function (rtnhtml) {
            jQuery("#formdetails").html("<br />" + rtnhtml);
            jQuery("select").unbind("change").bind("change", function () {
                dspinput(this);
            });
            contentheight();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("error thrown: " + XMLHttpRequest.responseText + " " + textStatus + " " + errorThrown);
        }
    });
}
