/* Variation scripts */
var satchmo = satchmo || {};

satchmo.use_sale_prices = true;

// Get the current selected product price.
satchmo.get_current_price = function(detail, qty, use_sale) {
    var taxed = satchmo.default_view_tax,
        k;
            
    if (use_sale) {
        k = taxed ? "TAXED_SALE" : "SALE";
    }
    else {
        k = taxed ? "TAXED" : "PRICE";
    }
    
    var prices = detail[k];
    if (prices) {
        var best = prices['1'];
        if (qty > 1) {
            for (var pricekey in prices) {
                var priceqty = parseInt(pricekey,10);
                if (priceqty > qty) {
                    break;
                }
                best = prices[pricekey];
            }
        }
        return best;        
    }
    else {
        return "";
    }
};

satchmo.make_optionkey = function() {
    var work = Array(satchmo.option_ids.length);
    for (var ix=0; ix<satchmo.option_ids.length; ix++) {
        var k = "#" + satchmo.option_ids[ix];
        var v = $(k).fieldValue()[0];
        work[ix] = v;
    }
    return work.join('::');
};
        
// used for sorting numerically
satchmo.numeric_compare = function(a, b) {
    return a-b;
};
   
satchmo.option_ids = "";

satchmo.get_initial_options = function(){
    //Initial size options
    var initial_options = [];
    $('#'+satchmo.option_ids[1] + ' option').each(function() {
        initial_options.push($(this).val());
    });
    
    return initial_options;  
};
        
// Update the product name
satchmo.set_name = function(name) {
    $("#productname").attr('value', name);
};

satchmo.set_option_ids = function(arr) {
    arr.sort(satchmo.numeric_compare);
    satchmo.option_ids = arr;
};

// Update the product price
satchmo.set_price = function(price) {
    $("#price").text(price);
};

satchmo.show_error = function(msg) {
    var section = $('#js_error');
    if (section.length === 0) {
        if (msg != "") {
            $('form#options').before("<div id='js_error' class='error'>" + msg + "</div>");
        }
    }
    else {
        section.html(msg);
        if (msg == "") {
            section.hide();
        }
        else {
            section.show();
        }
    }
    var disabled = (msg != "");
    if (disabled){
        $('#buy_button').attr('src', '/media/static/img/buy-off-state.png');
    }
    
    else {
        $('#buy_button').attr('src', '/media/static/img/buy.jpg');
    }
    $('#buy_button').toggleClass('disabled', disabled);
    $('#buy_button').attr('disabled', disabled);
};

satchmo.update_options = function(){
    //Init
    $('#'+satchmo.option_ids[1]).children().remove().end();
    for(var i in satchmo.initial_options){
        $('#'+satchmo.option_ids[1]).append('<option value="'+ satchmo.initial_options[i] +'">' + satchmo.initial_options[i] + '</option>');
    }
    
    var select_options = new Array();
    $.each(satchmo.variations, function(key, value) {
        if(key != 'SALE'){
    		if (parseInt(value['QTY']) >= 0){
    			var option = key.split("::");
    			var option_values = {};
    			option_values["color"] = option[0];
    			option_values["size"] = option[1];
    			select_options.push(option_values);
    		}
    	}
    });
    
    var selected_color = $('#1 option:selected').val();
    
    var tmp_option = [];
    for(i=0; i<select_options.length;i++){
        if(select_options[i].color == selected_color){
            tmp_option.push(select_options[i].size);
        }
    }
    
    var lookup = {};
    for (var j in tmp_option) {
        lookup[tmp_option[j]] = tmp_option[j];
    }
      
    for (i in satchmo.initial_options) {
        if (typeof lookup[satchmo.initial_options[i]] == 'undefined') {
            $('#'+satchmo.option_ids[1]).find('option:contains('+ satchmo.initial_options[i] +')').remove();
        } 
    }
};
    
// update name and price based on the current selections
satchmo.update_price = function() {
    $('#restock').hide();
    $("#id_id").val('');
    $("#id_opts").val('');
    var key = satchmo.make_optionkey(),
        detail = satchmo.variations[key],
        msg = "",
        use_sale, sale_price, full_price;
        
    if (detail) {
        var qty = parseInt($('#quantity').fieldValue()[0],10);
        satchmo.set_name(detail['SLUG']);
        
        if (!satchmo.variations['SALE']) {
            use_sale = false;
        }
        else {
            use_sale = satchmo.use_sale_prices;
        }

        if (use_sale) {
            full_price = satchmo.get_current_price(detail, qty, false);
            $('#fullprice').text(full_price);
            $('#price').addClass('sale_text');
            $('#sale_img').show();

            sale_price = satchmo.get_current_price(detail, qty, true);
        }
        else {
            sale_price = satchmo.get_current_price(detail, qty, false);
            $('#fullprice').hide();
            $('#price').removeClass('sale_text');
            $('#sale_img').hide();
        }

        satchmo.set_price(sale_price);

        if (qty && qty > detail['QTY']) {
            if (detail['QTY'] == -1 || detail['QTY'] == 0) {
                msg = "SOLD OUT";
                $('#restock').show();
                $("#id_id").val(satchmo.product_id);
                $("#id_opts").val($('#1 option:selected').text() + ' - ' + $('#'+satchmo.option_ids[1]+' option:selected').val());
             }
             else {
                 msg = "we're sorry, we only have " + detail['QTY'] + " available in that color/size combination.";
                 $('#restock').show();
                 $("#id_id").val(satchmo.product_id);
                 $("#id_opts").val($('#1 option:selected').text() + ' - ' + $('#'+satchmo.option_ids[1]+' option:selected').val());
             }
        }
    }
    else {
        msg = "SOLD OUT";
        $('#restock').show();
    }
    satchmo.show_error(msg);
};

/* AJAX Cart add scripts */

var AO = {
    // Set status div to current values.
    set_status: function(){
        var price = $('#price').html();
        $('#status_price').html(price);
        var qty = 'Qty: '+ $('#quantity').val();
        $('#status_qty').html(qty);
        var size = 'Size: ' + $('#'+satchmo.option_ids[1]+' option:selected').text();
        $('#status_option_size').html(size);
        var color = 'Color: ' + $('#1 option:selected').text();
        $('#status_option_color').html(color);
    },
    
	// handle a form submission
	// including updating the cart quantity
    updatestatus : function(json, result_tgt, count_tgt) {
        var result = json.results;
        if (result == "Success") {
            result = 'Item added to cart!';
            $(result_tgt+" h4").html(result);
        }
        else {
            error_msg = json.errors[0][1];
            $(result_tgt+" h4").html(error_msg);
        }
        
        errors = json.errors;
        if (errors > 0) {
            for (var i = 0; i<errors.length; i++) {
                which = errors[i][0];
                err = errors[i][1];
                if (which == 'quantity') {
                    $('#label-quantity span.error').html(err);
                }
                else if (which == 'product') {
                    var t = tgt.html();
                    tgt.html(t + '<br/>' + err);
                }
            }
        }
        else {
            var ct = '(' + json.cart_count + ')';
            $(count_tgt).html(ct);
        }
    },

    validate : function(formArray, jqForm, tgt) {
        var qty = 0;
        for (var i = 0; i<formArray.length; i++) {
            var elt = formArray[i];
            if (elt.name == 'quantity') {
                qty = elt.value;
            }
        }
        if (parseInt(qty,10)<=0) {
            $('#label-quantity span.error').html("Choose a quantity");
            return false;
        }
        return true;
    }
};

var status_update = {
    close: function (dialog) {
        $.modal.close();
        $('#status_update').css("visibility", "hidden");
        location.reload();
    }
};

function validate_email(formdata, jqform, options) {
    var email = formdata[0].value;
    if ((email.indexOf(".") > 2) && (email.indexOf("@") > 0)){
        return true;
    }
    else {
        alert('Please enter a valid email address!');
        return false;
    }
}