var qty=0;
var productID=0;
var priceunit=0;
var colorID;
var sizeID;

jQuery(document).ready(function($) {
    
    
    //newsletterControl.check();						   
    // btn checkout cart---------------------------
    shoppingCart.goStepCheckout();
    // btn clear cart---------------------------
    shoppingCart.clearCart();
    // btn remove cart--------------------------
    shoppingCart.removeProductCart();	
    // btn Update cart--------------------------
    shoppingCart.updateCart();	
    // Btn add to cart -------------------------    
    shoppingCart.addToCart();
    //--------------------------------------------------
    

    jQuery('#twitter-link-content').cycle({
        fx:     'scrollUp',
        speed:    2000,
        timeout:  5000
    });
    
    jQuery("#header-cart").click(function(){
        var $href=$(this).attr("href");
        window.location.href=$href;
    });  
});

var checkBox={
    isChecked:function(class_action){
        var arrayID=new Array();
        $(class_action).each(function(){
            arrayID.push(this.value);
        });	
        if(arrayID!=""){
            return true;	
        }else{
            return false;	
        }
			
    }	
}

var shoppingCart={
    addToCart:function(){
        jQuery(".addToCart").click(function(){
            qty=$("#qty-input").val();
            productID=$("#productID").val();
            priceunit=$("#price").val();
            sizeID=$("#sizeID").val();
            colorID=$("#colorID").val();
            
            var next_add=true;
            
            if(parseInt(qty)>0){
                
                if(sizeID==""){
                    alert("You need to select a size");	
                    next_add=false;
                }
                if(colorID==""){
                    alert("You need to select a color");	
                    next_add=false;
                }
                
                if(next_add){
                    $.post('/controllers/process.php', {
                        productID:productID, 
                        qty:qty,
                        model:"Shopping",
                        action:"checkStock"
                    }, function(data){
                        if(data.instock=="OK"){
                            $.post('/controllers/process.php', {
                                productID:productID, 
                                qty:qty,
                                sizeID:sizeID,
                                colorID:colorID,
                                price:priceunit, 
                                model:"Shopping",
                                action:"add"
                            }, function(datax){
                                if(datax.ok=="DONE"){
                                    // Next---
                                    window.location.href="/shop/cart.php";
                                //--------
                                }else{
                                    alert(datax.message);
                                    return false;	
                                }
                            },"json");
                        }
                        if(data.instock=="IS_GREATER"){
                            alert(data.message);
                            return false;
                        }
                        if(data.instock=="SOLD_OUT"){
                            alert(data.message);
                            return false;
                        }
                        if(data.instock=="ERRORNUMBER"){
                            alert(data.message);
                            return false;
                        }
                    },"json");	
                }
            }else{
                alert("The quantity is required in your product");
                return false;
            }
        });
    },
	
    updateCart:function(){
        var total=jQuery("#total_item").val();
        var error
        jQuery(".update_cart").click(function(){
            for(i=0; i<total; i++){
                q=$("#qty"+i).val();
                if(q>0){
                    error=1;
                }
                else{
                    alert("The quantity is required in your product");
                    error=0;
                    break;
                }
            }
			
            if(error){
                $("#action_cart").val("update");
				
                frm=document.forms["frmCart"];
                frm.submit();
            }
        });	
    },
	
    clearCart:function(){
        jQuery(".clear_cart").click(function(){
            var ok=confirm("Are you sure you want to empty your shopping cart?");
            if(ok==true){
                $("#action_cart").val("clearCart");				
                frm=document.forms["frmCart"];
                frm.submit();
            }
        });
    },
	
    removeProductCart:function(){
        jQuery(".remove_x").click(function(){
            $("#action_cart").val("remove");
            $("#index").val($(this).attr("name"));
            frm=document.forms["frmCart"];
            frm.submit();
        });
    },
		
    goStepCheckout:function(){
        jQuery(".step_one_checkout").click(function(){
            $("#action_cart").val("goStepCheckout");	
            frm=document.forms["frmCart"];
            frm.submit();
        });
    }
}

var addressCustomers={
    state:function(country,state,idDivState, objName_state){
        $.post('/controllers/process.php', {
            state:state, 
            country_:country,
            action:"showStateCustomers",
            model:"Countries",
            objState:objName_state
        }, function(data){
            $("#"+idDivState).html(data);
        //g(idDivState).innerHTML=data; 
        });
    },
    stateShip:function(country,state,idDivState, objName_state){
        $.post('/controllers/process.php', {
            state:state, 
            country_:country,
            action:"showStateCustomers",
            model:"Countries",
            objState:objName_state
        }, function(data){
            $("#"+idDivState).html(data);
            
            if(country=="United States"){
                g("disclamer").style.display="none";
                g("accept_terms").value=0;
            }else{
                g("disclamer").style.display="";
                g("accept_terms").value=1;
            }
        });
    }
}

var newsletterControl={
    check:function(){
        jQuery("#newsletter-button").click(function(){
            if(emailCheck($("#newsletter-email").val())==0){
                alert("Please type in a valid email address");
                $("#newsletter-email").focus();	
                return false;
            }else{
                frm=document.forms["newsletter-form"];
                frm.submit();
            }
        });
    }	
}


var loader='<img src="/images/ajax-loader.gif" alt="loader" id="imgLoader" />';
function onfocus_ctrl(text,idCtrl){
    if(g(idCtrl).value==text){
        g(idCtrl).value="";
    }
}
function onblur_ctrl(text,idCtrl){
    if(g(idCtrl).value==""){
        g(idCtrl).value=text;
    }	
}

function egc_code_KeyPress(e){
    var key=e.keyCode || e.which;
    if(key==13)
        apply_egc_code();
}

function coupon_code_KeyPress(e){
    var key=e.keyCode || e.which;
    if(key==13)
        apply_coupon_code();
}

function apply_coupon_code(){
    var subtotal=0;
    var coupon_code=0;
    var costShipping=0;
    subtotal=g("subtotal").value;
    coupon_code=g("coupon_code").value;
    costShipping=g("price_shipping").value;
    stateShipping=g("stateShipping").value;
    if(trim(coupon_code)==""){
        alert("Enter your discount code");
        g("coupon_code").focus();
        return false;
    }else{
        $.post('/controllers/process.php', {
            coupon_code:coupon_code, 
            subtotal:subtotal,
            action:"discountCode",
            model:"Shopping",
            costShipping:costShipping,
            stateShipping:stateShipping
        }, function(data){
            if(data.OK=="OK"){
                /*g("discountCodeAmount_div_label").style.display="";
                g("discountCodeAmount_div").style.display="";
                g("discountCodeAmount_div").innerHTML=currencyConvert(data.discountAmount);
                */
               g("discountCode_div").style.display="";
               g("discountCode_div").innerHTML="<label>Discount Code:</label><span>- $ "+currencyConvert(data.discountAmount)+"</span>";
               
                if(data.freeshipping=="YES"){
                   g("freeShippingcode").value="YES";
                }else{
                   g("freeShippingcode").value="NO"; 
                }
                g("idCouponCode").value=data.couponID;
                g("discountCodePercent").value=data.discountPercent;
                g("amountCodeDiscount").value=data.discountAmount;
                
				//g("amountCodeDiscount").value=data.estimatetotal;
		g("monto_tax").value=currencyConvert(data.amountTax);
		//g("montoTaxID").innerHTML=currencyConvert(data.amountTax);
                g("lblAmountTax").innerHTML="<label>Tax:</label><span>$ "+data.amountTax+"</span>";
			
		g("total_amount").value=currencyConvert(data.totalAmount);
		//g("totalAmount_without_egc").innerHTML=currencyConvert(data.totalAmount);
		//g("totalAmount").innerHTML=currencyConvert(data.totalAmount);
                g("totalAmount").innerHTML="<label>Total Amount: </label><span>$ "+currencyConvert(data.totalAmount)+"</span>";
				
            }else{
                g("idCouponCode").value="0";
                //g("discountCodeAmount_div_label").style.display="none";
                //g("discountCodeAmount_div").style.display="none";
                g("discountCode_div").style.display="none";
                g("freeShippingcode").value="NO";
		g("coupon_code").value="";
				
				$.post('/controllers/process.php', {
					coupon_code:coupon_code, 
					subtotal:subtotal,
					action:"clearDiscountCode",
					model:"Shopping",
					costShipping:costShipping,
					stateShipping:stateShipping
				}, function(data){
					g("monto_tax").value=currencyConvert(data.amountTax);
					//g("montoTaxID").innerHTML=currencyConvert(data.amountTax);
                                        g("lblAmountTax").innerHTML="<label>Tax:</label><span>$ "+data.amountTax+"</span>";
                                        
					g("total_amount").value=currencyConvert(data.totalAmount);
					//g("totalAmount_without_egc").innerHTML=currencyConvert(data.totalAmount);
					//g("totalAmount").innerHTML=currencyConvert(data.totalAmount);
                                        g("totalAmount").innerHTML="<label>Total Amount: </label><span>$ "+currencyConvert(data.totalAmount)+"</span>";
				},"json");
                alert(data.message);
            }
        },"json");
    }
}

function clearCart(){
    var ok=confirm("Are you sure you want to empty your shopping cart?");
    if(ok==true){
        window.location.href="controllers/cartController.php?action=clear";
    }
}
function addCart_KeyPress(e,productID,flagColorSize){
    var key=e.keyCode || e.which;
    if(key==13)
        addCart(productID,flagColorSize);
}

function currencyConvert(n){
    n = Math.round( (n*100) )/100;
    strN = new String( n );
    if( strN.indexOf( "." ) == -1 )
        strN += ".00";
    else if( strN.indexOf( "." ) == strN.length-2 )
        strN += "0";
    return strN;
}

function validCreditCart(ccNumb) {
    var valid = "0123456789" //Digitos validos
    var len = ccNumb.length;
    var iCCN = parseInt(ccNumb); 
    var sCCN = ccNumb.toString(); 
    sCCN = sCCN.replace (/^\s+|\s+$/g,'');
    var iTotal = 0;  
    var bNum = true; 
    var bResult = false; 
    var temp; 
    var calc; 
 
    for (var j=0; j<len; j++) {
        temp = "" + sCCN.substring(j, j+1);
        if (valid.indexOf(temp) == "-1"){
            bNum = false;
        }
    }
 
    if(!bNum){
        bResult = false;
    }
 
    if((len == 0)&&(bResult)){
        bResult = false;
    } else{
        if(len >= 12){  // 15 or 16 for Amex or V/MC
            for(var i=len;i>0;i--){  
                calc = parseInt(iCCN) % 10; 
                calc = parseInt(calc);  
                iTotal += calc;
                i--;  
                iCCN = iCCN / 10;
                calc = parseInt(iCCN) % 10 ;
                calc = calc *2; 
                switch(calc){
                    case 10:
                        calc = 1;
                        break;       //5*2=10 & 1+0 = 1
                    case 12:
                        calc = 3;
                        break;       //6*2=12 & 1+2 = 3
                    case 14:
                        calc = 5;
                        break;       //7*2=14 & 1+4 = 5
                    case 16:
                        calc = 7;
                        break;       //8*2=16 & 1+6 = 7
                    case 18:
                        calc = 9;
                        break;       //9*2=18 & 1+8 = 9
                    default:
                        calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
                }                                               
                iCCN = iCCN / 10;
                iTotal += calc;
            } //end for
            if ((iTotal%10)==0){
                bResult = true;
            } else {
                bResult = false; 
            }
        }
    }
    return bResult;
}

