﻿///<reference path="jquery-1.2.6.js">

/* Form validation and help */

var defOffColor = "#C6B6A3";
var offColor = defOffColor;
var errColor = "#E673A0";
$(function() {
    $(".checkoutOrder input[title]").each(function() {
        if ($(this).val() == "")
            $(this).val($(this).attr("title"));
        $(this).css("color", offColor);
        this.blurval = function() {
            if ($(this).val() == "") {
                $(this).val($(this).attr("title"));
                var color = offColor;
                if (this.id == "phone" || this.id == "addressCont" || this.id == "country")
                    color = defOffColor;
                $(this).css("color", color);
                if (color == errColor)
                    $(this).addClass("validationFailed");
            }
        };
        this.focusval = function() {
            if ($(this).val() == $(this).attr("title"))
                $(this).val("");
            $(this).css("color", "#7E5F3D");
            $(this).removeClass("validationFailed");
        }
        $(this).blur(this.blurval);
        $(this).focus(this.focusval);
    });

    var cbVal = function() {
        if ($("#cbTerms").attr("checked"))
            $("#CheckBox").addClass("checked");
        else
            $("#CheckBox").removeClass("checked");
    };
    $("#CheckBoxLink").click(function() {
        $("#cbTerms").click();
        cbVal();
    });
    cbVal();
    var cb = $("#CheckBox");
    if (cb.length > 0) {
        cb[0].blurval = function() {
            if ($(this).hasClass("checked"))
                $("#terms").css("color", "#7E5F3D");
            else if (offColor == errColor)
                $("#terms").css("color", errColor);
        };
        cb[0].focusval = function() { };
    }
});

function Validate() {
    offColor = errColor;


    $(".checkoutOrder input[title],#CheckBox").each(function() { this.focusval(); this.blurval(); });
    var ok = Req("firstName") && Req("lastName") && Req("email") &&
    Req("address") && Req("city") && Req("postalCode") && $('#CheckBox').hasClass("checked") && ValidEmail("email");

    if (!ValidEmail("email")) {
        var m = $("input[id$=email]");
        m.addClass("validationFailed");
    }
    
    if (!ok)
        $("#valSummary").show();
    else
        $("#valSummary").hide();
    return ok;
}

function Req(endId) {
    var i = $("input[id$=" + endId + "]");
    return $.trim(i.val()) != "" && i.val() != i.attr("title");
}

function ValidEmail(email) {
    var i = $("input[id$=" + email + "]");

    var myRegex = new RegExp("[a-z0-9._åäö]+@[a-z0-9._åäö]+\.[a-z0-9._åäö]{2,4}", "g");
    return myRegex.test(i.val());

}



$(function() {
    BindFields();
    switch (currentPage) {
        case "Shop": ProductList(BuildCart);
            break;
        case "Checkout": ProductList(BuildCheckout);
            break;
        case "Confirm": ProductList(BuildConfirm);
    }
});



var callback;



// *****************
// AJAX - anrop
// *****************
function ProductList(callbackFunction)
{
    
	callback = callbackFunction;
	$.ajax({type:'POST',url:'/Framework/Json/Shop/CartFeed.aspx',data:'action=list',dataType:'json',success: callback });
}

function RemoveProduct(GUID)
{
	$.ajax({type:'POST',url:'/Framework/Json/Shop/CartFeed.aspx',data:'action=remove&id='+GUID,dataType:'json',success: callback });
}

function AddProduct(pid)
{
	var add = $('#item' + pid + " select").val();
	var q = $('#item' + pid + " input").val();

	$.ajax({type:'POST',url:'/Framework/Json/Shop/CartFeed.aspx',data:'action=add&pid='+pid+'&q='+q+'&add='+add,dataType:'json',success: callback });
}

function UpdateItem(GUID, quantity, callbackFunction)
{
    $.ajax({ type: 'POST', url: '/Framework/Json/Shop/CartFeed.aspx', data: 'action=update&id=' + GUID + '&q=' + quantity, dataType: 'json', success: callbackFunction });
}

function SubmitOrder() {
    //Remove title texts
    $("input").filter(function() { return $(this).val() == $(this).attr("title"); }).val("");
    $('.thankyou').removeClass("offscreen");

    $("#orderForm").ajaxSubmit({
    success: function() {
            $('#formHeaderConfirm').css("left", "-1500px");
            $(".formHeader").addClass("offscreen");
            $(".checkoutOrder").addClass("offscreen");
            $('.thankyou .wait').hide();
            $('.thankyou .confirmation').removeClass("offscreen");
        },
        error: function() {
            location.href = "/error";
        }
    });
}

// *****************
// Olika carts
// *****************
function BuildCart(cart) {
    $('#CurrentCart').empty();
    if (cart.items.length > 0) {
        $.each(cart.items, function(i) {
            var output = '<tr><td class="col2"><span class="col1">{0}</span>{1}{2}</td><td class="col3"><a href="#" onclick="RemoveProduct(\'' + this.guid + '\')"><img src="/media/images/shop_removeCartItem.gif" alt="remove {1} from the shopping cart" /></a></td></tr>';
            this.additional = (this.additional != "undefined") ? Format(" ({0})", this.additional) : "";
            $('#CurrentCart').prepend(Format(output, this.quantity, this.name, this.additional));
        });
        $('.fullCart').show(0);
        $('.emptyCart').hide(0);
        $('#CartValue').text(cart.totalvalue);
       
    } else {
        $('.fullCart').hide(0);
        $('.emptyCart').show(0);
    } 
}

function BuildCheckout(cart)
{
    $('.productRepresentationBar').remove();
	$.each(cart.items, function(i) {

	    this.additional = (this.additional != "undefined") ? Format(" ({0})", this.additional) : "";
	    var output = '<div class="productRepresentationBar" id="{4}" style="overflow:hidden"><div class="panel"><span class="topLeftSmall"></span><span class="topRightSmall"></span><span class="bottomLeftSmall"></span><span class="bottomRightSmall"></span><span class="product alignLeft">{0}{3}</span> <div class="alignRight"><span class="quantity"> Quantity: </span><input type="text" value="{1}" onkeyup="ChangeQuantity(\'{4}\',this.value,{5})" /> <span class="price">Price: <span class="priceValue">{2}</span></span> <span class="currency">SEK</span></div></div><a href="#" style="width:80px" onclick="RemoveProduct(\'{4}\')"><img src="/media/images/shop_removeCartItem.jpg" alt="remove {0} from your shopping cart" /></a></div>';

	    $('#productChoices').prepend(Format(output, this.name, this.quantity, this.totalvalue,this.additional,this.guid,this.value));
	});

	$('#CartValue').text(cart.totalvalue);
}

function BuildConfirm(cart) {
   $('.productRepresentationBar').remove();

    $.each(cart.items, function(i) {
        this.additional = (this.additional != "undefined") ? Format(" ({0})", this.additional) : "";
        var output = '<div class="productRepresentationBar" id="{4}"><div class="panel expandWidth"><span class="topLeftSmall"></span><span class="topRightSmall"></span><span class="bottomLeftSmall"></span><span class="bottomRightSmall"></span><span class="product alignLeft">{0}{3}</span><div class="alignRight"><span class="quantity"> Quantity: </span><span class="inputRepacement">{1}</span> <span class="price">Price: {2}</span><span class="currency">SEK</span></div></div></div>';

        $('#productChoices').prepend(Format(output, this.name, this.quantity, this.totalvalue, this.additional, this.guid, this.value));
    });

	$('#CartValue').text(cart.totalvalue);
}

// ***************************************
// Funktioner som uppdaterar element
// ***************************************
function ChangeQuantity(id, value, unitPrice)
{
	if(Math.ceil(value) != Math.floor(value))
		value = 0;

if (value > 0) {
    $('#' + id + ' .priceValue').text(value * unitPrice);
    $('#CartValue').text(TotalCartValue());
}   
}

function TotalCartValue()
{
    var summa = 0;
    $('.priceValue').each(function(i) {
        summa += parseInt($(this).text());
    });

    return summa;
}

function ChangeOrder()
{
    $('.confirmOrder').css("display", "none");
    $('.checkoutOrder').css("display", "inline");
    ProductList(BuildCheckout);
    $('fieldset.paperForm').removeClass("confirmed");
    $('#formHeader').css("left", "");
    $('#formHeaderConfirm').css("left", "-1500px");

}

function PlaceOrder()
{
    if (!Validate())
        return;
    
    var items = $('.productRepresentationBar')
    $.each(items, function(i) {
        var guid = $(this).attr("id");
        var quantity = $('#' + guid + ' input').val();

        UpdateItem(guid, quantity, BuildConfirm);
    });
    
    $('.confirmOrder').show();
    $('.checkoutOrder').hide();

    $('fieldset.paperForm').addClass("confirmed");
    $('#formHeaderConfirm').css("left", "");
    $('#formHeader').css("left", "-1500px");

}

// ***************************************
// Utils och binds
// ***************************************

function Format(str)
{
    for (i = 0; i < arguments.length; i++)
    {
        var myRegex = new RegExp("\\{" + i + "\\}", "g");
        str = str.replace(myRegex, arguments[i+1]);
    }
    return str;
}


function BindFields() // länkar elements värde med ett annat
{
    $('.checkoutOrder input').each(function(e) {
        $(this).bind("change", null, function(e) {
        $('.confirmOrder #' + $(this).attr("id")).text($(this).val());
        });

    });

}