﻿/*
    functions for handling favorites
    Richard Appelgren, Zooma By Semcon 2008
*/

var favorites = new Object();

favorites.PanelSelector = '#FavoritesPanel';
favorites.PanelListItemsSelector = '#FavoritesPanelFavoritesList .item';
favorites.PanelListItemPrefixSelector = '#FavoritesPanelListItem';
favorites.MenuButtonSelector = '#FavoritesButton';
favorites.MenuCountSelector = '#FavoritesMenuCount';
favorites.EmailPanelSelector = '#FavoritesPanelEmailPanel';
favorites.PanelListItemsElementSelector = '#FavoritesPanelFavoritesList';

favorites.panelItemsCurrentIndex = 0;
favorites.cookieName = 'FavoritesCookie';
favorites.isLoaded = false;
favorites.defaultSepPrefixChar = '|';
favorites.defaultSepChar = ',';
favorites.templateContent = null;

favorites.load = function() {
    // code to load all this via ajax/webservice
    if (favorites.isLoaded) {
        return;
    }

    var arrItems = favorites.getItems();

    if (arrItems == null || (arrItems.length == 0)) {
        $('#FavoritesPanelTotalSum').text('0,00');
        return;
    }

    favorites.panelItemsCurrentIndex = 0;

    // now contact a webservice, send in those values and get
    var strArtNoValues = '';
    for (var i = 0; i < arrItems.length; i++) {
        strArtNoValues += arrItems[i] + favorites.defaultSepChar;
    }
    
    var strJsonInData = "{'strArtNoValues':'" + strArtNoValues + "','strLangCode':'" + EPI_CURRENT_LANG_CODE + "','strMarketCode':'" + EPI_CURRENT_MARKET_CODE + "'}";
    $.ajax({
        type: "POST",
        url: common.miscServiceUrl + '/GetFavoritesData',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: strJsonInData,
        timeout: common.ajaxTimout,
        success: function(indata) {
            if (common.isValue(favorites.templateContent)) {
                $(favorites.PanelListItemsElementSelector).setTemplate(favorites.templateContent);
                $(favorites.PanelListItemsElementSelector).processTemplate(indata.d);

                $('#FavoritesPanelTotalSum').text($('#FavoritesPanelTotalPriceWithCurrency').val());
                favorites.isLoaded = true;
            }
            else {
                // make another webservice call to collect data from the template
                var __strFullTemplateUrl = common.jqueryTemplatesBaseUrl + 'FavoritesPanelItems.txt';
                $.ajax({
                    url: __strFullTemplateUrl,
                    timeout: common.ajaxTimout,
                    success: function(strFileContent) {
                        $(favorites.PanelListItemsElementSelector).setTemplate(strFileContent);
                        $(favorites.PanelListItemsElementSelector).processTemplate(indata.d);
                        favorites.templateContent = strFileContent;
                        $('#FavoritesPanelTotalSum').text($('#FavoritesPanelTotalPriceWithCurrency').val());
                        favorites.isLoaded = true;
                    },
                    error: function(msg1, a1, b1) {
                        alert('error, please reload the page and try again.');
                    }                    
                });
            }
            

            /*
            $(favorites.PanelListItemsElementSelector).setTemplateURL(common.jqueryTemplatesBaseUrl + 'FavoritesPanelItems.html');
            $(favorites.PanelListItemsElementSelector).processTemplate(indata.d);

            // now, get the total count of prices
            $('#FavoritesPanelTotalSum').text($('#FavoritesPanelTotalPriceWithCurrency').val());

            favorites.isLoaded = true;
            // note; investigate the possibillities to use some sort of event handling, and do this when the render of html is done
            // productdetails.toggleLoading(false);
            */
        },
        error: function(msg, a, b) {
            alert('error, please reload the page and try again');
        }
    });
}

favorites.remove = function(e) {
    var strArtNo = (common.isValue(e) && common.isValue(e.data)) ? e.data : null;

    if (strArtNo == null) {
        return false;
    }

    var strValues = common.getCookieValue(favorites.cookieName);
    var strNewValue = favorites.defaultSepPrefixChar + strArtNo + favorites.defaultSepChar;
    strValues = common.isValue(strValues) ? strValues : null;
    if (strValues != null) {
        if (strValues.indexOf(strNewValue) > -1) {
            strValues = strValues.replace(strNewValue, '');
        }
    }
    common.setCookie(favorites.cookieName, strValues);

    // removes all the html in the list
    $(favorites.PanelListItemsSelector).replaceWith('');

    favorites.isLoaded = false;

    $(favorites.MenuCountSelector).html('(' + favorites.count() + ')');

    // reload it, its the easist way to update all of it
    favorites.load();

    return false;
}
favorites.add = function(id) {
    // send in a id and save it to cookies
    var strValues = common.getCookieValue(favorites.cookieName);
    var strNewValue = favorites.defaultSepPrefixChar + id + favorites.defaultSepChar;
    strValues = common.isValue(strValues) ? strValues : null;

    if (strValues == null) {
        strValues = strNewValue;
    }
    else {
        if (strValues.indexOf(strNewValue) == -1) {
            strValues += strNewValue;
        }
    }
    common.setCookie(favorites.cookieName, strValues);
    $(favorites.MenuCountSelector).html('(' + favorites.count() + ')');
    favorites.isLoaded = false;
    favorites.toggleFavoritesPanel(false);
    return false;
    // maybe do an autoload when this is done
}
favorites.count = function() {
    // count the cookies
    var arrItems = favorites.getItems();
    if(arrItems != null) {
        return arrItems.length;
    }
    return 0;

}
favorites.getItems = function() {
    // make the cookies an array of identities
    var strValues = common.getCookieValue(favorites.cookieName) + '';
    if (common.isValue(strValues)) {
        var arr1 = strValues.split(favorites.defaultSepChar);
        var arr2 = [arr1.length-1];
        
        for (var i = 0; i < arr1.length; i++) {
            if (common.isValue(arr1[i])) {
                arr2[i] = arr1[i].replace(favorites.defaultSepPrefixChar, '');
            }
        }
        return arr2;
    }
    return null;
}

favorites.bottomMenuClick = function(e) {
    var setVisible = $(favorites.PanelSelector).css('display') == 'none';
    favorites.toggleFavoritesPanel(setVisible);
    return false;
}
favorites.toggleFavoritesPanel = function(setVisible) {
    if (setVisible) {
        favorites.load();
        $(favorites.PanelSelector).fadeIn(1000, function() { });
        $(favorites.MenuButtonSelector).parent().addClass('active');
        favorites.emailClick(true);
    }
    else {
        $(favorites.PanelSelector).fadeOut(1000, function() { });
        $(favorites.MenuButtonSelector).parent().removeClass('active');
    }
    return false;
}
favorites.panelNextClick = function() {
    if (!favorites.isLoaded) return false;

    var items = $(favorites.PanelListItemsSelector);
    var itemCount = items.length;
    if ((itemCount < 9) || favorites.panelItemsCurrentIndex + 8 == itemCount) return false;
    
    $(items[favorites.panelItemsCurrentIndex]).css('display', 'none');
    favorites.panelItemsCurrentIndex++;

    return false;
}
favorites.panelPrevClick = function() {
    if (!favorites.isLoaded || favorites.panelItemsCurrentIndex == 0) return false;

    var items = $(favorites.PanelListItemsSelector);
    favorites.panelItemsCurrentIndex--;
    $(items[favorites.panelItemsCurrentIndex]).css('display', 'block');

    return false;
}
favorites.emailClick = function(bForceClose) {
    bForceClose = (common.isValue(bForceClose) && bForceClose == true) ? true : false;
    var setVisible = $(favorites.EmailPanelSelector).css('display') == 'none' && !bForceClose;
    if(setVisible) {
        $(favorites.EmailPanelSelector).fadeIn(1000, function() { });
    }
    else {
        $(favorites.EmailPanelSelector).fadeOut(1000, function() { });
    }
    return false;
}

favorites.sendEmailClick = function() {

    var objYourName = document.getElementById('FavoritesPanelTAFYourName');
    var objYourEmail = document.getElementById('FavoritesPanelTAFYourEmail');
    var objFriendEmail = document.getElementById('FavoritesPanelTAFFriendEmail');
    var objMessage = document.getElementById('FavoritesPanelTAFMessage');

    // do some basic validation before sending the package

    // get all data the this SendToAFriend needs
    var arrItems = favorites.getItems();
    if (arrItems == null || (arrItems.length == 0)) {
        return;
    }

    var strArtNoValues = '';
    for (var i = 0; i < arrItems.length; i++) {
        strArtNoValues += arrItems[i] + favorites.defaultSepChar;
    }

    var strJsonInData = "{'strPageID':'" + EPI_CURRENT_PAGE_ID + "','strYourName':'" + objYourName.value + "','strYourEmail':'" + objYourEmail.value + "','strFriendEmail':'" + objFriendEmail.value + "','strPersonalMessage':'" + objMessage.value + "','strArtNoValues':'" + strArtNoValues + "','strLangCode':'" + EPI_CURRENT_LANG_CODE + "','strMarketCode':'" + EPI_CURRENT_MARKET_CODE + "','strProductDetailsUrlExt':'" + EPI_CURRENT_PRODUCT_DETAILS_URL_EXT + "','strSiteUrl':'" + EPI_CURRENT_BASE_URL + "'}";
    //alert(strJsonInData);
    $.ajax({
        type: "POST",
        url: common.miscServiceUrl + '/FavoritesSendTellAFriendEmail',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: strJsonInData,
        timeout: common.ajaxTimout,
        success: function(indata) {
            //alert('success:' + indata);
            favorites.emailClick(true);
        },
        error: function(msg, a, b) {
            //alert('error:' + b);
            favorites.emailClick(true);
        }
    });

    return false;
}

favorites.printClick = function() {
    window.open(EPI_CURRENT_PRINT_FAVORITES, 'PrintFavorites');
    return false;
}
favorites.productClick = function(e) {
    var strArtNo = (common.isValue(e) && common.isValue(e.data)) ? e.data : null;

    if (strArtNo == null) {
        return false;
    }

    productdetails.open({ data: strArtNo });
    productdetails.toggleNextPrevDisplayNav(false);
    return false;
}


// bind event handlers for favorites specific events
$(document).ready(function() {
    $('#FavoritesPanelButtonNext').bind('click', favorites.panelNextClick);
    $('#FavoritesPanelButtonPrev').bind('click', favorites.panelPrevClick);
    $('#FavoritesButton').bind('click', favorites.bottomMenuClick);
    $('#FavoritesMenuCount').html('(' + favorites.count() + ')');
    $('#FavoritesPanelEmailButton').bind('click', favorites.emailClick);
    $('#FavoritesPanelPrintButton').bind('click', favorites.printClick);
    $('#FavoritesPanelCloseButton').bind('click', favorites.bottomMenuClick);

    $('#FavoritesPanelEmailPanelSendEmail').bind('click', favorites.sendEmailClick);
});
