/* UTILITIES FIRST ... */

var J = jQuery.noConflict();

var storeImagePath = null;
var storeHome = null;
var storeSecureHome = null;
var destURL = "/";


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 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;
}



//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 parseURI(uri) {
    return encodeURIComponent(uri);
}




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

function setLoadingSmall(myDiv) {
    J(myDiv).html("<img class=\"spinner\" src='"+storeImagePath+"ajax-loader_small.gif' alt=\"updating\">");
    
}



function login(dest_url) {
    destURL = dest_url;
}

function loginSubmit() {

    
    var shouldForward = false;
    J.ajax({
        
        type:'POST',
        url:'/customerLoginAJAX?dest_url='+destURL+"&username="+J("#username").val()+"&password="+J("#password").val()+"&lock_count="+J("#lock_count").val(),
        success:function(json){
            shouldForward = true;
            if(json.success == false){

                J("#loginError").html(json.message);
                J("#lock_count").val(parseInt(J("#lock_count").val())+1);
                shouldForward = false;
                
                
            }
            if (shouldForward) {

                
                parent.J.fn.colorbox.close();  // function used to close colorbox
                
                if (json.dest_url)
                    location = json.dest_url;
                
            }

        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr.status);
            alert(thrownError);
        } 
    });

}

function registerSubmit() {

    var shouldForward = false;
    J.ajax({

        type:'POST',
        url:'/registerAJAX?username='+J("#chooseusername").val()+"&password="+J("#choosepassword").val()+"&password2="+J("#repassword").val()+"&email="+J("#email_address").val()+"&cname="+J("#company").val(),
        success:function(json){
            shouldForward = true;
            if(json.success == false){

                J("#registerError").html(json.errorText);
                shouldForward = false;

            }
            if (shouldForward) {

                J("#registration_success").prepend("<h3>"+json.successText+"</h3>");
                J("div#pop_registration_success").colorbox({inline:true,href:"#inline_registrationsuccess",open:true});
            }
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr.status);
            alert(thrownError);
        }
    });

}

// freight quote
function showShippingOptions() {
    var productId = J('#pid').val();    // calculate based on quotes
    var quoteId = J("#quote_id").val(); // calculate based on quotes
    var country   = J('#freight_country').val();
    var zipcode   = J('#freight_zipcode').val();
    var qty       = J('#freight_qty').val();


    
    if(isEmpty(country)) {
        alert("Please select a country");
    } else if(isEmpty(zipcode)) {
        alert("Please enter a zipcode");
    } else if(isEmpty(qty) && productId) {
        alert("Please enter a quantity");
    } else {
        
        setLoadingSmall(J('#shipping_rates'));

        var url = '';
        if (productId) {
            url = '/shipping_options?pid='+productId+'&country='+country+'&zipcode='+zipcode+'&qty='+qty;
        } else {
            url = '/shipping_options?qid='+quoteId+'&country='+country+'&zipcode='+zipcode+'&qty=1';
        }
        
        J.ajax({

            type:'GET',
            url:url,
            success:function(res){
                J("#shipping_rates").html(res);
            }

        });
    }
}

// Add item to shopping cart
function addItemToCart(pn,varId){
    
    pn = parseURI(pn);
    var qty = 1;

    if(document.getElementById && document.getElementById('cartItem_qty')){
        qty = $('cartItem_qty').value;
    }

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

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

    J.ajax({

        method:'GET',
        url:requrl,
        success: function(res){

            location = storeHome+'/view_cart';
            
        },
        error: function(){
            alert("could not add item to cart");
        }

        
    });
}


function refreshCart(){

    J.ajax({
        method:'GET',
        url:'/refresh_cart',
        success:function(res){
          J("#shopping_cart").html(res)  ;
        },
        complete:function(){

            if( J("#cart_items")){

                J("#cart_items").html(J("#numberOfItems").val());
                J("#subtotal_items").html(J("#numberOfItems").val());

            }

            if( J("#div_subtotal")) {

                J("#div_subtotal").html(J("#subTotal").val());

            }

        }
    });

    /*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 = J('#quote_id').val();
    var shipMethodId = "1";
    
    
    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";
    

    var jxhr = J.ajax({

        method:'GET',
        url:'/cart?edit_quote=yes&quote_id=' + quoteId + '&addtocart=no' + s + '&ship_method_id=' + shipMethodId + '&response_type=refresh_cart',
        beforeSend:function(xhr){
            setLoadingSmall(J("#"+loadanimation));
        },
        success:function(res){
          J("#shopping_cart").html(res)  ;
        },
        complete:function(){
            
            if( J("#cart_items")){

                J("#cart_items").html(J("#numberOfItems").val());
                J("#subtotal_items").html(J("#numberOfItems").val());
                J("#cart_items_bar").html(J("#numberOfItems").val());
                
            }

            if( J("#div_subtotal")) {

                J("#div_subtotal").html(J("#subTotal").val());

            }

            if (J("#grand_total")) {

                J("#grand_total").html(J("#subTotal").val());

            }

            if (isFromViewCart == false){
                updateShipping();
            }

        }

    });


}

//sendCallmedetail() :: sagar

function sendCallmedetail() {

    // callme form  

    var userName = J("#user_name").val();
    var phoneNumber = J("#ph_code").val();
    var emailAddress = J("#user_email").val();
    var cmpName = J("#cmp_name").val();

    var callDay = J("#call_me_day").val();
    var callHour = J("#call_me_hour").val();
    var callMinute = J("#call_me_minute").val();
    var callTimeZone = J("#call_me_timezonde").val();

    if( Trim(userName).length == 0) {

        alert("Name field is Blank. Please enter Name");
        J("#user_name").focus();
        return false;

    } else if( Trim(phoneNumber).length == 0) {

        alert("phone number field is Blank. Please enter phone number");
        J("#ph_code").focus();
        return false;

    } else if(!isEmail(emailAddress)) {

        alert("Invalid email");
        J("#user_email").focus();
        return false;

    } else {

        J.ajax({

           type: "POST",
           url: "/callme_process",
           data:J("#callme").serialize(),
           complete: function (res) {

               var process = Trim(res.responseText);

               if (process == "Done") {

                   parent.J.fn.colorbox.close();  // function used to close colorbox

               } else if (process == "Fail") {

                   alert("Unable to send contact information.");
                   
               }

           }

         });

    }
}


function submitInquiryEmail(){

    // inquiry form

    var emailAddress = J("#email_add").val();
    var fullName = J("#fullName").val();

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

        J.ajax({

            type:"POST",
            url:"/inquiry_email",
            data:J("#inquiry").serialize(),
            complete: function (res) {

                parent.J.fn.colorbox.close();   // close popup

            }

        });

    }
}

function getTSToken() {

    
     var rand = Math.ceil(100000 * Math.random());
     var url ="/ts_token?" + rand;

     J.ajax({

        type:"POST",
        url:url,
        success: function (res) {
            var seconds = Trim(res);
            J("#ts").val(seconds);
        },
        error: function() {
            alert("Request Failed");
        }

      });

}

function submitQuoteRequest(){

    var emailAddress = J("#email").val();
    var fullName     = J("#full_name").val();
    var companyRole  = J("#company_role").val();
    var phone        = J("#phone").val();
    var qty          = J("#quantity").val();
    var ts           = J("#ts").val();
    var qtyNum       = /(^\d+$)|(^\d+\.\d+$)/;

    if (J("#page_url").val())
        J("#page_url").val(window.document.location.href) ;


    if ( ts == 100) {

        var rand = Math.ceil(100000 * Math.random())
        var url ="/ts_token?" + rand;

        J.ajax({

            type:"POST",
            url:url,
            success: function (res) {
                var seconds = Trim(res.responseText);
                J("#ts").val(seconds);
            },
            statusCode: {
                404: function() {
                  alert('404 response');
                }
            },
            error: function() {
                alert("Request Failed");
            }
        });


    }


    if ( Trim(fullName).length == 0) {

        alert("Name field is Blank");
        J("#full_name").focus();
        return false;

    } else if(!isEmail(emailAddress)) {

        alert("Invalid email");
        J("#email").focus();
        return false;

    } else if( Trim(companyRole).length == 0) {

        alert("Company Role field is Blank");
        J("#company_role").focus();
        return false;

    } else if( Trim(qty).length == 0) {

        alert("Quantity is Blank");
        J("#quantity").focus();
        return false;

    } else if (!qtyNum.test(qty)) {

        alert("Please enter a specific quantity.");
        J("#quantity").focus();
        return false;

    } else {
        
        //var captchaString = J("#jcaptcha_validate").val();

        /*J.ajax({

            type:"POST",
            url:'/validateCaptcha?s='+captchaString,
            complete: function (res) {

                var result = res.responseText;

                if (result.indexOf("true") == -1) {

                    alert("Please enter valid security code");

                    J("#jcaptcha_validate").val("");

                    J('#captcha_iframe').attr("src","/jcaptcha.go");

                    J("#jcaptcha_validate").focus("");

                } else {

                    J("#quote_form").submit();
                    parent.J.fn.colorbox.close();
                    
                }
            }
        });*/

        J.ajax({

			type:'GET',
			url:'/validateNewCaptcha?captcha_validate='+jQuery('#captcha_validate').val(),
			success:function(res){
				if (res=="success"){
					J("#quote_form").submit();
					return true;
				} else {
					alert("Please enter valid captcha");
					return false;
				}
			},
			error:function(){
				alert("Error");
				return false;
			}


		});
       
    }
}


function searchProduct() {


    var search = Trim(J("#main_search_box").val());
    J("#main_search_box").val(search);

    if ( J('#cat') && (J('#cat').val() > 0) ) {
        document.frmsearch.cat.value = J('#cat').val();
    } else {
        document.frmsearch.cat.value = "0";
    }

    return true;

    /*document.frmsearch.pageIndex.value = "1";

    if ( J('#cat') && (J('#cat').val() > 0) ) {
        document.frmsearch.cat.value = J('#cat').val();
    } else {
        document.frmsearch.cat.value = "0";
    }
    document.frmsearch.sort.value  = "0";
    document.frmsearch.order.value = "0";

    document.frmsearch.submit();*/
}

function getFeaturedProduct(pageNum, parentCatID){

    J("#"+parentCatID).load("/storefront/featuredProducts/"+pageNum+"/"+parentCatID);

}
