var thumbnailPath = '';
var productTabs;
var resultCropDimension = new Array();
var imageHeight;
var imageWidth;
var storeImagePath = null;
var storeHome = null;
var storeSecureHome = null;
var crop_popup = null;


function setStoreVariables( path , secureHome , home){
    storeImagePath = path;
    storeHome = home;
    storeSecureHome = secureHome;
}

function doProcessThumbnail( divId )
{
    if(document.getElementById('target_upload').contentWindow.document.getElementById('uploadfail'))
    {
        //document.getElementById('process').style.visibility='hidden';
        $('process').style.visibility='hidden';
        //popupHide('profileThumbnailUpload');
        popupHide( divId );
        alert("Uploaded file was not valid. Please use valid .jpg or .gif file to upload.");
        //popupShow('commonConfirm','userWebsite');
        return false;
    }

    if(document.getElementById('target_upload').contentWindow.document.getElementById('filePath'))
    {
        var path = document.getElementById('target_upload').contentWindow.document.getElementById('filePath').value;
        var width = document.getElementById('target_upload').contentWindow.document.getElementById('width').value;
        var height = document.getElementById('target_upload').contentWindow.document.getElementById('height').value;
        //added for activate upload button
        document.getElementById('thumbnailImg').src = path;
        //document.getElementById('thumbnailImg').height = height;
        //document.getElementById('thumbnailImg').width = width;
        document.getElementById('thumbnailImg').style.maxWidth = width+'px';
        //alert("width::"+width);
        //alert("maxwidth::"+document.getElementById('thumbnailImg').style.maxWidth);
        document.getElementById('thumbnailImg').style.maxHeight= height+'px';
        //alert("height::"+height);
        //alert("max height:::"+document.getElementById('thumbnailImg').style.maxHeight);
        document.getElementById('photoUrl').value = path;
        document.getElementById('photoUrlFullsize').value = path;
        //end
        //alert("path in doProcessThumbnail js"+path);
        document.getElementById('process').style.visibility='hidden';
        popupHide( divId );
        thumbnailPath = path;
        imageHeight = height;
        imageWidth = width;
        //setCropImage(path,width,height);
        //popupShow('cropImageArea','showCropArea');
       // crop_popup =  window.open('/open_crop_popup?path='+path+'&height='+parseInt(height)+'&width='+parseInt(width)+'&imagepath='+storeImagePath,'crop_popup','location=no,menubar=no,status=no,scrollbars=no,resizable=no,titlebar=no,toolbar=no,top=10,left=10,height='+(parseInt(height)+120)+',width='+(parseInt(width)+100)) ;
    }

}

function closeCroppingTool(divEle){
    popupHide(divEle);
}


function parseURI(uri)
{
    return encodeURIComponent(uri);
}

function submitaddthumbnail( frm )
{
    //document.getElementById('photoUrl').value = document.getElementById('uploadfile1').value;
    //alert("thumb nail url ::"+document.getElementById('photoUrl').value);
    //document.getElementById('process').style.visibility='visible';
    $('process').style.visibility='visible';
    //document.getElementById('screenwidth').value = parseInt(screen.width - 170);
    //document.getElementById('screenheight').value = parseInt(screen.height - 170);
    //document.getElementById('screenwidth').value = 854;
    //document.getElementById('screenheight').value = 598;
    //document.getElementById('screenwidth').value = 800;
    $('screenwidth').value = 800;
    //document.getElementById('screenheight').value = 600;
    $('screenheight').value = 600;

    frm.submit();
}

function loadproductImagesIframe(){
    if(document.getElementById && document.getElementById('process1')){
        //document.getElementById('process1').style.visibility='';
        $('process1').style.visibility='';
    }
    if(document.getElementById && document.getElementById('productImagesUpload'))
        popupHide('productImagesUpload');

}

function loadproductDocIframe(){
    if(document.getElementById && document.getElementById('process2')){
        //document.getElementById('process2').style.visibility='';
        $('process2').style.visibility='';
    }
    if(document.getElementById && document.getElementById('productDocUpload'))
        popupHide('productDocUpload');
}

function showWatermarkPreview(imageName,transparencyVal)
{
    //document.getElementById('process2').style.visibility='' ;
    $('process2').style.visibility='' ;
    var url ="/preview_watermarked_image?imageName="+imageName+"&transparency="+transparencyVal;
    var options = {
        method: 'get',
        onSuccess: function(t) {

            var resData = ''
            try
            {
                resData = Trim(t.responseText);
            }
            catch(e){
                alert("error : ");
            }
            if(resData.indexOf("watermark") != -1)
            {
                var data = resData.split(',');

                //document.getElementById("watemarkedPreviewImage").src = Trim(data[1]);
                $("watemarkedPreviewImage").src = Trim(data[1]);
                //document.getElementById('process2').style.visibility='hidden';
                $('process2').style.visibility='hidden';
                popupShow('watermarkedImagePreview','watermarkImage');
            }
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) {},
        onLoaded:  function(t) {}
    }
    new Ajax.Request(url,options);
}



/*
function doRequestUploadProductImages(tableId, productId){
     var options = {
        method: 'get',
        onSuccess: function(t) {


            var resData = ''
            try
            {
                resData = Trim(t.responseText);
            }
            catch(e){
                alert("error : ");
            }

            var data = resData.split(',');
            var img = new HTMLImageElement();
            img.id = data[1];
            img.scr = data[2];
            var objTABLE = document.getElementById(tableId);
            var objTBody = objTABLE.getElementsByTagName("TBODY")[0];
            var objTR_no = document.createElement("TR");
            var objTD_no = document.createElement("TD");
            objTD_no.appendChild(img);
            objTR_no.appendChild(objTD_no);
            var objTD_no = document.createElement("TD");
            objTD_no.innerHTML = "delete";
            objTR_no.appendChild(objTD_no);

            objTBody.appendChild(objTR_no);
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) {},
        onLoaded:  function(t) {}
    }
    new Ajax.Request('/add_product_images?pid='+productId,options);
}
 */

function Trim(s)
{
    // Remove leading spaces and carriage returns
    while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
    {
        s = s.substring(1,s.length);
    }
    // Remove trailing spaces and carriage returns
    while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
    {
        s = s.substring(0,s.length-1);
    }
    return s;
}

function setDefaultPath(strThumnailImagePath)
{
    if(strThumnailImagePath != "")
    {
        var path = strThumnailImagePath;
        //document.getElementById("thumbnailImg").src = path;
        $("thumbnailImg").src = path;
        //document.getElementById('process').style.visibility='hidden';
        $('process').style.visibility='hidden';
        popupHide('productThumbnailUpload');
    }

}

function sendRequestAndUpdate(url,params)
{

    var sendHttp = getXMLHttpObject();
    var parameters = '';
    if(params)
        parameters = params;
    if(sendHttp == null)
    {
        alert("Your browser is outdated");
        return;
    }
    sendHttp.onreadystatechange = function(){

        if(sendHttp.readyState == 4)
        {

            var resString = sendHttp.responseText;
            // alert(resString);
            return resString;

        }

    };
    sendHttp.open('POST', url, true);
    sendHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    sendHttp.setRequestHeader("Content-length", parameters.length);
    sendHttp.setRequestHeader("Connection", "close");
    sendHttp.send(parameters);
}
function getXMLHttpObject()
{
    var xmlHttp = null;
    try
    {
        xmlHttp = new XMLHttpRequest();
    }
    catch(e)
    {
        try
        {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

    }

    return xmlHttp;

}

function isEmail(address) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(address) ;
}


// isIntegerInRange (STRING s, INTEGER a, INTEGER b)
function isIntegerInRange (s, a, b)
{   if (isEmpty(s))
    if (isIntegerInRange.arguments.length == 1) return false;
    else return (isIntegerInRange.arguments[1] == true);

// Catch non-integer strings to avoid creating a NaN below,
// which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

function isInteger (ele)
{
    var i;
    var s = ele.value;

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    return true;
}

function isEmpty(s)
{
    return ((s == null) || (s.length == 0))
}

function isDigit (c)
{
    return ((c >= "0") && (c <= "9"))
}

function isFloat(ele){
    if(isNaN(ele.value*2)){
        return false;
    }
}

function goodchars(e, goods)
{
    return goodchars(e, goods, null);
}
function goodchars(e, goods, ele)
{
    var key, keychar;
    key = getkey(e);

    if (key == null) return true;

    if(ele != null && key==46){
        if (ele.value.indexOf('.') != -1)
            return false;
    }

    // get character
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();
    goods = goods.toLowerCase();

    // check goodkeys
    if (goods.indexOf(keychar) != -1)
        return true;

    // control keys
    if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
        return true;

    // else return false
    return false;
}

function getkey(e)
{
    if (window.event)
        return window.event.keyCode;
    else if (e)
        return e.which;
    else
        return null;
}

//////////////////////////////////////////////////////////...


function createRequestObject() {
    var req;

    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    } catch (e) {
        //alert("Permission UniversalBrowserRead denied.");
    }

    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        if(req.overrideMimeType) {
            req.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!req) {
        alert("couldn't connect");
        return false;
    }

    return req;
}

function showCart(cartDivId){

    setLoadingBlack(document.getElementById(cartDivId));
    new Ajax.Updater(cartDivId,'/cart?response_type=show_cart',{
        evalScripts:true,
        onComplete:function(){

        }
    });
}

function hideCart(cartDivId){
    document.getElementById(cartDivId).innerHTML ="";
}

function addToCart(cartDivId,pn,varId,divLoading){
    if( document.getElementById(divLoading))
        setLoading($(divLoading));
    pn = parseURI(pn);
    var qty = 1;
    var url = '/cart?addtocart=yes&buy_' + pn + '=yes&qty_' + pn + '=' + qty + '&response_type=refresh_cart&var_id='+varId;

    new Ajax.Updater('shopping_cart',url,{
        evalScripts:true,
        onComplete:function(){
            if( document.getElementById(divLoading)){
                //document.getElementById(divLoading).innerHTML = "(Added to cart)";
                $(divLoading).innerHTML = "(Added to cart)";
             }
            if( document.getElementById('cart_items')){
                //document.getElementById('cart_items').innerHTML = $('numberOfItems').value;
                $('cart_items').innerHTML = $('numberOfItems').value;
            }
            if( document.getElementById('div_subtotal')){
                //document.getElementById('div_subtotal').innerHTML = $('subTotal').value;
                $('div_subtotal').innerHTML = $('subTotal').value;
            }
        }
    });

}

function changeQuoteUpdateSubtotal() {
    var inputName  = '';
    var totalItems = ($('numOfItems').value)/1;
    var subtotal   = 0;
    for (var i=1; i<=totalItems; i++) {
        inputName = 'item' + i;
        if ($(inputName)) {
            //search for qty_ and itemprice_
            var itemID = $(inputName).value;
            var qtyName = "qty_" + itemID;
            var itempriceName = "itemprice_" + itemID;
            var qty = ($(qtyName).value)/1;
            var price = ($(itempriceName).value);
            price = price.replace(/,/g,"");
            price = (price)/1;
            subtotal = (subtotal)/1 + (qty * price);
            }
    }
        //$('div_subtotal').innerHTML = '$' + subtotal.toFixed(2);
    $('div_subtotal').innerHTML = formatCurrency(subtotal.toFixed(2));
}

//courtesy http://www7.ewebcity.com/cyanide7
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,"");
    if (isNaN(num))
        num = "0";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    var cents = num%100;
    num = Math.floor(num/100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
        num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
    }
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function addItemToCart(pn,varId){

    pn = parseURI(pn);
    var qty = 1;
    if(document.getElementById && document.getElementById('cartItem_qty')){
       //qty = document.getElementById('cartItem_qty').value;
        qty = $('cartItem_qty').value;
    }

    if(qty == "") qty=1;

    var url = '/cart?addtocart=yes&buy_' + pn + '=yes&qty_' + pn + '=' + qty + '&var_id='+varId;

    new Ajax.Request(url,
    {
        method:'get',
        onSuccess: function(transport){
            location = storeHome+'/view_cart';
        },
        onFailure: function(){
            alert('Something went wrong...') ;
        }
    });

}


function refreshCart(){

    new Ajax.Updater('shopping_cart','/refresh_cart',{
        evalScripts:true,
        onComplete:function(){
            if( $('cart_items'))
                $('cart_items').innerHTML = $('numberOfItems').value;
        }
    });

}

function updateCart(itemList, isFromViewCart, loadanimation, to_delete){

    var s = "";
    //var quoteId = document.getElementById('quote_id').value ;
    var quoteId = $('quote_id').value ;
    var shipMethodId = "1"; //document.getElementById('ship_method_id').options[document.getElementById('ship_method_id').selectedIndex].value;
    if( itemList != '' )
    {
        var itemArray = itemList.split(",");
        for(var i=0; i < itemArray.length; i++) {
            var item = itemArray[i].split("^");

            s = s + '&mod_' + item[0]+'_'+item[1] + '=yes&qty_' + item[0]+'_'+item[1] + '=' + document.getElementById(item[0]+'_'+item[1] ).value;

        }
    }

    if(isFromViewCart)
        s = s + "&isFromViewCart=true";

    if(to_delete)
        s = s + "&to_delete=true";

    setLoadingSmall($(loadanimation));

    new Ajax.Updater('shopping_cart','/cart?edit_quote=yes&quote_id=' + quoteId + '&addtocart=no' + s + '&ship_method_id=' + shipMethodId + '&response_type=refresh_cart',{
        evalScripts:true,
        onComplete:function(){

            if( $('cart_items'))
                $('cart_items').innerHTML = $('numberOfItems').value;
            if( $('div_subtotal'))
                $('div_subtotal').innerHTML = "Subtotal: " + $('subTotal').value;

        }
    });
}

function addRelatedProductToCart(pn,varId){

    var qty = 1;
    eval( 'document.getElementById("sb_'+pn+'").style.display = "block"');

    var requestString = '/cart?addtocart=yes&buy_' + pn + '=yes&qty_' + pn + '=' + qty + '&response_type=show_cart&var_id='+varId;
    var http = createRequestObject();
    http.open('get', requestString);
    http.onreadystatechange = function(){
        eval( 'document.getElementById("sb_'+pn+'").style.display = "none"');
        eval( 'document.getElementById("sa_'+pn+'").style.display = "block"');
    };
    http.send(null);

}

function submitQuote(){

    var emailAddress = document.request_quote.email.value;
    if(!isEmail(emailAddress))
    {
        alert("Invalid email");
        document.request_quote.email.focus();
    }
    else{
        document.request_quote.page_url.value = window.document.location.href;
        // if(Control.Modal.current)
        //    Control.Modal.current.close();
        document.request_quote.submit();
    }

}

function submitQuoteRequest1(){
    var emailAddress = document.quote_form1.email.value;
    var fullName = document.quote_form1.full_name.value;

    var companyRole = document.quote_form1.company_role.value;
    var phone = document.quote_form1.phone.value;


    if(!isEmail(emailAddress))
    {
        alert("Invalid email");
        document.quote_form1.email.focus();
        return false;
    }
    else if( Trim(fullName).length == 0) {
        alert("Name field is Blank");
        document.quote_form1.full_name.focus();
        return false;
    }
    else if( Trim(companyRole).length == 0) {
        alert("Company Role field is Blank");
        document.quote_form1.company_role.focus();
        return false;
    }
    else if( Trim(phone).length == 0) {
        alert("Phone No. is Blank");
        document.quote_form1.phone.focus();
        return false;
    }
    else{

        var s = document.quote_form1.jcaptcha_validate.value;
       // alert(">>>>>> s  :: "+ s);
        new Ajax.Request('/validateCaptcha?s='+s, {
            onComplete : function(t){

                var result = t.responseText;
                //alert(">>>>>> result "+ result);
                if(result.indexOf("true") == -1){
                       $('captcha_error-message1').style.display = "block";
                } else {
                        $('captcha_error-message1').style.display = "none";
                     sendQuoteRequestMail1();
                }

               $('captcha_iframe1').src = '/jcaptcha.go';
            }

        });



    }

}

function sendQuoteRequestMail(){
     $('quote_form').submit();
     /*lgbox_hide();
     new Ajax.Request('/sent_quote_request', {
            onComplete : function(t){

                //alert("request send");


            },
            parameters: $('quote_form').serialize(true)
        });
    */
}


function sendQuoteRequestMail1(){
     new Ajax.Request('/sent_quote_request', {
            onComplete : function(t){

                alert("request send");

            },
            parameters: $('quote_form1').serialize(true)
        });
}



function submitFAQ(){
    var emailAddress = $('c_e_mail').value;
    var name = $('c_name').value;
    var question = $('c_question').value;
    if(!isEmail(emailAddress))
    {
        alert("Invalid email");
        emailAddress.focus();
        return false;
    }
    else if( Trim(name).length == 0) {
        alert("Name field is Blank");
        name.focus();
        return false;
    }
    else if( Trim(question).length == 0) {
        alert("Question field is Blank");
        question.focus();
        return false;
    }

    lgbox_hide();

    new Ajax.Request('/ask_question', {
        onComplete : function(t){



        },
        parameters: $('question_form').serialize(true)
    });


}
function onFocusNotes()
{
    var textDescription = document.quote_form.description.value;
    if(textDescription == "Add some notes here"){
        document.quote_form.description.value = "";
    }
}

function onBlurNotes(){
    var textDescription = document.quote_form.description.value;
    if(textDescription == ""){
        document.quote_form.description.value = "Add some notes here";
    }
}
function submitQuoteRequest(){
    var emailAddress = document.quote_form.email.value;
    var fullName     = document.quote_form.full_name.value;
    var companyRole  = document.quote_form.company_role.value;
    var phone        = document.quote_form.phone.value;
    var qty          = document.quote_form.quantity.value;
    var ts           = document.quote_form.ts.value;
    var qtyNum       = /(^\d+$)|(^\d+\.\d+$)/;

    if(document.quote_form.page_url)
        document.quote_form.page_url.value = window.document.location.href ;

    if( Trim(fullName).length == 0) {
        alert("Name field is Blank");
        document.quote_form.full_name.focus();
        return false;
    }
    else if(!isEmail(emailAddress))
    {
        alert("Invalid email");
        document.quote_form.email.focus();
        return false;
    }
   /* else if(emailAddress != document.quote_form.email1.value){
        alert("Invalid email");
        document.quote_form.email1.focus();
        return false;
    }*/
    else if( Trim(companyRole).length == 0) {
        alert("Company Role field is Blank");
        document.quote_form.company_role.focus();
        return false;
    }
    else if( Trim(phone).length == 0) {
        alert("Phone No. is Blank");
        document.quote_form.phone.focus();
        return false;
    }
    else if( Trim(qty).length == 0) {
        alert("Quantity is Blank");
        document.quote_form.quantity.focus();
        return false;
    } else if (qtyNum.test(qty) == false) {
        alert("Please enter a specific quantity.");
        document.quote_form.quantity.focus();
        return false;
    } else{
        var s = document.quote_form.jcaptcha_validate.value;
               //alert(">>>>>> s  :: "+ s);
               new Ajax.Request('/validateCaptcha?s='+s, {
                   onComplete : function(t){

                       var result = t.responseText;
                       if(result.indexOf("true") == -1)
                       {
                           alert("Please enter valid security code");
                           document.quote_form.jcaptcha_validate.value = "";
                           document.quote_form.jcaptcha_validate.focus();
                       } else {
                           //$('captcha_error-message').style.display = "none";
                           sendQuoteRequestMail();
                       }
                       $('captcha_iframe').src = '/jcaptcha.go';
                   }

               });

    }

}

function submitInquiryEmail(){
    var emailAddress = document.inquiry.email_add.value;
    var fullName = document.inquiry.fullName.value;


    if(!isEmail(emailAddress))
    {
        alert("Invalid email");
        document.inquiry.email_add.focus();
        return false;
    }
    else if( Trim(fullName).length == 0) {
        alert("Name field is Blank. Please enter Name");
        document.inquiry.fullName.focus();
        return false;
    }

    else{
        new Ajax.Request('/inquiry_email', { method:'post',
            onComplete : function(t){
                lgbox_hide();
            },
            parameters: $('inquiry').serialize(true)
        });
    }

}
function sendQuoteLink()
{
    var emailAddress = document.quoteform.quote_email_add.value;

    if(!isEmail(emailAddress)){
        alert("Invalid email");
        document.quoteform.quote_email_add.focus();
        return false;
    }
    else if( Trim(emailAddress).length == 0){
        alert("Email address is Blank. Please enter email address.");
        document.quoteform.quote_email_add.focus();
        return false;
    }
    else{
        new Ajax.Request('/quoteLinksend', { method:'post',
            onComplete : function(t){
                lgbox_hide();
            },
            parameters: $('quoteform').serialize(true)
        });
    }
}
function setPassword()
{
    var userPass = document.changePass.txtpassword.value;
    var userPass2 = document.changePass.txtpassword2.value;
    var username = document.changePass.txtusername.value;
    if(Trim(username).length == 0)
    {
        alert("Please enter username.");
        document.changePass.txtusername.focus();
        return false;
    }
    else if( Trim(userPass).length == 0)
    {
        alert("Please enter password.");
        document.changePass.txtpassword.focus();
        return false;
    }
    else if(Trim(userPass2).length == 0)
    {
        alert("Please enter Re-type password.");
        document.changePass.txtpassword2.focus();
        return false;
    }
    else if(userPass != userPass2)
    {
    	alert("Passwords do not match.");
    	return false;
    }
    else
    {
        new Ajax.Request('/setPassword', { method:'post',
            onComplete : function(t){
                if(t.responseText.indexOf("Username already taken") != -1)
                {
                    alert("Username already taken. please try another.");
                    return false;
                }
                else
                {
                    lgbox_hide();
                }
            },
            parameters: $('changePass').serialize(true)
        });
    }
}


function openQuoteLinkPopUp(popupId, orderID)
{
    lgbox();
    var url = '/openPopup?popupId='+popupId+'&orderNumber='+orderID ;
    setLoading($('popup_content_id'));
    new Ajax.Updater('popup_content_id',url,{
        method: "get",
        onComplete:function(){
            $('popup_content_id').style.display="block";
            Effect.ScrollTo('popup_content_id');
        }
    });
}
function openResetPasswordPopUp(popupId, userID)
{
    lgbox();
    var url = '/openPopup?popupId='+popupId+'&userid='+userID ;
    setLoading($('popup_content_id'));
    new Ajax.Updater('popup_content_id',url,{
        method: "get",
        onComplete:function(){
            $('popup_content_id').style.display="block";
            Effect.ScrollTo('popup_content_id');
        }
    });
}
function sendCallmedetail()
{
    var userName = document.callme.user_name.value;
    var phoneNumber = document.callme.ph_code.value;
    var emailAddress = document.callme.user_email.value;
    var cmpName = document.callme.cmp_name.value;
    var callDay = document.callme.call_me_day.options[document.callme.call_me_day.options.selectedIndex].value;
    var callHour = document.callme.call_me_hour.options[document.callme.call_me_hour.options.selectedIndex].value;
    var callMinute = document.callme.call_me_minute.options[document.callme.call_me_minute.options.selectedIndex].value;
    var callTimeZone = document.callme.call_me_timezone.options[document.callme.call_me_timezone.options.selectedIndex].value;

    if( Trim(userName).length == 0) {
        alert("Name field is Blank. Please enter Name");
        document.callme.user_name.focus();
        return false;
    }
    else if( Trim(phoneNumber).length == 0) {
        alert("phone number field is Blank. Please enter phone number");
        document.callme.ph_code.focus();
        return false;
    }
    else if(!isEmail(emailAddress))
    {
        alert("Invalid email");
        document.callme.user_email.focus();
        return false;
    }
    else
    {
        new Ajax.Request('/callme_process', { method:'post',
            onComplete : function(t){
                var process = Trim(t.responseText);
                //alert("process ::::: "  + process);
                if(process == "Done"){
                    lgbox_hide();
                }else if(process == "Fail"){
                    alert("Unable to send contact information.");
                }
            },
            parameters: $('callme').serialize(true)
        });
    }
}
function sendRequestEmptySearch(){
    //    lgbox_hide3();
    //setLoading($('loading')) ;

    new Ajax.Request('/empty_search', {
        onComplete : function(t){

            $('div_id_1').innerHTML = t.responseText;

        },
        parameters: $('empty_search_request1').serialize(true)
    });

}



function recalculate(itemList, action) {

    var s = "";
    var quoteId = document.getElementById('quote_id').value ;
    var shipMethodId = "1"; //document.getElementById('ship_method_id').options[document.getElementById('ship_method_id').selectedIndex].value;
    if( itemList != '' )
    {
        var itemArray = itemList.split(",");
        for(var i=0; i < itemArray.length; i++) {
            var item = itemArray[i].split("^");

            s = s + '&mod_' + item[0]+'_'+item[1] + '=yes&qty_' + item[0]+'_'+item[1] + '=' + document.getElementById(item[0]+'_'+item[1] ).value;

        }
    }

    if( action == 'save')
    {
        setLoading(document.getElementById("shopping_cart"));
        new Ajax.Updater('shopping_cart','/cart?edit_quote=yes&quote_id=' + quoteId + '&addtocart=no' + s + '&ship_method_id=' + shipMethodId + '&response_type=save_confirm',{
            evalScripts:true,
            onComplete:function(){

            }
        });

    }
    else if( action == 'checkout' )
    {
        //var checkoutText = document.getElementById("checkout_text");
        //setLoading(checkoutText);
        //var o = document.getElementById("o").value;
        var o = $("o").value;
        var http = createRequestObject();
        var requestString = '/cart?edit_quote=yes&quote_id=' + quoteId + '&addtocart=no' + s + '&ship_method_id=' + shipMethodId + '&response_type=checkout';
        http.open('get', requestString);
        http.onreadystatechange = function() { location = storeSecureHome+'/billing_shipping?o=' + o; };
        http.send(null);

    }
    else if( action == 'update' )
    {
        //setLoading(document.getElementById("shopping_cart"));
        setLoading($("shopping_cart"));
        new Ajax.Updater('shopping_cart','/cart?edit_quote=yes&quote_id=' + quoteId + '&addtocart=no' + s + '&ship_method_id=' + shipMethodId + '&response_type=refresh_cart',{
            evalScripts:true,
            onComplete:function(){
                document.getElementById('number_items').innerHTML = "("+document.getElementById('numberOfItems').value+" Items)";
            }
        });

    }
    else if( action == 'change_user' )
    {
        //setLoading(document.getElementById("shopping_cart"));
        setLoading($("shopping_cart"));
        var quoteUserId = document.document.getElementById("quote_user_id").options[document.getElementById("quote_user_id").selectedIndex].value ;
        new Ajax.Updater('shopping_cart','/cart?edit_quote=yes&quote_id=' + quoteId + '&addtocart=no' + s + '&ship_method_id=' + shipMethodId + '&quote_user_id=' + quoteUserId + '&response_type=refresh_cart',{
            evalScripts:true,
            onComplete:function(){

            }
        });

    }
}

function setLoadingSmall(myDiv) {
    myDiv.innerHTML = "<img class=\"spinner\" src='"+storeImagePath+"ajax-loader_small.gif' alt=\"updating\">";
}
function setLoading(myDiv) {
    myDiv.innerHTML = "<img class=\"spinner\" src='"+storeImagePath+"ajax-loader_big.gif' alt=\"updating\"> Please wait...";
}
function setLoadingBlack(myDiv) {
    myDiv.innerHTML = "<div style=\"margin-top:20px\"><img class=\"spinner\" src='"+storeImagePath+"ajax-loader_big.gif'  alt=\"updating\"> Please wait...";
}
function setLoadingGray(myDiv) {
    myDiv.innerHTML = "<img class=\"spinner\" src='"+storeImagePath+"ajax-loader_big.gif' alt=\"updating\"> Please wait...";
}

function searchForAllProducts(){
    document.frmsearch.search_kw.value = "";
    document.frmsearch.submit();
}


function searchProduct() {
    document.frmsearch.pageIndex.value = "1";
    if ( $('catid') && ($('catid').value > 0) ) {
        document.frmsearch.cat.value = $('catid').value;
    } else {
        document.frmsearch.cat.value = "0";
    }
    document.frmsearch.sort.value  = "0";
    document.frmsearch.order.value = "0";

    document.frmsearch.submit();
}

function searchProductTop() {
    $('frmSearchTop').pageIndex.value = "1";
    $('frmSearchTop').cat.value       = "0";
    $('frmSearchTop').sort.value      = "0";
    $('frmSearchTop').order.value     = "0";

    $('frmSearchTop').submit();
}


function saveCustomMessageText(){
    var ele = $('h_message_id').value
    popupHide('customMessageEditor');
    setLoading($(ele)) ;
    new Ajax.Request('/save_custom_message', {
        onComplete : function(t){

            $(ele).innerHTML = Trim(t.responseText);

        },
        parameters: $('frm_customMessage').serialize(true)
    });
}

/* ######### CHAT ############ */

var chatter = new Array();

function openChatDialogCheck(){
    alert(chatter[chatter.length -1]);
}

function openChatDialog(user1, user2, sid){
    var url = '/chatdialog?user1='+user1+'&user2='+user2+'&storeId='+sid;
    var str = 'chat'+user1+user2;
    window.open(url,str,'location=no,menubar=no,status=no,scrollbars=no,resizable=no,titlebar=no,toolbar=no,top=10,left=500,height=550,width=320') ;
}

function getCookie(c_name)
{
    if (document.cookie.length > 0)
    {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1)
        {
            c_start = c_start + c_name.length + 1 ;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end));
        }
   }
   return "";
}

function setCookie(c_name,value)
{

    document.cookie=c_name+ "=" +escape(value)+"; expires=-1";

}

function removeCookie(c_name)
{
    var cookie_date = new Date ( );  // current date & time
    cookie_date.setTime ( cookie_date.getTime() - 1 );
    document.cookie = c_name += "=; expires=" + cookie_date.toGMTString();
   // document.cookie=c_name+ "=; expires=0";
}


/********** product detail page *************************/
 function editProduct(){
        document.frm_product_detail.action = "edit_product" ;
        document.frm_product_detail.method = "post";
        document.frm_product_detail.submit();
    }

    function goBack(){
        document.frm_product_detail.action = "search_product";
        document.frm_product_detail.method = "post";
        document.frm_product_detail.submit();
    }

function isPriceComparison(pn){
    var flg = false;
    var url = '/openPopup?popupId=11&pn='+pn ;
    new Ajax.Request(url,{
        method: "get",
        onSuccess:function(t){

             var resData = Trim(t.responseText);
            // alert(">>>>> alert "+resData);
             if( resData == 'true')
                $('compare_prices_link').style.display = 'block';
        }
    });
   
}

function addItemThisCondition(pn,varId){
        setLoadingSmall($('sb_loading'));
        addItemToCart(pn,varId);
}

function getQuotePopup(pn){
    var varId = 0;
    var oneProductVariation = -1;
    if ($('oneProductVariation')) {
        oneProductVariation = $('oneProductVariation').value;
    }

    // Comment by Nalay For Make this work in all browsers
    /*
    for(var i=0; i < document.frm_product_detail.product_variation.length ; i++){
        if(document.frm_product_detail.product_variation[i].checked)
            varId =  document.frm_product_detail.product_variation[i].value ;
    } */

    for(var i=0; i < document.getElementsByName("product_variation").length ; i++){
        if(document.getElementsByName("product_variation")[i].checked)
            varId =  document.getElementsByName("product_variation")[i].value ;
    }

    if( (varId == 0) && (oneProductVariation == -1)) {
        alert("Please select a product condition");
    } else if (oneProductVariation >= 0) {
        getQuoteThisCondition(pn,oneProductVariation);
    } else {
        getQuoteThisCondition(pn,varId);
    }
}

function getQuoteThisCondition(pn,varId){
    openPopup('4',pn,varId);
}

function addItem(pn){
    var varId = 0;
    var oneProductVariation = -1;
    if ($('oneProductVariation')) {
        oneProductVariation = $('oneProductVariation').value;
    }

    // Comment by Nalay For Make this work in all browsers
    /*
    for(var i=0; i < document.frm_product_detail.product_variation.length ; i++){
        if(document.frm_product_detail.product_variation[i].checked)
            varId =  document.frm_product_detail.product_variation[i].value ;
    }*/

    for(var i=0; i < document.getElementsByName("product_variation").length ; i++){
        if(document.getElementsByName("product_variation")[i].checked)
            varId =  document.getElementsByName("product_variation")[i].value ;
    }

    if( (varId == 0) && (oneProductVariation == -1)) {
        alert("Please select a product condition");
    } else if (oneProductVariation >= 0) {
        setLoadingSmall($('sb_loading'));
        addItemToCart(pn,oneProductVariation);
    } else {
        setLoadingSmall($('sb_loading'));
        addItemToCart(pn,varId);
    }
}



function openPopup(popupId){

     lgbox();

    var url = '/openPopup?popupId='+popupId ;

    /*
    for(var i=0 ; i < arguments.length ; i++ ){
        alert(">>>>>"+arguments[i]);
    }
    */

    if(popupId == '4' || popupId == '7') {
        if(arguments.length > 1)
            url += '&pn=' + arguments[1];
        if(arguments.length > 2)
            url += '&varId=' + arguments[2];
    }

     if(popupId == '9' || popupId == '10') {
          if(arguments.length > 1)
            url += '&s=' + arguments[1];
     }
    setLoading($('popup_content_id'));
    new Ajax.Updater('popup_content_id',url,{
        method: "get",
        onComplete:function(){
            $('popup_content_id').style.display="block";
            Effect.ScrollTo('popup_content_id');
        }
    });
}
//Used in dhtmlx category tree
function dhtmlxPopup(productEmail){
    dhtmlx_hide();
    //alert("productEmail :::"+productEmail);
    if(productEmail != "emailProduct" ){
        //document.getElementById('popup_content_id').style.height = "230px";
        $('popup_content_id').style.height = "230px";
        //document.getElementById('popup_content_id').style.width = "600px";
        $('popup_content_id').style.width = "600px";
    }
    else{
        //document.getElementById('popup_content_id').style.height = "130px";
        $('popup_content_id').style.height = "130px";
        //document.getElementById('popup_content_id').style.width = "400px";
        $('popup_content_id').style.width = "400px";
    }
    $('popup_content_id').innerHTML = "";
    $('popup_content_id').style.display="block";
    Effect.ScrollTo('popup_content_id');
}
function openSubPopup(popupId){

    lgbox1();

    var url = '/openPopup?sub=t&popupId='+popupId ;

    /*
    for(var i=0 ; i < arguments.length ; i++ ){
        alert(">>>>>"+arguments[i]);
    }
    */

    if(popupId == '4' || popupId == '7') {
        if(arguments.length > 1)
            url += '&pn=' + arguments[1];
        if(arguments.length > 2)
            url += '&varId=' + arguments[2];
    }

     if(popupId == '9' || popupId == '10') {
          if(arguments.length > 1)
            url += '&s=' + arguments[1];
     }
    setLoading($('popup_content_id1'));
    new Ajax.Updater('popup_content_id1',url,{
        method: "get",
        onComplete:function(){

            if(popupId == '4'){
                $('quantity').value = $('qty_pc').value;
            }

        }
    });
}


function showShippingOptions(){
    var productId = $('pid').value;
    var country   = $('freight_country').options[$('freight_country').selectedIndex].value;
    var zipcode   = $('freight_zipcode').value;
    var qty       = $('freight_qty').value;

    if(isEmpty(country)){
        alert("Please select a country");
    }
    else if(isEmpty(zipcode)){
        alert("Please enter a zipcode");
    }
    else if(isEmpty(qty)){
        alert("Please enter a quantity");
    }
    else{
        setLoading($('shipping_rates'));
        new Ajax.Updater('shipping_rates','/shipping_options?pid='+productId+'&country='+country+'&zipcode='+zipcode+'&qty='+qty,{
            evalScripts:true,
            onComplete:function(){

            }
        });
    }
}

function showShippingOptionsProductDetail(){
    var productId = $('pid').value;
    var country   = $('freight_country_product_detail').options[$('freight_country_product_detail').selectedIndex].value;
    var zipcode   = $('freight_zipcode_product_detail').value;
    var qty       = 1;

    if(isEmpty(country)){
        alert("Please select a country");
    }
    else if(isEmpty(zipcode)){
        alert("Please enter a zipcode");
    }
    else if(isEmpty(qty)){
        alert("Please enter a quantity");
    } else {
        var rand = Math.ceil(100000 * Math.random())
        var url ="/shipping_options";
        var params = "?pid=" + productId + "&country=" + country + "&zipcode=" + zipcode + "&qty=" + qty;
        url = url + params;
        $('shipping_rates_product_detail').style.display = "block";
        $('shipping_rates_product_detail').show();
        var options = {
            method: 'POST',
            onSuccess: function(t) {
                var square = $('shipping_rates_product_detail');
                //square.update("<div>close</div>" + t.responseText);
                square.update("<div style='float:right'><a href='javascript:closeShipping();'>close</a></div><br clear='all'>" + t.responseText);
            },
            on404:     function(t) { alert("404 Response")},
            onFailure: function(t) { alert("Request failed")},
            onLoading: function(t) { $('shipping_rates_product_detail').update("loading ...")},
            onLoaded:  function(t) {}
          }
          new Ajax.Request(url,options);
    }
}

function showShippingOptionsQuoteDetail(){
    var quoteId   = $('quote_id').value;
    var country   = $('freight_country_product_detail').options[$('freight_country_product_detail').selectedIndex].value;
    var zipcode   = $('freight_zipcode_product_detail').value;
    var qty       = 1; // we don't care about this

    if(isEmpty(country)){
        alert("Please select a country");
    }
    else if(isEmpty(zipcode)){
        alert("Please enter a zipcode");
    } else {
        var rand = Math.ceil(100000 * Math.random())
        var url ="/shipping_options";
        var params = "?qid=" + quoteId + "&country=" + country + "&zipcode=" + zipcode + "&qty=" + qty;
        url = url + params;
        $('shipping_rates_quote_detail').style.display = "block";
        $('shipping_rates_quote_detail').show();
        var options = {
            method: 'POST',
            onSuccess: function(t) {
                var square = $('shipping_rates_quote_detail');
                square.update("<div style='float:right'><a href='javascript:closeShipping();'>close</a></div><br clear='all'>" + t.responseText);
            },
            on404:     function(t) { alert("404 Response")},
            onFailure: function(t) { alert("Request failed")},
            onLoading: function(t) { $('shipping_rates_quote_detail').update("loading ...")},
            onLoaded:  function(t) {}
          }
          new Ajax.Request(url,options);
    }
}


function closeShipping() {
    if ($('shipping_rates_product_detail'))
        $('shipping_rates_product_detail').hide();
    if ($('shipping_rates_quote_detail'))
        $('shipping_rates_quote_detail').hide();
}

function changeItemCondiction(ele, partNumber){

    if( ('opt_q_'+ele.value) == ele.id){
       $('add_cart_button').style.display = 'none';
       $('get_quote_button').style.display = '';
       $('quoteLink').href = "/new_quote?pn="+partNumber+"&varId="+ele.value;
    }else{
       $('add_cart_button').style.display = '';
       $('get_quote_button').style.display = 'none';
    }

}
function showRightsMessage()
{
    alert("Your user account for the admin Store was created\nwith restricted access to system resources.");
    return false;
}
function openPage(strPageURL)
{
	window.location.href = storeSecureHome+strPageURL;
}

// Updated Address Book Start //
function addressBookOpen() {
    // show address book
    $('newAddressBook').show();
    // if not loaded, load lastname tab
    if ($F('isLastnameTabLoaded') == "no") {
        addressBookLoadLastnameTab();
    }
}

function addressBookClose() {
    // hide address book
    $('newAddressBook').hide();
}

function addressBookOpenUser(userID) {
    var shippingCountry = "";
    var billingCountry  = "";

    var rand = Math.ceil(100000 * Math.random())
    var url ="/addressBookLoadUser";   //returns JSON
    var params = "userID=" + userID + "&rand=" + rand
    url = url + "?" + params;

    var options = {
        method: 'POST',
        onSuccess: function(t) {
            var json = t.responseText.evalJSON(true);

            $('userID').value = userID;

            // load top right bar
            $('email').value = json.Bean.email;
            $('cname').value = json.Bean.company;
            $('fname').value = json.Bean.firstname;
            $('lname').value = json.Bean.lastname;            

            // load shipping address
            $('s_firstname').value = json.Bean.sFirstname;
            $('s_lastname').value  = json.Bean.sLastname;
            $('s_address1').value  = json.Bean.sAddress1;
            $('s_address2').value  = json.Bean.sAddress2;
            $('s_city').value      = json.Bean.sCity;
            $('s_state').value     = json.Bean.sState;
            $('s_zipcode').value   = json.Bean.sZipcode;
            shippingCountry = json.Bean.sCountry;
            $('s_daytime_phone_code').value = json.Bean.sDaytimePhoneCode;
            $('s_daytime_phone_no').value   = json.Bean.sDaytimePhoneNo;
            $('s_daytime_phone_ext').value  = json.Bean.sDaytimePhoneExt;
            $('s_evening_phone_code').value = json.Bean.sEveningPhoneCode;
            $('s_evening_phone_no').value   = json.Bean.sEveningPhoneNo;
            $('s_email').value              = json.Bean.sEmail;

            // load billing address
            $('b_firstname').value = json.Bean.bFirstname;
            $('b_lastname').value  = json.Bean.bLastname;
            $('b_address1').value  = json.Bean.bAddress1;
            $('b_address2').value  = json.Bean.bAddress2;
            $('b_city').value      = json.Bean.bCity;
            $('b_state').value     = json.Bean.bState;
            $('b_zipcode').value   = json.Bean.bZipcode;
            billingCountry           = json.Bean.bCountry;
            $('b_daytime_phone_code').value = json.Bean.bDaytimePhoneCode;
            $('b_daytime_phone_no').value   = json.Bean.bDaytimePhoneNo;
            $('b_daytime_phone_ext').value  = json.Bean.bDaytimePhoneExt;
            $('b_evening_phone_code').value = json.Bean.bEveningPhoneCode;
            $('b_evening_phone_no').value   = json.Bean.bEveningPhoneNo;
            $('b_email').value              = json.Bean.bEmail;

            // now, load salesperson via AJAX separately
            rand = Math.ceil(100000 * Math.random())
            var url2    ="/addressBookSalesperson";
            var params2 = "userID=" + userID + "&rand=" + rand
            url2 = url2 + "?" + params2;
            var options2 = {
                method: 'POST',
                onSuccess: function(t) {
                    var div = $('salespersonDIV');
                    div.update(t.responseText);
                    addressBookDisplayBillingTab();
                    $('isSameAddress').checked = false;
                },
                on404:     function(t) { alert("404 Response")},
                onFailure: function(t) { alert("Request failed")},
                onLoading: function(t) { $('salespersonDIV').update("loading ...")},
                onLoaded:  function(t) {}
            }
            new Ajax.Request(url2,options2);

            // didn't see this coming ... ok, load billing and shipping country pulldowns ... GAH
            var url3 ="/addressBookCountries";
            var params3 = "type=shipping&selected=" + shippingCountry + "&rand=" + rand
            url3 = url3 + "?" + params3;
            var options3 = {
                method: 'POST',
                onSuccess: function(t) {
                    var country = $('shippingCountry');
                    country.update(t.responseText);
                },
                on404:     function(t) { alert("404 Response")},
                onFailure: function(t) { alert("Request failed")},
                onLoading: function(t) { $('shippingCountry').update("loading ...")},
                onLoaded:  function(t) {}
            }
            new Ajax.Request(url3,options3);

            var url4 ="/addressBookCountries";
            var params4 = "type=billing&selected=" + billingCountry + "&rand=" + rand
            url4 = url4 + "?" + params4;
            var options4 = {
                method: 'POST',
                onSuccess: function(t) {
                    var country = $('billingCountry');
                    country.update(t.responseText);
                },
                on404:     function(t) { alert("404 Response")},
                onFailure: function(t) { alert("Request failed")},
                onLoading: function(t) { $('billingCountry').update("loading ...")},
                onLoaded:  function(t) {}
            }
            new Ajax.Request(url4,options4);
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) {},
        onLoaded:  function(t) {}
    }
    new Ajax.Request(url,options);    

}

function addressBookSaveUser() {
    /* save the form to an iframe iframeSaveUser */
    $('newAddressBookForm').submit();
}

function addressBookUpdateLeftColumn() {
    if ($('newAddressBookLeftTabsLastnameAnchor').hasClassName("active")) {
        addressBookLoadLastnameTab();
    } else {
        addressBookLoadCompanyTab();
    }
}

function addressBookLoadLastnameTab() {
    var rand = Math.ceil(100000 * Math.random())
    var url ="/addressBookLoadLastname?" + rand;
    var options = {
        method: 'POST',
        onSuccess: function(t) {
            var tab = $('newAddressBookLeftMainLastname');
            tab.update(t.responseText);
            $('isLastnameTabLoaded').value = "yes";
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) { $('newAddressBookLeftMainLastnameIframe').update("loading ...")},
        onLoaded:  function(t) {}
    }
    new Ajax.Request(url,options);
}

function addressBookLoadCompanyTab() {
    var rand = Math.ceil(100000 * Math.random())
    var url ="/addressBookLoadCompany?" + rand;
    var options = {
        method: 'POST',
        onSuccess: function(t) {
            var tab = $('newAddressBookLeftMainCompany');
            tab.update(t.responseText);
            $('isCompanyTabLoaded').value = "yes";
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) { $('newAddressBookLeftMainCompanyIframe').update("loading ...")},
        onLoaded:  function(t) {}
    }
    new Ajax.Request(url,options);
}

function addressBookDisplayCompanyTab() {
    $('newAddressBookLeftTabsLastnameAnchor').removeClassName("active");
    $('newAddressBookLeftTabsCompanyAnchor').addClassName("active");
    if ($F('isCompanyTabLoaded') == 'no')
        addressBookLoadCompanyTab();
    $('newAddressBookLeftMainLastname').hide();
    $('newAddressBookLeftCustomerList').hide();
    $('newAddressBookLeftMainCompany').show();
}


function addressBookDisplayLastnameTab() {
    $('newAddressBookLeftTabsLastnameAnchor').addClassName("active");
    $('newAddressBookLeftTabsCompanyAnchor').removeClassName("active");
    if ($F('isLastnameTabLoaded') == 'no')
        addressBookLoadLastnameTab();
    $('newAddressBookLeftMainLastname').show();
    $('newAddressBookLeftCustomerList').hide();
    $('newAddressBookLeftMainCompany').hide();
}

function addressBookDisplayBillingTab() {
    $('newAddressBookRightMainTabsShippingAnchor').removeClassName("active");
    $('newAddressBookRightMainTabsBillingAnchor').addClassName("active");
    $('newAddressBookRightMainShipping').hide();
    $('newAddressBookRightMainBilling').show();
}


function addressBookDisplayShippingTab() {
    $('newAddressBookRightMainTabsShippingAnchor').addClassName("active");
    $('newAddressBookRightMainTabsBillingAnchor').removeClassName("active");
    $('newAddressBookRightMainShipping').show();
    $('newAddressBookRightMainBilling').hide();
}

function searchCustomerNew() {
     var vText2 = $('custNameNew').value;
     var orderBy = "lastname";
     if ($('newAddressBookLeftTabsCompanyAnchor').hasClassName("active")) {
         orderBy = "company";
     }

     if(Trim(vText2) == "")  {
         alert("Plese enter a search term");
         return false;
     }

    $('newAddressBookLeftCustomerList').show();
    $('newAddressBookLeftMainLastname').hide();
    $('newAddressBookLeftMainCompany').hide();
     setLoading($('newAddressBookLeftCustomerList'));

     new Ajax.Updater('newAddressBookLeftCustomerList',"/customer_list?text=" + vText2 + "&newFormat=yes&orderBy=" + orderBy,{
        evalScripts:true,
        onComplete:function(){
            $('loadImage').style.display = "none";
        }
    });
}

    function addressBookDuplicate(ele){
        if(ele.checked){
            $('s_firstname').value          = $('b_firstname').value  ;
            $('s_lastname').value           = $('b_lastname').value  ;
            $('s_address1').value           = $('b_address1').value  ;
            $('s_address2').value           = $('b_address2').value   ;
            $('s_city').value               = $('b_city').value     ;
            $('s_state').value              = $('b_state').value    ;
            $('s_zipcode').value            = $('b_zipcode').value   ;
            $('s_daytime_phone_code').value = $('b_daytime_phone_code').value ;
            $('s_daytime_phone_no').value   = $('b_daytime_phone_no').value  ;
            $('s_daytime_phone_ext').value  = $('b_daytime_phone_ext').value  ;
            $('s_evening_phone_code').value = $('b_evening_phone_code').value ;
            $('s_evening_phone_no').value   = $('b_evening_phone_no').value  ;
            $('s_email').value              = $('b_email').value    ;
            $('s_country').selectedIndex    = $('b_country').selectedIndex   ;
        }
    }

// Updated Address Book End //


// new image uploader stuff
function openFlashUploader() {
    // wrap a setTimeout around this, combed with _hasPopupBlocker ...
    var productID = $F('pid');
    var imageWindow = window.open('/image_uploader?pid=' + productID);
}

function openFlashUploaderIframe() {
    // wrap a setTimeout around this, combed with _hasPopupBlocker ...
    var productID = $F('pid');
    var rand = Math.ceil(100000 * Math.random())
    var imageWindow = $('imageUploadIframe');
    imageWindow.src = "/image_uploader?pid=" + productID + "&rand=" + rand;
    imageWindow.show();

    //imageWindow.style.display = 'block';
//    var rand = Math.ceil(100000 * Math.random())
//    var url ="/image_uploader?pid=" + productID + "&" + rand;
//    var options = {
//        method: 'POST',
//        onSuccess: function(t) {
//            var imageWindow = $('imageUploadDiv');
//            imageWindow.show();
//            imageWindow.update(t.responseText);
//            alert(t.responseText);
//           //$('isLastnameTabLoaded').value = "yes";
//        },
//        on404:     function(t) { alert("404 Response")},
//        onFailure: function(t) { alert("Request failed")},
//        onLoading: function(t) { $('imageUploadDiv').update("loading ...")},
//        onLoaded:  function(t) {}
//    }
//    new Ajax.Request(url,options);
    //var imageWindow = window.open('/image_uploader?pid=' + productID);
}

function closeFlashUploader() {
    closeFlashUploaderIframe();
    closeFlashUploaderRelatedIframe();
}

function closeFlashUploaderIframe() {
    var imageWindow = $('imageUploadIframe');
    imageWindow.hide();
}

function openFlashUploaderRelatedIframe() {
    // wrap a setTimeout around this, combed with _hasPopupBlocker ...
    var productID = $F('pid');
    var imageWindow = $('imageUploadRelatedIframe');
    var rand = Math.ceil(100000 * Math.random())
    imageWindow.src = "/image_uploader?pid=" + productID + "&related=yes" + "&rand=" + rand;
    imageWindow.show();
}

function closeFlashUploaderRelatedIframe() {
    var imageWindow = $('imageUploadRelatedIframe');
    imageWindow.hide();
}


function openFlashUploaderRelated() {
    // wrap a setTimeout around this, combed with _hasPopupBlocker ...
    var productID = $F('pid');
    var imageWindow = window.open('/image_uploader?pid=' + productID + '&related=yes');
}
function openFlashUploaderRelatedDiv() {
    // wrap a setTimeout around this, combed with _hasPopupBlocker ...
    var productID = $F('pid');
    var imageWindow = window.open('/image_uploader?pid=' + productID + '&related=yes');
}


// courtesy stackoverflow.com/questions/668286/detect-blocked-popup-in-chrome
function _hasPopupBlocker(poppedWindow) {
    var result = false;
    try {
            if (typeof poppedWindow == 'undefined') {
                // Safari with popup blocker... leaves the popup window handle undefined
                result = true;
            } else if (poppedWindow && poppedWindow.closed) {
                // This happens if the user opens and closes the client window...
                // Confusing because the handle is still available, but it's in a "closed" state.
                // We're not saying that the window is not being blocked, we're just saying
                // that the window has been closed before the test could be run.
                result = false;
            } else if (poppedWindow && poppedWindow.test) {
                // This is the actual test. The client window should be fine.
                result = false;
            } else {
                // Else we'll assume the window is not OK
                result = true;
            }
        } catch (err) {
            //if (console) {
            //    console.warn("Could not access popup window", err);
            //}
        }

    return result;
}

// new image uploader stuff end

// Create property stuff on edit_product START //
function createNewProperty() {
    $("newProperty").value = "";
    $("div_new_property").show();
}


function loadProperty() {
    var rand = Math.ceil(100000 * Math.random());
    var selectedName = "Carl";
    var ppl = $('productPropertyList');
    // sorry, this is hackish ...
    for (var i=0; i < ppl.length;i++) {
        if (i == ppl.selectedIndex) {
            selectedName = ppl.options[i].text;
        }
    }
    var url ="/load_property";   //returns JSON
    var params = "propertyID=" + ppl.value + "&productID=" + $("pid").value + "&rand=" + rand
    url = url + "?" + params;

    var options = {
        method: 'POST',
        onSuccess: function(t) {            
            $('propertyName').update(selectedName)
            var json = t.responseText.evalJSON(true);

            var description = json.Bean.description;
            if ((description == "undefined") || (description == "null") || (description == null) || (description == undefined) )
                description = "";
            $('propertyID').value = json.Bean.propertyId;
            $('propertyValue').value = description;
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) { },
        onLoaded:  function(t) { }
    }
    new Ajax.Request(url,options);
}


function saveProperty() {
    // 1. save new property via AJAX & reload dropdown via AJAX
    var rand = Math.ceil(100000 * Math.random())
    var url ="/product_properties?pid=" + $("pid").value + "&propertyID=" + $("propertyID").value + "&propertyValue=" +  $("propertyValue").value + "&" + rand;
    var options = {
        method: 'POST',
        onSuccess: function(t) {
            var tab = $('propertyList');
            tab.update(t.responseText);
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) { $('propertyList').update("loading ...")},
        onLoaded:  function(t) {}
    }
    new Ajax.Request(url,options);
}


function addNewProperty() {
    // 1. save new property via AJAX & reload dropdown via AJAX
    var rand = Math.ceil(100000 * Math.random())
    var url ="/product_properties?pid=" + $("pid").value + "&newProperty=" + $("newProperty").value + "&" + rand;
    var options = {
        method: 'POST',
        onSuccess: function(t) {
            var tab = $('propertyList');
            tab.update(t.responseText);
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) { $('propertyList').update("loading ...")},
        onLoaded:  function(t) {}
    }
    new Ajax.Request(url,options);

    // 2. blank out newproperty and hide div
    $("newProperty").value = "";
    $("div_new_property").hide();
}
// Create property stuff on edit_product END

//begin about.jsp javascript
function activeDeactive(index, totalDivs)
    {
      for(var i=0 ; i<=totalDivs ; i++)
      {
          if(i == index)
          {
              //if(document.getElementById(index+"h").className == "accordion_toggle accordion_toggle_active")
              if($(index+"h").className == "accordion_toggle accordion_toggle_active")
              {
                  //document.getElementById(index+"h").className = "accordion_toggle";
                  $(index+"h").className = "accordion_toggle";
                  //document.getElementById(index+"div").style.display="none";
                  $(index+"div").style.display="none";
              }
              else
              {
                  //document.getElementById(index+"h").className = "accordion_toggle accordion_toggle_active";
                  $(index+"h").className = "accordion_toggle accordion_toggle_active";
                  //document.getElementById(index+"div").style.display="block";
                  $(index+"div").style.display="block";
                  //document.getElementById(index+"link").className = "on";
                  $(index+"link").className = "on";
                  Effect.ScrollTo(index+"h");
              }

          }
          else
          {
                  //document.getElementById(i+"h").className = "accordion_toggle";
                  $(i+"h").className = "accordion_toggle";
                  //document.getElementById(i+"div").style.display="none";
                  $(i+"div").style.display="none";
                  //document.getElementById(i+"link").className="";
                  $(i+"link").className="";
          }
      }
    }
// end about.jsp javascript

// begin billing_shipping.jsp javascript
function hide_cc() {
    var cc_checked = document.billing_shipping.payment_type_id[0].checked;
    var d = document.billing_shipping;

    if( !cc_checked ) {
        d.cc_number.disabled = true;
        d.cc_number.value = "";
        d.cc_number.style.backgroundColor = '#888';
        d.exp_month.disabled = true;
        d.exp_month.style.backgroundColor = '#888';
        d.exp_year.disabled = true;
        d.exp_year.style.backgroundColor = '#888';
        d.cvv2.disabled = true;
        d.cvv2.value = "";
        d.cvv2.style.backgroundColor = '#888';
        d.cc_type.disabled = true;
        d.cc_type.style.backgroundColor = '#888';
    } else {
        d.cc_number.disabled = false;
        d.cc_number.style.backgroundColor = '#fff';
        d.exp_month.disabled = false;
        d.exp_month.style.backgroundColor = '#fff';
        d.exp_year.disabled = false;
        d.exp_year.style.backgroundColor = '#fff';
        d.cc_type.disabled = false;
        d.cc_type.style.backgroundColor = '#fff';
        d.cvv2.disabled = false;
        d.cvv2.style.backgroundColor = '#fff';
    }
}
var httpTax;
var httpShip;
function enable_shipping () {
    //if( document.billing_shipping.shipping_amount.style.display == "block" )
    if( $('shipping_amount').style.display == "block" )
    {
        //document.billing_shipping.shipping_amount.style.display = "none";
        $('shipping_amount').style.display = "none";
    }
    else
    {
        //document.billing_shipping.shipping_amount.style.display = "block";
        $('shipping_amount').style.display = "block";
    }
}
function updateTax() {
    var state = document.billing_shipping.s_region[document.billing_shipping.s_region.selectedIndex].value
    var ship_method_id=document.billing_shipping.ship_method_id[document.billing_shipping.ship_method_id.selectedIndex].value;
    var country=document.billing_shipping.s_country[document.billing_shipping.s_country.selectedIndex].value ;
    //var postal=document.billing_shipping.s_postal.value;
    var postal=$('s_postal').value;

    //setLoadingBlack(document.getElementById('tax'));
    setLoadingBlack($('tax'));
    //setLoadingBlack(document.getElementById('finish_loader'));
    setLoadingBlack($('finish_loader'));
    //document.getElementById('finish_button').style.display='none';
    $('finish_button').style.display='none';

    var url ="/taxt?quote_id=<%= qb.getId() %>&country="+country+"&postal="+postal+"&ship_method_id="+ship_method_id+"&state="+state;
    var options = {
        method: 'get',
        onSuccess: function(t) {
            //var taxDiv = document.getElementById('tax');
            var taxDiv = $('tax');
            taxDiv.innerHTML = t.responseText;
            //document.getElementById('finish_button').style.display='block';
            $('finish_button').style.display='block';
            //document.getElementById('finish_loader').style.display='none';
            $('finish_loader').style.display='none';
        },
        on404:     function(t) { alert("404 Response")},
        onFailure: function(t) { alert("Request failed")},
        onLoading: function(t) {},
        onLoaded:  function(t) {}
    }
    new Ajax.Request(url,options);

}
function updateBillCountry() {
    var b_country = document.billing_shipping.b_country[document.billing_shipping.b_country.selectedIndex].value;
    if( (b_country == 'US') || (b_country == 'CA') ) {
        //document.getElementById("b_region2").style.display = "none";
        $("b_region2").style.display = "none";
        //document.billing_shipping.b_region2.value = "";
        $('b_region2').value = "";
    } else {
        //document.getElementById("b_region2").style.display = "block";
        $("b_region2").style.display = "block";
        //document.billing_shipping.b_region.selectedIndex = 0;
        $('b_region').selectedIndex = 0;
    }
}

function highlightZipAndCountry() {
    //var x1 = document.getElementById("highlight_zip");
    var x1 = $("highlight_zip");
    //var x2 = document.getElementById("highlight_country");
    var x2 = $("highlight_country");
    x1.setAttribute('style','background-color:#FFD7D7');
    x2.setAttribute('style','background-color:#FFD7D7');
}

function copy_to_billing() {
    var x = document.billing_shipping;
    x.b_firstname.value = x.s_firstname.value;
    x.b_lastname.value = x.s_lastname.value;
    x.b_company.value = x.s_company.value;
    x.b_addr.value = x.s_addr.value;
    x.b_addr2.value = x.s_addr2.value;
    x.b_city.value = x.s_city.value;
    x.b_region.selectedIndex = x.s_region.selectedIndex;
    x.b_postal.value = x.s_postal.value;
    x.b_country.selectedIndex = x.s_country.selectedIndex;
    x.b_phone.value = x.s_phone.value;
    x.b_email.value = x.s_email.value;
    x.b_region2.value = x.s_region2.value;
    document.getElementById("b_region2").style.display =
    document.getElementById("s_region2").style.display;
}
// end billing_shipping.jsp javascript

// begin checkout.jsp javascript
function same_address_checkout(ele){
    if(ele.checked)
    {
     /*   document.frm_checkout.b_firstname.value               	=	  document.frm_checkout.s_firstname.value         ;
        document.frm_checkout.b_lastname.value                   =    document.frm_checkout.s_lastname.value          ;
        document.frm_checkout.b_address1.value                   =    document.frm_checkout.s_address1.value          ;
        document.frm_checkout.b_address2.value                   =    document.frm_checkout.s_address2.value          ;
        document.frm_checkout.b_city.value                       =    document.frm_checkout.s_city.value              ;
        document.frm_checkout.b_state.selectedIndex              =    document.frm_checkout.s_state.selectedIndex     ;
        document.frm_checkout.b_zipcode.value                    =    document.frm_checkout.s_zipcode.value           ;
        document.frm_checkout.b_country.selectedIndex            =    document.frm_checkout.s_country.selectedIndex   ;
        document.frm_checkout.b_daytime_phone_code.value         =    document.frm_checkout.s_daytime_phone_code.value;
        document.frm_checkout.b_daytime_phone_no.value           =    document.frm_checkout.s_daytime_phone_no.value  ;
        document.frm_checkout.b_daytime_phone_ext.value          =    document.frm_checkout.s_daytime_phone_ext.value ;
        document.frm_checkout.b_evening_phone_code.value         =    document.frm_checkout.s_evening_phone_code.value;
        document.frm_checkout.b_evening_phone_no.value           =    document.frm_checkout.s_evening_phone_no.value  ;
        document.frm_checkout.b_email.value                      =    document.frm_checkout.s_email.value             ;
        */
         $('b_firstname_cout').value          = $('s_firstname_cout').value ;
         $('b_lastname_cout').value           = $('s_lastname_cout').value  ;
         $('b_address1_cout').value           = $('s_address1_cout').value  ;
         $('b_address2_cout').value           = $('s_address2_cout').value   ;
         $('b_city_cout').value               = $('s_city_cout').value     ;
         $('b_state_cout').value              = $('s_state_cout').value    ;
         $('b_zipcode_cout').value            = $('s_zipcode_cout').value   ;
         $('b_country').selectedIndex         = $('s_country').selectedIndex   ;
         $('b_daytime_phone_code_cout').value = $('s_daytime_phone_code_cout').value ;
         $('b_daytime_phone_no_cout').value   = $('s_daytime_phone_no_cout').value  ;
         $('b_daytime_phone_ext_cout').value  = $('s_daytime_phone_ext_cout').value  ;
         $('b_evening_phone_code_cout').value = $('s_evening_phone_code_cout').value ;
         $('b_evening_phone_no_cout').value   = $('s_evening_phone_no_cout').value  ;
         $('b_email_cout').value              = $('s_email_cout').value    ;
    }
}
function expandBillAddress(){
    //var idExpAdress = document.getElementById("expBillAddress");
    var idExpAdress = $("expBillAddress");
    if(idExpAdress.style.display == "block"){
        idExpAdress.style.display = "none";
    }
    else{
        idExpAdress.style.display = "block";
    }
}

function paypalpay() {
 //    if (! ($('ship_method_id').value == '') ) {
         document.paypal_form.submit();
 //    } else {
 //       alert("A valid shipping method must be selected first.")
 //       return false;
 //    }
}
// end checkout.jsp javascript

// begin profile.jsp javascript
function same_address_profile(ele){
     if(ele.checked){
         //Added by nisarg to resolve profile submit problem on live.Actual problem is with $in javascript
      /*   document.frm_profile.s_firstname.value =  document.frm_profile.b_firstname.value;
         document.frm_profile.s_lastname.value = document.frm_profile.b_lastname.value
         document.frm_profile.s_address1.value = document.frm_profile.b_address1.value;
         document.frm_profile.s_address2.value = document.frm_profile.s_address2.value;
         document.frm_profile.s_city.value = document.frm_profile.b_city.value;
         document.frm_profile.s_state.value = document.frm_profile.b_state.value;
         document.frm_profile.s_zipcode.value = document.frm_profile.b_zipcode.value;
         document.frm_profile.s_country.value = document.frm_profile.b_country.value;
         document.frm_profile.s_daytime_phone_code.value = document.frm_profile.b_daytime_phone_code.value;
         document.frm_profile.s_daytime_phone_no.value = document.frm_profile.b_daytime_phone_no.value;
         document.frm_profile.s_daytime_phone_ext.value = document.frm_profile.b_daytime_phone_ext.value;
         document.frm_profile.s_evening_phone_code.value = document.frm_profile.b_evening_phone_code.value;
         document.frm_profile.s_evening_phone_no.value = document.frm_profile.b_evening_phone_no.value;
         document.frm_profile.s_email.value = document.frm_profile.b_email.value;*/
         $('s_firstname_pro').value          = $('b_firstname_pro').value ;
         $('s_lastname_pro').value           = $('b_lastname_pro').value  ;
         $('s_address1_pro').value           = $('b_address1_pro').value  ;
         $('s_address2_pro').value           = $('b_address2_pro').value   ;
         $('s_city_pro').value               = $('b_city_pro').value     ;
         $('s_state_pro').value              = $('b_state_pro').value    ;
         $('s_zipcode_pro').value            = $('b_zipcode_pro').value   ;
         $('s_country').selectedIndex        = $('b_country').selectedIndex   ;
         $('s_daytime_phone_code_pro').value = $('b_daytime_phone_code_pro').value ;
         $('s_daytime_phone_no_pro').value   = $('b_daytime_phone_no_pro').value  ;
         $('s_daytime_phone_ext_pro').value  = $('b_daytime_phone_ext_pro').value  ;
         $('s_evening_phone_code_pro').value = $('b_evening_phone_code_pro').value ;
         $('s_evening_phone_no_pro').value   = $('b_evening_phone_no_pro').value  ;
         $('s_email_pro').value              = $('b_email_pro').value    ;
     }
 }
function changePassword(ele){
        if(ele.checked){
            //document.getElementById("div_changepassword").style.dispaly = "block";
            $('div_changepassword').style.display = "block";
        }
        else{
          //  document.getElementById("div_changepassword").style.dispaly = "none";
           $('div_changepassword').style.display = "none";
        }
    }


function saveProfile_profile(){
        //$('flg_type').value = "save";
        document.frm_profile.flg_type.value ="save";
        document.frm_profile.submit();
    }
// end profile.jsp javascript

// begin edit_product.jsp javascript
function uploadProductImage(){
    popupShow('productThumbnailUpload','clickChangeThumbnail');
    $("applyToAll").value = 'false';
   // $("chk_applyToAll").checked = false;
}
function productClone(){
        var confirmClone = confirm("Are you sure you want to clone this product ( "+ document.edit_product_form.part_number.value +" ) ?");

        if(confirmClone){
            $('clone').value = "clone";
            document.edit_product_form.action ="/edit_product";
            document.edit_product_form.submit();
          /*  document.edit_product_form.clone.value = "clone";
            document.edit_product_form.action ="/edit_product";
            document.edit_product_form.submit();
            */
         }
    }
function changeProduct( id ){
    if( id != 0){
        $('pid').value=id;
        document.edit_product_form.action = "/edit_product?pid="+id;
        document.edit_product_form.submit();
     /*   document.edit_product_form.pid.value=id;
        document.edit_product_form.action = "/edit_product?pid="+id;
        document.edit_product_form.submit();
        */
    }
}
function createNewMfg(){
    $('div_new_mfg').style.display = "block";
    //document.getElementById("div_new_mfg").style.display = "block";
}
var flag_newCat = false;
function createNewCategory()
{
    $("cat_id").disabled = true;
    if(flag_newCat)
    {
        $("newCategoryContent").style.display = "";
        $("subCategoryContent").style.display = "none";
        $("sub_cat_name").value = "";
        $("sub_cat_page").value = "";
        $("sub_cat_meta_keywords").value = "";
        $("sub_cat_meta_desc").value = "";
    }
    else
    {
        $("subCategoryContent").style.display = "none";
        $("newCategoryContent").style.display = "";
        //var objTR = document.getElementById("new_cat1");
        var objTR = $("new_cat1");
        var objTD = document.createElement("TD");
        objTD.innerHTML = "Category Name";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        var inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "cat_name";
        inputElement.id = "cat_name";
        objTD.appendChild(inputElement);
        objTR.appendChild(objTD);

        //objTR = document.getElementById("new_cat2");
        objTR = $("new_cat2");
        objTD = document.createElement("TD")
        objTD.innerHTML = "Category Title";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "cat_page";
        inputElement.id = "cat_page";
        objTD.appendChild(inputElement);
        objTR.appendChild(objTD);

        //objTR = document.getElementById("new_cat3");
        objTR = $("new_cat3");
        objTD = document.createElement("TD")
        objTD.innerHTML = "Category Meta Keywords(comma seperated)";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "cat_meta_keywords";
        inputElement.id = "cat_meta_keywords";
        inputElement.style.width = "500px";
        objTD.appendChild(inputElement);
        objTR.appendChild(objTD);

        //objTR = document.getElementById("new_cat4");
        objTR = $("new_cat4");
        objTD = document.createElement("TD")
        objTD.innerHTML = "Category Meta Descriptions";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "cat_meta_desc";
        inputElement.id = "cat_meta_desc";
        inputElement.style.width = "500px" ;
        objTD.appendChild(inputElement);

        objTR.appendChild(objTD);
        flag_newCat = true;
    }
}
var flag_SubCat = false;
function createSubCategory()
{
    $("cat_id").disabled = true;
    if(flag_SubCat)
    {
        $("subCategoryContent").style.display = "";
        $("newCategoryContent").style.display = "none";
        $("cat_name").value = "";
        $("cat_page").value = "";
        $("cat_meta_keywords").value = "";
        $("cat_meta_desc").value = "";
    }
    else
    {
        $("subCategoryContent").style.display = "";
        $("newCategoryContent").style.display = "none";
        //var objTR = document.getElementById("new_subcat1");
        var objTR = $("new_subcat1");
        var objTD = document.createElement("TD");
        objTD.innerHTML = "Category Name";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        var inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "sub_cat_name";
        inputElement.id = "sub_cat_name";
        objTD.appendChild(inputElement);
        objTR.appendChild(objTD);

        //objTR = document.getElementById("new_subcat2");
        objTR = $("new_subcat2");
        objTD = document.createElement("TD")
        objTD.innerHTML = "Category Title";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "sub_cat_page";
        inputElement.id = "sub_cat_page";
        objTD.appendChild(inputElement);
        objTR.appendChild(objTD);

        //objTR = document.getElementById("new_subcat3");
        objTR = $("new_subcat3");
        objTD = document.createElement("TD")
        objTD.innerHTML = "Category Meta Keywords(comma seperated)";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "sub_cat_meta_keywords";
        inputElement.id = "sub_cat_meta_keywords";
        inputElement.style.width = "500px";
        objTD.appendChild(inputElement);
        objTR.appendChild(objTD);

        //objTR = document.getElementById("new_subcat4");
        objTR = $("new_subcat4");
        objTD = document.createElement("TD")
        objTD.innerHTML = "Category Meta Descriptions";
        objTD.className = "col-1";
        objTR.appendChild(objTD);
        objTD = document.createElement("TD");
        inputElement = document.createElement("input");
        inputElement.type = "text";
        inputElement.name = "sub_cat_meta_desc";
        inputElement.id = "sub_cat_meta_desc";
        inputElement.style.width = "500px" ;
        objTD.appendChild(inputElement);

        objTR.appendChild(objTD);
        flag_SubCat = true;
    }
}

function closeCreateNewCategoryContent()
{
    $("cat_id").disabled = false;
    $("newCategoryContent").style.display = "none";
    $("cat_name").value = "";
    $("cat_page").value = "";
    $("cat_meta_keywords").value = "";
    $("cat_meta_desc").value = "";
}
function closeCreateSubCategoryContent()
{
    $("cat_id").disabled = false;
    $("subCategoryContent").style.display = "none";
    $("sub_cat_name").value = "";
    $("sub_cat_page").value = "";
    $("sub_cat_meta_keywords").value = "";
    $("sub_cat_meta_desc").value = "";
}
function uploadProductRelatedImage(){
    //Event.stop(event);
    //document.getElementById('process1').style.visibility='hidden';
    $('process1').style.visibility='hidden';
    document.form2.ordering.value="";
    //$('ordering').value="";
    document.form2.shortDesc.value="";
    //$('shortDesc').value="";
    document.form2.uploadfile1.value="";
    //$('uploadfile1').value="";
    popupProduct('productImagesUpload','productImage');
}
function uploadProductDoc(){
    //Event.stop(event);
    //document.getElementById('process2').style.visibility='hidden';
    $('process2').style.visibility='hidden';
    document.form3.uploadfile2.value="";
    popupProduct('productDocUpload','productDoc');
}


function chooseImage(){
    popupShow('img_chooser','NotGiven');
    new Ajax.Updater('img_chooser_content',"/image_chooser",{
        evalScripts:true,
        onComplete:function(){
           if($('mfg_id')){
               if($('mfg_id').options.length > 0){
                    setPeviewImage($('mfg_id').options[0].value);
               }
            }
        }
    });
}
function setPeviewImage(val){
    var valArray = val.split(",");
    $('choose_img_preview').src = valArray[0];
    $('url_fullimage').value = valArray[1];
   // document.getElementById('choose_img_preview').src = valArray[0];
    //document.getElementById('url_fullimage').value = valArray[1];
}
function setChooseImage(){
    if(document.getElementById && document.getElementById('choose_img_preview')){
        $('thumbnailImg').src = $('choose_img_preview').src;
        //alert("photo thumbnail img"+document.getElementById('thumbnailImg').src);
        $('thumbnailImg').style.maxHeight = $('choose_img_preview').style.maxHeight;
        $('thumbnailImg').style.maxWidth = $('choose_img_preview').style.maxWidth;
        $('photoUrl').value = $('choose_img_preview').src;
        //alert("photo url :::"+document.getElementById('photoUrl').value);
        $('photoUrlFullsize').value = $('url_fullimage').value;
        //alert("photo full size:::"+document.getElementById('photoUrlFullsize').value);
    /*    document.getElementById('thumbnailImg').src = document.getElementById('choose_img_preview').src;
        //alert("photo thumbnail img"+document.getElementById('thumbnailImg').src);
        document.getElementById('thumbnailImg').style.maxHeight = document.getElementById('choose_img_preview').style.maxHeight;
        document.getElementById('thumbnailImg').style.maxWidth = document.getElementById('choose_img_preview').style.maxWidth;
        document.getElementById('photoUrl').value = document.getElementById('choose_img_preview').src;
        //alert("photo url :::"+document.getElementById('photoUrl').value);
        document.getElementById('photoUrlFullsize').value = document.getElementById('url_fullimage').value;
        //alert("photo full size:::"+document.getElementById('photoUrlFullsize').value);
        */
    }
    popupHide('img_chooser');
}
function searchImage(displayall)
{
    $("spinner").style.display = "block";
    var partNumber = $("txtPNumber").value;
    if(displayall)
    {
        partNumber = "";
        $("txtPNumber").value = "";
    }
    $('img_chooser_content').innerHTML = "";
    new Ajax.Updater('img_chooser_content',"/image_chooser?pNumber="+partNumber,{
        evalScripts:true,
        onComplete:function(){
           $("spinner").style.display = "none";
            if($('mfg_id')){
                if($('mfg_id').options.length > 0){
                        $('btnsDIV').style.display = "block";
                        setPeviewImage($('mfg_id').options[0].value);
                }
           }else{
                $('btnsDIV').style.display = "none";
           }
        }
    });
}
function goBack(){
    document.edit_product_form.action = "search_product";
    document.edit_product_form.submit();
}

function addTab()
{
    //document.getElementById('tabName').value = "";
    $('tabName').value = "";
    if(tabSize > 4)
    {
        alert("You are allowed to add a maximum of 5 tabs.");
        return false;
    } else {
        popupShow('addTabDiv','NotGiven');
    }
}
function saveTab(txtID)  {
    if(Trim(document.getElementById(txtID).value) == "") {
        alert("Please enter valid tab Name.");
        return false;
    } else {
        tabSize = tabSize + 1;
        var iLiId = parseInt(tabSize + 1);
        var tabDisplayIndex = parseInt(tabSize + 1);
        //var tabDisplayName = document.getElementById(txtID).value;
        var tabDisplayName = $(txtID).value;
        var objLi = document.createElement("li");
        objLi.id        = "li" + iLiId;
        objLi.className = "";

        var objHref = document.createElement("a");
        //var objHref = $("a");
        objHref.appendChild(document.createTextNode(tabDisplayName));
        objHref.id   = "tabTitle" + tabSize;
        objHref.href = "javascript:displayTab("+parseInt(tabDisplayIndex)+");";
        objLi.appendChild(objHref);

        //document.getElementById("tabUL").appendChild(objLi);
        $("tabUL").appendChild(objLi);

        popupHide('addTabDiv');
        displayTab(tabDisplayIndex);
    }
}
var tabIndexID = "";
var tabDatabaseID = "";
function changeTabTitle(tabIndex, tabID) {
      tabIndexID = tabIndex;
      tabDatabaseID = tabID;
      $("editTabName").value = document.getElementById(tabIndexID).innerHTML;
      //document.getElementById("editTabName").value = document.getElementById(tabIndexID).innerHTML;
      popupShow('editTabDiv','NotGiven');
}
function displayTab(tabIndex) {
    for(var i=0 ; i<=6 ; i++) {
		if(i == tabIndex) {
            if(document.getElementById("li"+tabIndex)){
                $("li"+tabIndex).className="tabberactive";
             }
            if(document.getElementById("tab"+tabIndex+"_content")){
                $("tab"+tabIndex+"_content").style.display = "block";
             }
        } else {
            if(document.getElementById("li"+i)){
                $("li"+i).className="";
             }
            if(document.getElementById("tab"+i+"_content")){
                $("tab"+i+"_content").style.display = "none";
            }
        }
    }
}
function isDimensionValidForUPS() {
    //UPS limit Package exceeds maximum size total constraints of 165 inches
    // (length + girth, where girth is 2 x width plus 2 x height).
    var length = $("length").value;
    var width  = $("width").value;
    var height = $("height").value;
    var weight = $("weight").value;
    length = length.replace(/,/g, "");
    width  = width.replace(/,/g, "");
    height = height.replace(/,/g, "");
    weight = weight.replace(/,/g, "");

    if(Trim(length) == ""){
        alert("Please enter valid length for dimension.");
        return false;
    }if(isNaN(length)){
        alert("Invalid dimension length. Length should be numeric.");
        return false;
    }

    if(Trim(weight) == ""){
        alert("Please enter valid weight for dimension.");
        return false;
    }if(isNaN(weight)){
        alert("Invalid dimension weight. Weight should be numeric.");
        return false;
    }

    if(Trim(width) == ""){
        alert("Please enter valid width for dimension.");
        return false;
    }if(isNaN(width)){
        alert("Invalid dimension width. Width should be numeric.");
        return false;
    }

    if(Trim(height) == ""){
        alert("Please enter valid height for dimension.");
        return false;
    }if(isNaN(height)){
        alert("Invalid dimension height. Height should be numeric.");
        return false;
    }

    if(parseInt(parseInt(length) + parseInt((2 * width) + (2 * height))) > 165) {
        alert("UPS allows maximum size dimension constraints of 165 inches.(length + girth, where \n girth is 2 x width plus 2 x height).");
        return false;
    } else {
        return true;
    }
}
function limiter(textAreaID, displayMsgId, charlength) {
	var tex = document.getElementById(textAreaID).value;
	var len = tex.length;
	if(len > charlength) {
        tex = tex.substring(0,charlength);
        document.getElementById(textAreaID).value = tex;
        return false;
	}
	//document.getElementById(displayMsgId).value = charlength - len;
    $(displayMsgId).value = charlength - len;
}
//end edit_product.jsp javascript

// begin quote.jsp javascript
function openAdminNotepad() {
        popupShow('add_note','NotGiven');
    }

    function saveComments(quoteID, close) {
        var vComment = document.getElementById("txtComments").value;
        if(Trim(vComment).length == 0)
        {
            alert("Please enter comment");
        }
        else
        {
            new Ajax.Updater('adminCommentBox',"/save_comment?QuoteID="+quoteID+"&comment="+vComment,{
                evalScripts:true,
                onComplete:function(){
                    document.getElementById("txtComments").value = "";
                    if(close){
                        popupHide('add_note');
                    }
                }
            });
        }
    }
function isNumber(inputStr) {
    for (var i = 0; i < inputStr.length; i++) {
        var oneChar = inputStr.substring(i, i + 1)
        if (oneChar < "0" || oneChar > "9") {
            //alert("Please enter positive numbers only.")
            return false
        }
    }
    return true
}
//end quote.jsp javascript

// begin user.jsp javascript
function changeStatus()
    {
        if(Trim($("btnLock").innerHTML) == "Unlock")
        {
            $("accountStatus").value = "OFF";
            $("btnLock").innerHTML = "";
            $("btnLock").innerHTML = "Currently unlocked - click to lock";
        }
        else
        {
            $("accountStatus").value = "ON";
            $("btnLock").innerHTML = "";
            $("btnLock").innerHTML = "Currently locked - click to unlock";
        }
    }
function saveAndBack()
    {
        $("saveandback").value = "true";
        document.forms.user_form.submit();
    }
function adminCheck()
	{
		if($('admin').checked)
		{
			$('user').checked = true;
			$('accountant').checked = true;
			$('shipping').checked = true;
			shippingCheck();
			userCheck();
			accountantCheck();
		}
		else
		{
			$('user').checked = false;
			$('accountant').checked = false;
			$('shipping').checked = false;
			shippingCheck();
			userCheck();
			accountantCheck();
		}
	}
function userCheck(flag)
	{
		if($('user').checked)
		{
			$('product_price').checked = true;
			$('store_feature').checked = true;
			$('category').checked = true;
			$('template').checked = true;
            $('tableseditor').checked = true;
            $('products').checked = true;
			$('view_users').checked = true;
        }
		else
		{
			$('product_price').checked = false;
			$('store_feature').checked = false;
			$('category').checked = false;
            $('tableseditor').checked = false;
            $('template').checked = false;
			$('products').checked = false;
			$('view_users').checked = false;
		}
	}
function accountantCheck()
	{
		if($('accountant').checked)
			$('transactions').checked = true;
		else
			$('transactions').checked = false;
	}
	function shippingCheck()
	{
		if($('shipping').checked)
			$('orders_shipping').checked = true;
		else
			$('orders_shipping').checked = false;
	}
// end user.jsp javascript

// begin select_customer.jsp javascript
function clickNext()
	{
        //var vCustomerEmailAddress = document.getElementById("customer").options[document.getElementById("customer").selectedIndex].text;
        var vCustomerEmailAddress = $("customer").options[$("customer").selectedIndex].text;
        //var vCustomerID = document.getElementById("customer").options[document.getElementById("customer").selectedIndex].value;
        var vCustomerID = $("customer").options[$("customer").selectedIndex].value;
        if(vCustomerID == "0")
        {
            alert("Please select customer to create quote.");
            return false;
        }
        else
        {
            //document.getElementById("custID").value = vCustomerID;
            $("custID").value = vCustomerID;
            document.frmCustomer.action="/admin_new_quote";
            document.frmCustomer.method = "post";
            document.frmCustomer.submit();
        }
    }
function createNewCustomer()
    {
        $("extCusDiv").style.display = "none";
        $("createcustomerdiv").style.display = "block";
    }
function saveProfile()
    {
        //document.createCus.saveCustomer.value = "save";
        $('saveCustomer').value = "save";
        //Added by nisarg to check enable while error in page
        if(document.createCus.isSameAddress.checked){
            //document.createCus.sameAddress.value = "checked" ;
            $('sameAddress').value = "checked" ;
        }
        //end
        document.createCus.action = "/select_customer";
        document.createCus.method = "post";
        alert("save profile submit");
        document.createCus.submit();
    }
function closeNewCustomer()
    {
        $("createcustomerdiv").style.display = "none";
        $("extCusDiv").style.display = "block";
    }
function trim(myString)
    {
        return myString.replace(/^s+/g,'').replace(/s+$/g,'')
    }
function same_address_cust(ele)
    {
        if(ele.checked){

        /*    document.createCus.s_firstname.value      		= 	document.createCus.b_firstname.value;
            document.createCus.s_lastname.value 			= 	document.createCus.b_lastname.value;
            document.createCus.s_address1.value 			= 	document.createCus.b_address1.value;
            document.createCus.s_address2.value 			= 	document.createCus.b_address2.value;
            document.createCus.s_city.value 				= 	document.createCus.b_city.value;
            document.createCus.s_state.value 				= 	document.createCus.b_state.value;
            document.createCus.s_zipcode.value 				= 	document.createCus.b_zipcode.value;
            document.createCus.s_country.value 				= 	document.createCus.b_country.value;
            document.createCus.s_daytime_phone_code.value 	= 	document.createCus.b_daytime_phone_code.value;
            document.createCus.s_daytime_phone_no.value 	= 	document.createCus.b_daytime_phone_no.value;
            document.createCus.s_daytime_phone_ext.value 	= 	document.createCus.b_daytime_phone_ext.value;
            document.createCus.s_evening_phone_code.value 	= 	document.createCus.b_evening_phone_code.value;
            document.createCus.s_evening_phone_no.value 	= 	document.createCus.b_evening_phone_no.value;*/
            //document.createCus.s_email.value 				= 	document.createCus.b_email.value;

            $('s_firstname_cus').value          = $('b_firstname_cus').value  ;
            $('s_lastname_cus').value           = $('b_lastname_cus').value  ;
            $('s_address1_cus').value           = $('b_address1_cus').value  ;
            $('s_address2_cus').value           = $('b_address2_cus').value   ;
            $('s_city_cus').value               = $('b_city_cus').value     ;
            $('s_state_cus').value              = $('b_state_cus').value    ;
            $('s_zipcode_cus').value            = $('b_zipcode_cus').value   ;
            $('s_country').selectedIndex        = $('b_country').selectedIndex   ;
            $('s_daytime_phone_code_cus').value = $('b_daytime_phone_code_cus').value ;
            $('s_daytime_phone_no_cus').value   = $('b_daytime_phone_no_cus').value  ;
            $('s_daytime_phone_ext_cus').value  = $('b_daytime_phone_ext_cus').value  ;
            $('s_evening_phone_code_cus').value = $('b_evening_phone_code_cus').value ;
            $('s_evening_phone_no_cus').value   = $('b_evening_phone_no_cus').value  ;
            //$('s_email').value              = $('b_email').value    ;
            
        }
    }
// end select_customer.jsp javascript

// begin editable_tables.jsp javascript
var isChangesMade = false;
    var counter = 0 ;
    function loadTable(table_id){

        if(isChangesMade){
            if(confirm("Discard changes ?")){
                //document.edit_form.tableId.value = table_id ;
                $('tableId').value = table_id ;
                document.edit_form.submit();
            }
        }
        else{
            //document.edit_form.tableId.value = table_id;
            $('tableId').value = table_id;
            document.edit_form.submit();
        }
         return true;
    }
    function cancelChanges(){
        document.edit_form.submit();
        return true;
    }
function saveChanges(){
        //document.edit_form.flag.value = "save";
        $('flag').value = "save";
        document.edit_form.submit();
        return true;
    }
    function deleteRows(){
        var flg = false;
        for(var i=0; i < document.getElementsByName("chk_delete_item").length ; i++){
            if(document.getElementsByName("chk_delete_item")[i].checked){
                flg = true;
                break;
            }
        }

        if(flg){
            if(confirm("Do you want to delete selected Items?")){
                document.edit_form.flag.value = "delete";
                //$('flag').value = "delete";
                document.edit_form.submit();
                 return true;
            }
        }else{
            alert("Please select Item for delete.");
        }

        return false;

    }
function editShipPrice(id){
        //var ele = document.getElementById("tr_ship_price_"+id);
        var ele = $("tr_ship_price_"+id);
        var objTD;
        for(var i = 0; i < ele.childNodes.length; i++)
        {
            objTD = ele.childNodes[i];
            if(objTD.tagName == "TD")
                ele.removeChild(objTD);
        }
        //var catId = document.edit_form.cbo_cat.value;
        var catId = $('cbo_cat').value;

        new Ajax.Updater(ele.id,"/add_ship_price_row?id="+id+"&cat_id="+catId);
    }
    function addNewShipPrice(){
        counter++;
       // var objTABLE = document.getElementById("ship_price_table");
        var objTABLE = $("ship_price_table");
        var objTBody = objTABLE.getElementsByTagName("TBODY")[0];
        //var objTR = document.createElement("TR");
        var objTR = $("TR");
        objTR.id = "new_tr"+counter;
        //var catId = document.edit_form.cbo_cat.value;
        var catId = $('cbo_cat').value;
        new Ajax.Updater(objTR.id,"/add_ship_price_row?count="+counter+"&cat_id="+catId);
        objTBody.appendChild(objTR);

    }
function changeCategory(){
        if(isChangesMade){
            if(confirm("Discard changes ?")){
               // document.edit_form.displayFreeShipp.value = "false";
                 $('displayFreeShipp').value = "false";
                document.edit_form.submit();

            }
        }
        else{
            //document.edit_form.displayFreeShipp.value = "false";
            $('displayFreeShipp').value = "false";
            document.edit_form.submit();

        }
        return true;
    }
    function displayAllFreeShippingProducts()
    {
       // document.edit_form.displayFreeShipp.value = "true";
        $('displayFreeShipp').value = "true";
        document.edit_form.submit();
    }
function checkUnCheckAll(){
        for(var i=0 ; i < document.edit_form.elements.length ; i++)
        {
            if(document.edit_form.elements[i].type == "checkbox" && document.edit_form.elements[i].name.indexOf("free_shipping_") != -1)
            {
                document.edit_form.elements[i].checked = document.edit_form.chkAll.checked;
            }
        }
    }


    function assignAllEnableDisable()
    {
        if(document.getElementById("chAssignAll").checked)
        {
            //document.getElementById("new_shipMethod_all").disabled = false;
            //document.getElementById("new_base_price_all").disabled = false;
            //document.getElementById("new_addtl_price_all").disabled = false;
            //document.getElementById("btnAssignAll").disabled = false;
            $("btnAssignAll").disabled = false;
            //document.getElementById("free_ship_all").disabled = false;
            $("free_ship_all").disabled = false;
        }
        else
        {
            //document.getElementById("new_shipMethod_all").disabled = true;
            //document.getElementById("new_base_price_all").disabled = true;
            //document.getElementById("new_addtl_price_all").disabled = true;
            //document.getElementById("btnAssignAll").disabled = true;
            $("btnAssignAll").disabled = true;
            //document.getElementById("free_ship_all").disabled = true;
            $("free_ship_all").disabled = true;
        }
    }
function assignToAll()
    {
        //document.edit_form.flag.value = "save";
        $('flag').value = "save";
        document.edit_form.submit();
        return true;
    }
// end editable_tables.jsp javascript