var FavoritesHandler = '/Frontend/Rudeco/Favorites.ashx';
var RudecoCookiesName = 'RuduceFavoritesCookies_RetailerId_';
function DataProvider() {
    this.AjaxHandler = '';
}

DataProvider.prototype.MakeRequest = function (data, onSuccessCallback) {
    jQuery.ajax({
        url: this.AjaxHandler,
        data: {
            objToDeserialize: data
        },
        success: function (data, textStatus) {
            try {
                if ($.isFunction(onSuccessCallback))
                    onSuccessCallback(data);
            }
            catch (e) {
                alert('Error');
            }
        }
    });
}
function Retailer() {
    this.strId = '';
    this.Id = new Object();
    this.Email = '';
    this.ShowProductPrice = new Boolean();
    this.Lang = 'da-DK';
}
function Product(id, name, identifier, price, currency) {
    this.Id = id;
    this.Identifier = identifier;
    this.Name = name;
    this.Price = price;
    this.Currency = currency;
}
function FavoriteItem(product, quantity) {
    this.Product = product;
    this.Quantity = quantity;
}
function FavoritesCollection() {
    this.Favorites = new Array();
}
function ContactInfo() { 
    this.FirstAndSurname = '';
    this.Company = '';
    this.Email = '';
	this.PhoneNumber = '';
	this.PreferredPhoneTime = '';
	this.Message = '';
	this.IncludeWishList = new Boolean();
}
function CookiesWrapper(obj) {
    this.Value = obj;
}
function FavoritesManager() {
    this.Retailer = new Retailer();
    this.TotalOrder = 0;
    this.ContactInfo = new ContactInfo();
    this.FavoritesCollection = new Array();
}
FavoritesManager.prototype.UpdateFavorites = function () {
    alert(this.TotalOrder);
}
FavoritesManager.prototype.ClearCookies = function () {
    $.JSONCookie(RudecoCookiesName, new CookiesWrapper(), { path: '/' });
    this.FavoritesCollection = new Array();
}
FavoritesManager.prototype.ClearFavoritesProducts = function () {
    $('.prod').remove();
    $('#totalOrder').remove();
}
FavoritesManager.prototype.InitFavoritesForm = function () {
    var count = this.FavoritesCollection.length;
    if(count < 1) {
        $('#Favs').hide();
    }
}
FavoritesManager.prototype.BuildProductsTable = function () {
    if (!this.Retailer.ShowProductPrice) {
        this.BuildProductsTableWithoutPrice();
        return;
    }

    var count = this.FavoritesCollection.length;
    var total = new Number();
    for (var i = 0; i < count; i++) {
        total = total + this.FavoritesCollection[i].Product.Price * this.FavoritesCollection[i].Quantity;
        $('#FavHead').append(
            '<ul class="prod">' +
				'<li id="name">' + this.FavoritesCollection[i].Product.Name + '</li>' +
				'<li id="identifier">' + this.FavoritesCollection[i].Product.Identifier + '</li>' +
				'<a class="a-decrease" href="#" rel="' + this.FavoritesCollection[i].Product.Id + '">' +
					'<li class="decrease">-</li>' +
				'</a>' +
				'<li id="quantity">' + this.FavoritesCollection[i].Quantity + '</li>' +
				'<a class="a-increase" href="#" rel="' + this.FavoritesCollection[i].Product.Id + '">' +
					'<li class="increase">+</li>' +
				'</a>' +
				'<li class="unitprice">' + $.formatNumber(this.FavoritesCollection[i].Product.Price, { format: "#,###.00", locale: "dk" }) + ' ' + this.FavoritesCollection[i].Product.Currency + '</li>' +
				'<li class="total">' + $.formatNumber(this.FavoritesCollection[i].Product.Price * this.FavoritesCollection[i].Quantity, { format: "#,###.00", locale: "dk" }) + ' ' + this.FavoritesCollection[i].Product.Currency + '</li>' +
			'</ul>'
            );
    }
    if (count > 0) {
        $('#FavHead').append(
            '<ul id="totalOrder"><li id="allinall">Total</li><li id="totalprice">' + $.formatNumber(total, { format: "#,###.00", locale: "dk" }) + ' ' + this.FavoritesCollection[0].Product.Currency + '</li></ul>'
        );
        this.CheckNotificationArrow();
    }
    this.TotalOrder = total;
    this.BindEvents();
    //this.InitFavoritesForm();
}
FavoritesManager.prototype.BuildProductsTableWithoutPrice = function () {
    var count = this.FavoritesCollection.length;
    var total = new Number();
    for (var i = 0; i < count; i++) {
        total = total + this.FavoritesCollection[i].Product.Price * this.FavoritesCollection[i].Quantity;
        $('#FavHead').append(
            '<ul class="prod">' +
				'<li id="name">' + this.FavoritesCollection[i].Product.Name + '</li>' +
				'<li id="identifier">' + this.FavoritesCollection[i].Product.Identifier + '</li>' +
				'<a class="a-decrease" href="#" rel="' + this.FavoritesCollection[i].Product.Id + '">' +
					'<li class="decrease">-</li>' +
				'</a>' +
				'<li id="quantity">' + this.FavoritesCollection[i].Quantity + '</li>' +
				'<a class="a-increase" href="#" rel="' + this.FavoritesCollection[i].Product.Id + '">' +
					'<li class="increase">+</li>' +
				'</a>' +
				'<li class="unitprice">' + '-' + '</li>' +
				'<li class="total">' + '-' + '</li>' +
			'</ul>'
            );
    }
    if (count > 0) {       
        this.CheckNotificationArrow();
    }
    this.TotalOrder = total;
    this.BindEvents();
    //this.InitFavoritesForm();
}
FavoritesManager.prototype.GetAjaxManager = function () {
    var provider = new DataProvider();
    provider.AjaxHandler = FavoritesHandler;
    return provider;
}
FavoritesManager.prototype.IsProductInFavorites = function (productId) {
    var count = this.FavoritesCollection.length;
    for (var i = 0; i < count; i++) {
        if (this.FavoritesCollection[i].Product.Id == productId) {
            return true;
        }
    }
    return false;
}
FavoritesManager.prototype.AddProductToFavorites = function (product) {
    if (this.IsProductInFavorites(product.Id)) {
        this.IncreaseProduct(product.Id);
    }
    else {
        var favorite = new FavoriteItem(product, 1);
        this.FavoritesCollection.push(favorite);
    }
    this.SaveFavorites();
}
FavoritesManager.prototype.RemoveProductFromFavorites = function (productId) {
    var count = this.FavoritesCollection.length;
    for (var i = 0; i < count; i++) {
        if (this.FavoritesCollection[i].Product.Id == productId) {
            this.FavoritesCollection.splice(i, 1);
        }
    }
    this.SaveFavorites();
}
FavoritesManager.prototype.IncreaseProduct = function (productId) {
    var count = this.FavoritesCollection.length;
    for (var i = 0; i < count; i++) {
        if (this.FavoritesCollection[i].Product.Id == productId) {
            this.FavoritesCollection[i].Quantity = this.FavoritesCollection[i].Quantity + 1;
        }
    }
}
FavoritesManager.prototype.DecreaseProduct = function (productId) {
    var count = this.FavoritesCollection.length;
    for (var i = 0; i < count; i++) {
        if (this.FavoritesCollection[i].Product.Id == productId) {
            if (this.FavoritesCollection[i].Quantity > 1) {
                this.FavoritesCollection[i].Quantity = this.FavoritesCollection[i].Quantity - 1;
            }
            else {
                this.RemoveProductFromFavorites(productId);
            }
        }
    }
}
FavoritesManager.prototype.RetrieveFavorites = function () {
    //alert(JSON.stringify($.JSONCookie(RudecoCookiesName)));
    var cookies = new CookiesWrapper();
    cookies = $.JSONCookie(RudecoCookiesName);
    this.FavoritesCollection = new Array();
    if (typeof cookies.Value != 'undefined') {
        this.FavoritesCollection = cookies.Value;
    }

    cookies = new CookiesWrapper();
    cookies = $.JSONCookie(RudecoCookiesName + '_retailer');
    if (typeof cookies.Value != 'undefined')
    {
        this.Retailer = cookies.Value;
    }
}
FavoritesManager.prototype.SaveFavorites = function () {
    var cookies = new CookiesWrapper();
    cookies.Value = this.FavoritesCollection;
    $.JSONCookie(RudecoCookiesName, cookies, { path: '/' });

    cookies = new CookiesWrapper();
    cookies.Value = this.Retailer;
    $.JSONCookie(RudecoCookiesName + '_retailer', cookies, { path: '/' });
}
FavoritesManager.prototype.HideFavoritesForm = function () {
    $('#minDiv').hide('slow');
}
FavoritesManager.prototype.UpdateCookiesNameWithRetailerId = function () {
    RudecoCookiesName = RudecoCookiesName + this.Retailer.strId;
}
FavoritesManager.prototype.CheckNotificationArrow = function () {
    $('#wishNotif').hide();
}
FavoritesManager.prototype.BindEvents = function () {
    var manager = this;
    jQuery("a.a-increase").each(
            function (intIndex) {
                $(this).bind(
                    "click",
                    function () {
                        var productId = $(this).attr("rel");
                        manager.IncreaseProduct(productId);
                        manager.SaveFavorites();
                        manager.ClearFavoritesProducts();
                        manager.BuildProductsTable();
                    }
                );
            }
     );
     jQuery("a.a-decrease").each(
            function (intIndex) {
                $(this).bind(
                    "click",
                    function () {
                        var productId = $(this).attr("rel");
                        manager.DecreaseProduct(productId);
                        manager.SaveFavorites();
                        manager.ClearFavoritesProducts();
                        manager.BuildProductsTable();
                    }
                );
            }
     );
}

jQuery(document).ready(function () {

    var manager = new FavoritesManager();
    manager.UpdateCookiesNameWithRetailerId();
    manager.RetrieveFavorites();
    //manager.CheckNotificationArrow();
    //manager.InitFavoritesForm();

    jQuery('#addToFavorites').click(function () {
        var details = $("#addToFavorites").attr("rel").split(',');
        var prod = new Product();
        prod.Id = details[0];
        prod.Name = details[1];
        prod.Identifier = details[2];
        prod.Price = details[3];
        prod.Currency = details[4];
        //retailer 
        var retailerContactEmail = $("#addToFavorites").attr("rel").split(',')[5];
        var retailerId = $("#addToFavorites").attr("rel").split(',')[6];
        var showProductPrice = details[7];
        var lang = $("#Favs").attr("culture");
        manager.Retailer.Id = retailerId;
        manager.Retailer.strId = retailerId;
        manager.Retailer.Email = retailerContactEmail;
        manager.Retailer.ShowProductPrice = showProductPrice == 'true' ? true : false;
        manager.Retailer.Lang = lang;

        manager.AddProductToFavorites(prod);
        manager.ClearFavoritesProducts();
        manager.BuildProductsTable();
        $('#wishNotif').show();
        $('#Favs').show();
    });
    jQuery('#showBtn').click(function () {
        manager.ClearFavoritesProducts();
        manager.BuildProductsTable();
        $('#minDiv').toggle();
    });
    jQuery('#btn').click(function () {
        if (IsFavoritesFormValid()) {
            manager.HideFavoritesForm();
            manager.ContactInfo = GetContactInfo();
            
            var lang = $("#Favs").attr("culture");
            manager.Retailer.Lang = lang;

            var dataProvider = manager.GetAjaxManager();
            dataProvider.MakeRequest(JSON.stringify(manager), function (data) { confirmFormSubmitting(data) });
        }
        return false;
    });
    jQuery('#hideBtn').click(function () {
        $('#minDiv').toggle();
        manager.CheckNotificationArrow();
    });
    function confirmFormSubmitting(data) {
        alert(data);
        manager.ClearCookies();
        manager.ClearFavoritesProducts();
        manager.BuildProductsTable();
    }
    function IsFavoritesFormValid() {
        var result = true;


        var nameBlank = $('#WName').attr('name');
        var companyBlank = $('#WCompany').attr('name');
        var emailBlank = $('#WEmail').attr('name');
        var phoneBlank = $('#WPhone').attr('name');
        var messageBlank = $('#WishListMessage').attr('name');

        var name = $('#WName').val();
        var company = $('#WCompany').val();
        var email = $('#WEmail').val();
        var phone = $('#WPhone').val();
        var message = $('#WishListMessage').val();

        if (name == nameBlank) {
            MarkFieldAsNotValid('#WName');
            result = false;
        }
        else {
            UnMarkField('#WName');
        }

        if (company == companyBlank) {
            MarkFieldAsNotValid('#WCompany');
            result = false;
        }
        else {
            UnMarkField('#WCompany');
        }

        var expr = new RegExp('[0-9a-z_]+@[0-9a-z_^\.]+\.[a-z]{2,3}');
        if (!expr.test(email.toLowerCase())) {
            MarkFieldAsNotValid('#WEmail');
            result = false;
        }
        else {
            UnMarkField('#WEmail');
        }

        if (phone == phoneBlank) {
            MarkFieldAsNotValid('#WPhone');
            result = false;
        }
        else {
            UnMarkField('#WPhone');
        }

        if ((message == '') || (message == messageBlank)) {
            MarkFieldAsNotValid('#WishListMessage');
            result = false;
        }
        else {
            UnMarkField('#WishListMessage');
        }
        return result;
    }
    function MarkFieldAsNotValid(fieldSelector) {
        $(fieldSelector).attr('style', 'border-color:#EC4847 !important;border-width:4px; !important');
    }
    function UnMarkField(fieldSelector) {
        $(fieldSelector).attr('style', '');
    }
    function GetContactInfo() {
        var contactInfo = new ContactInfo();
        contactInfo.FirstAndSurname = $('#WName').val();
        contactInfo.Company = $('#WCompany').val();
        contactInfo.Email = $('#WEmail').val();
        contactInfo.PhoneNumber = $('#WPhone').val();
        var contactTime = '';
        if ($('#time1').is(':checked')) {
            contactTime = '9-12; ';
        }
        if ($('#time2').is(':checked')) {
            contactTime = contactTime + '12-15'
        }
        contactInfo.PreferredPhoneTime = contactTime;
        contactInfo.Message = $('#WishListMessage').val();
        contactInfo.IncludeWishList = $('#IncludeWishCheck').is(':checked');

        return contactInfo;
    }
}); 
