var qty   = 0;
var price = 0;
var sku   = 0;
var skus  = new Array();

function updateSizes(color){
    
 var sizes = [];
 var el = document.createElement('div');
 el.id = "sizes";
 el.className = "clearboth"; 
 selSize = $("input[name='size']:checked").val();
 var sizeChecked = false;
 var skuCount = 0;
 for (var i in skus) {
 	skuCount++;
 }
 
 for (var i in skus){
     if (skus[i]['color'] == color){
         var option = document.createElement('div');
        option.className = "option";
        if (skus[i]['size_img'] != '') {
            att = document.createElement('img');
            att.src = baseUrl + '/images/attributes/'+skus[i]['size_img'];
        } else {
            att = document.createElement('span');
            att.className = 'att';
            t = document.createTextNode(skus[i]['size_name']);
            att.appendChild(t);
        }
        //input = document.createElement('input');
        //input.type="radio";
        //input.name="size";
        //input.id = i;
        //input.value=skus[i]['size'];
        //if (IEcheck == true) {
            //input.onclick = function() {updateQuantity(input.id);};
        //} else {
            //input.addEventListener('click',function() {updateQuantity(input.id);}, false)
        //}
		
        if(selSize){
            if(selSize == skus[i]['size']){
                sizeChecked = true;
                //input.checked = 'checked';
                sku   = i;
                qty   = skus[i]['quantity'];
                price = skus[i]['price'];
                
                document.getElementById('priceTag').innerHTML = "Price: <strong>$"+ this.price + "</strong>";
            }
        }

        
        if(skus[i]['quantity'] > 0)
        {
        	input = '<input type="radio" name="size" id="'+i+'" onclick="updateQuantity(\'' + i + '\');" '
        }
        else
        {
			if(skus[i]['size_name'] == 'coming this spring')
			{
        		input = '<input type="radio" class="hidden" name="size" id="'+i+'" disabled="true"" '
			}
			else
			{
				input = '<span class="out-of-stock">Temporarily<br /> out of stock</span><br /><input type="radio" class="hidden" name="size" id="'+i+'" disabled="true"" '
			}
        }
		
        if (sizeChecked) {
            input += ' checked="checked"';
        }else if(skuCount == 1){
            input += ' checked="checked"';
            updateQuantity(i);
        }
        input += ' />';
        option.appendChild(att);
        option.appendChild(document.createElement('br'));
        var span = document.createElement('span');
        span.innerHTML = input
        option.appendChild(span);
        el.appendChild(option);
    }
 }
 $("#sizes").replaceWith(el);
}

function updateQuantity(i){
    qty = skus[i]["quantity"];
    price = skus[i]['price'];
    sku = i;
    
    document.getElementById('priceTag').innerHTML = "Price: <strong>$"+ price + "</strong>";
}

function setSku(i) {
    this.qty = skus[i]['quantity'];
    this.price = skus[i]['price'];
    this.sku = i;
}

function changeImage(img){
    document.getElementById('mainImg').src = baseUrl + "/images/products/medium/"+img;
    document.getElementById('mainImg_anchor').href = baseUrl + "/images/products/" + img;
}

function addToCart(amt, sku) {
    if (this.sku == 0) {
        alert('Please select a color and size');
        return;
    }
    document.getElementById('addToBag').style.display="none";
    document.getElementById('adding').style.display = "block";
    setTimeout('updateAdding()', 1000);
    
    if (parseInt(amt) > parseInt(this.qty)){
        alert('There are only ' + this.qty + ' items in stock right now.');
        document.getElementById('qty').value= qty;

        return;
    } else { 
        $.ajax({
            type: 'POST',
            url: baseUrl+'/shop/additem/' ,
            data: {sku:this.sku, qty:amt, price:this.price },
            success: function(msg) {  
                updateqty(this.sku, amt);
            },
            error: function(msg){
                alert('Error: Couldn\'t add item');
            }
        })
    }
}

function updateAdding(){
    document.getElementById('addToBag').style.display="block";
    document.getElementById('adding').style.display = "none"; 
}

function removeItem(sku){
    //saveQty(sku, 0);
    updateCartTotal();
    $.ajax({
        type: 'POST',
        url: baseUrl+'/shop/removeitem/' ,
        data: {sku:sku },
        success: function(msg) {                   
            updateNoItems();
            updateCartTotal();
            document.getElementById('item_'+sku).style.display = 'none';
        },
        error: function(msg) {
            updateNoItems();
            updateCartTotal();
            document.getElementById('item_'+sku).style.display = 'none';
        }
    });
    
}
function updateqty(sku, amt){
    document.getElementById('qtyTagWrap').display = 'none';
    document.getElementById('addToBag').display = 'none';
    document.getElementById('qtyTagAdded').innerHTML = amt + " item(s) in cart";
    document.getElementById('qtyTagAdded').style.display = 'block';
    
    //Updating header cart variable
    //cartAmt = parseInt(document.getElementById('cartAmt').innerHTML);
    //cartAmt = parseInt(amt) + parseInt(cartAmt);
    updateNoItems();
}

function changeQty(sku, mQty){
    currVal = parseInt(document.getElementById('qty_'+sku).innerHTML);
    document.getElementById('qty_'+sku).innerHTML = '<input type="text" size="2" id="qty_new_'+sku+'" value="'+currVal+'" />';
    document.getElementById('qty_'+sku).innerHTML += '<input type="button" value="Save" onclick="saveQty(\''+sku+'\', '+mQty+');">';
}

function saveQty(sku, mQty){
    newVal = parseFloat(document.getElementById('qty_new_'+sku).value);
    if(newVal == 0)
    {
    	removeItem(sku);
    	return;
    }
    if (newVal > mQty){
        alert('There is only '+mQty+ ' items available for this particular product.');
        document.getElementById('qty_new_'+sku).value = mQty;
        return;
    }
    document.getElementById('qty_'+sku).innerHTML = newVal;
    
    itemPrice = parseFloat(document.getElementById('price_'+sku).innerHTML);
    
    total = (newVal * itemPrice).toFixed(2);
    $.ajax({
        type: 'POST',
        url: baseUrl+'/shop/additem/' ,
        data: {sku:sku, qty:newVal, price:itemPrice },
        success: function(msg) {                   
            updateNoItems();
            updateCartTotal();
        },
        error: function(msg) {
            alert('Error: Couldnt add item');
        }
    });
    document.getElementById('total_'+sku).innerHTML = total;
}

function updateCart(sku, newVal){
}

function updateNoItems(){
    $.ajax({
        type: 'POST',
        url: baseUrl+'/shop/getNoItems/' ,
        success: function(msg){                   
            document.getElementById('cartAmt').innerHTML = msg;
            //updateCartTotal();
        },
        error: function(msg){
            alert('Error: Couldnt update no. items');
        }
    })
}
function updateCartTotal(){
    $.ajax({
        type: 'POST',
        url: baseUrl+'/shop/getCartTotal/' ,                            
        success: function(msg) {                   
            document.getElementById('total_amt').innerHTML = msg;
        },
        error: function(msg) {
            alert('Error: Couldnt update no. items');
        }
    })
}
function showOrders(session_id){
    $.ajax({
        type: 'POST',
        url: baseUrl+'/profile/getorders/' ,
        data:'session='+session_id,
        success: function(msg) {                   
            document.getElementById(session_id).innerHTML = msg;
            $("#"+session_id).slideToggle('slow');
        },
        error: function(msg) {
            alert('Error: Couldnt update no. items');
        }
    })
}
function updateShipping(){
    $("#newShipping").slideToggle("slow");
}
function updateShipping2(){
    
    newHTML = '<div class="box" style="width:550px !important; cler:both;">';
    newHTML += '<h2><span id="white">Enter your new Information Below</span></h2>';
    
    newHTML += '<div class="form-field first_name" style="width: 230px; float: left;">';
    newHTML += '<label for="first_name"><strong>First Name*</strong></label>';
    newHTML += '<input id="first_name" type="text" name="first_name" size="30"/>';
    newHTML += '</div>';
    
    newHTML += '<div class="form-field last_name" style="width: 230px; float: left;">';
    newHTML += '<label for="last_name"><strong>Last Name</strong></label>';
    newHTML += '<input id="last_name" type="text" name="last_name" size="30"/>';
    newHTML += '</div>';
    
    newHTML += "<div style='clear:both;'></div>";
    
    newHTML += '<div class="form-field address" style="width: 230px; float: left;">';
    newHTML += '<label for="address"><strong>Address*</strong></label>';
    newHTML += '<input id="address" type="text" name="address" size="30"/>';
    newHTML += '</div>';
    
    newHTML += '<div class="form-field address_2" style="width: 230px; float: left;">';
    newHTML += '<label for="address_2"><strong>Address 2</strong></label>';
    newHTML += '<input id="address_2" type="text" name="address_2" size="30"/>';
    newHTML += '</div>';
    
    newHTML += "<div style='clear:both;'></div>";
    
    newHTML += '<div class="form-field city" style="width: 230px; float: left;">';
    newHTML += '<label for="city"><strong>City*</strong></label>';
    newHTML += '<input id="city" type="text" name="city" size="30" maxlength="255"/>';
    newHTML += '</div>';
    newHTML += '<div class="form-field state" style="width: 150px; float: left;">';
    newHTML += '<label for="state"><strong>State*</strong></label>';
    selectState = document.getElementById('stateSelect').innerHTML;
    newHTML += selectState;
    newHTML += '</div>';
    newHTML += '<div class="form-field zip" style="width: 100px; float: left;">';
    newHTML += '<label for="state"><strong>Zip*</strong></label>';
    newHTML += '<input id="zip" type="text" name="zip" size="10" maxlength="20"/>';
    newHTML += '</div>';
    newHTML += '<div style="clear: both;"/>';
    
    newHTML += '<img src="'+baseUrl+'images/btn-update.jpg" onClick="updateProfile();" />';
    newHTML += "</div>";
    
    document.getElementById('myshipping').innerHTML = newHTML;
}
function updateEmail(){
	
	$("#changeEmail").slideToggle("slow");
}
function changeEmailConfirm(){
	newEmail = $("#email").val();
	  
	//Changing Email through Ajax Call
	  
    data = 'newEmail='+newEmail;
    
    $.ajax({
        type: 'POST',
        url: baseUrl+'/profile/changeemail/' ,
        data:data,                            
        success: function(msg) {
            if (msg == 'success'){
                alert('Your Email has been changed successfully');               
				newHTML = "<p><strong>Email:</strong> ";
				newHTML += newEmail;
				newHTML += "<img class='link' src='"+baseUrl+"/images/btn-editSmall.jpg'  onclick='updateEmail();'/>";
				newHTML += "</p>";
				$("#finalEmail").html(newHTML);
                $("#changeEmail").slideUp('slow');    
            } else {
				if(msg == 'double entry'){
					alert('The email address you used already has an account');
				}else{
					alert('Invalid Email. Please try again using a valid Email');	
				}
                
            }    
        },
        error: function(msg) {
            alert('Error: Couldnt change your Email Address');
        }
    })
}
function updateProfile(){
    first_name = $("#first_name").val();
    last_name = $("#last_name").val();
    address = $("#address").val();
    address_2 = $("#address_2").val();
    city = $("#city").val();
    state = $("#state").val();
    zip = $("#zip").val();
    
    if (first_name == ''){
        alert('You must enter a first name');
        return;
    }
    if(last_name == ''){
        alert('You must enter a last name');
        return;
    }
    if(address == ''){
        alert('You must enter an address');
        return;
    }
    if(city == ''){
        alert('You must enter a city');
        return;
    }
    if(state == ''){
        alert('You must enter a state');
        return;
    }
    if(zip == ''){
        alert('You must enter a zip');
        return;
    }
    //Creating data element
    data = 'first_name='+first_name;
    data += '&last_name='+last_name;
    data += '&address='+address;
    data += '&address_2='+address_2;
    data += '&city='+city;
    data += '&state='+state;
    data += '&zip='+zip;
    
    //Updating profile information through Ajax Call
    $.ajax({
        type: 'POST',
        url: baseUrl+'/profile/updateprofile/' ,
        data:data,                            
        success: function(msg) {                   
            document.getElementById('myshipping').innerHTML = msg;
            $("#newShipping").slideToggle("slow");
        },
        error: function(msg) {
            alert('Error: Couldnt update profile information');
            
        }
    })
}

function changePassword(){
    //$("#changePassBtn").slideUp('slow');
    $("#changePass").slideToggle('slow');
}

function changePassConfirm(){
    oldPass = $("#current_pass").val();
    newPass = $("#new_pass").val();
    confirmPass = $("#confirm_pass").val();
    
    if(newPass != confirmPass){
        alert('New Password does not match with confirm password');
        return;
    }
    
    //Changing password through Ajax Call
    data  = 'oldPass='+oldPass;
    data += '&newPass='+newPass;
    
    $.ajax({
        type: 'POST',
        url: baseUrl+'/profile/changePass/' ,
        data:data,                            
        success: function(msg) {
            if (msg == 'success'){
                alert('Your password has been changed successfully');               
                $("#changePass").slideUp('slow');    
            } else {
                alert('Invalid current password. Please try again using valid current password');
            }    
        },
        error: function(msg) {
            alert('Error: Couldnt change your password');
        }
    })
}