﻿///Just English version of some controls

var langPack2 = {
    "loginFailed": "Въвели сте грешна парола или email!",
    "loginEmailUsed": "Вече има регистрация с този email! ({0})",    
    "passwordSent": "Вашата парола беше изпратена успешно!",
    "passwordChanged": "Вашата парола беше променена успешно!",
    "userAddressView": "<div><h3>Получател:</h3></div><div>{0} {1}</div><div>{2}, {3}</div><div><h3>За контакт:</h3></div><div>телефон: {4}</div>",
    "orderConfirmTip": "За да можете да приключите Вашата поръчка моля попълнете точен адрес за доставка!",
    "orderConfirmTip2": "Поръчката е готова за изпълнение! Натиснете бутона 'Приключи поръчката!' за да финализирате Вашата покупка.",
    "errorDefault": "Грешка: Моля опитайте отново!",
    "addToCart": "Добави в покупки",
    "pleaseWait": "Моля изчакайте",
    "addToCartSuccess": "Успешна покупка!",
    "pleaseWait": "Моля изчакайте!",
    "pleaseSelect": "Моля изберете",
    "save": "Запази",
    "deleteThis": "Изтрий",
    "edit": "Редактирай",
    "setProductCategory": "Добавяне на категория",
    "setProductAttribute": "Добавяне на атрибути",
    "categoryDialogTitle": "Редакция на категория",    
    "categoryDeleteConfirm": "Сигурни ли сте, че искате да изтриете тази категория?",    
    "categoryArchiveConfirm": "Внимание!!!\nТази категория не може да бъде изтрита, но може да бъде архивирана.\nАко желаете да архивирате тази категория натиснете Ok.\n\nВнимание!!!\nТова ще архивира всички под категории!",
    "attributeDeleteConfirm": "Сигурни ли сте, че искате да изтриете този атрибут?",    
    "attributeArchiveConfirm": "Внимание!!!\nТози атрибут не може да бъде изтрит, но може да бъде архивиран.\nАко желаете да архивирате този атрибут натиснете Ok.\n\nВнимание!!!\nТова ще архивира всички под атрибути!",
    "Attributes": "Атрибути",
    "Categories": "Категории",
    "attributeDialogTitle": "Редакция на атрибут",
    "Edit": "Редактирай",    
    "Delete": "Изтрий",
    "priceSimple": "{0} лв.",
    "selectItem": "Изберете: {0}",
    "editProductImage": "Редакция на изображение"
};

var langPack = {
    "selected": "Избрано",
    "goToCart": "Към Вашите покупки",
    "outOfStock": "Няма наличност от тази стока!",
    "attributeTip": "Изберете желания цвят и размер!",       
    "fieldRequired": "Задължително поле!",
    "fieldInvalid": "Невалидно поле!",
    "fieldInvalidEmail": "Невалиден email!",     
    "fieldInvalidPasswordMatch": "Паролите не съвпадат!",
    "fieldInvalidPasswordShort": "Въведете минимум 6 символа!",
    "loginSuccess": "Успешен вход!",
    "userLogin": "Вход за клиенти",
    "userRegister": "Бърза регистрация!",
    "loginLogIn": "Вход",
    "loginLogOut": "Изход",
    "txtSave": "Запази",
    "loginEmailUsed": "",              
    "statePleaseWait": "Моля изчакайте!",
    "stateDone": "Успешна покупка!",
    "stateDefault": "Добави в покупки",
    "cartShippingTip_1": "Остават {0} лв. до безплатна доставка!",
    "cartShippingTip_2": "Безплатна доставка с комплименти от BulBel.bg!",    
    "passwordSent": "Вашата парола беше изпратена успешно!",
    "passwordNotSent": "Няма регистрация с този email!",
    "retreiveEmailText": "Изпрати парола",
    "fieldInvalidPhone": "Моля въведете само цифри!",
    "passwordChangedError": "Грешна парола!",
    "passwordChange": "Смени паролата",    
    "helpSystemTitle": "Помощ - ",
    "contactForm": "Изпратете ни съобщение",
    "sendEmail": "Изпрати съобщение",
    "emailSent": "<h3>Вашето съобщение беше изпратено успешно!</h3> Благодарим за интереса към нашите услуги. Ще отговорим на Вашите въпроси при първа възможност.",
    "fieldInvalidValue": "Невалидна стойност!",
    "orderAdministration": "Администрация на поръчката",
    "userAdministration": "Администрация на потребителя",    
    "attributeUpdateParentConfirm": "Сигурни ли сте, че искате да запазите ''{0}'', като родител на този атрибут?",
    "attributeDeleteConfirm": "Сигурни ли сте, че искате да изтриете този атрибут?",    
    "attributeArchiveConfirm": "Внимание!!!\nТози атрибут не може да бъде изтрит, но може да бъде архивиран. Ако желаете да архивирате този атрибут натиснете Ok.",
    "attributeProductDelete": "Сигурни ли сте, че искате дa премахнете връзката между тaзи група атрибути и продукта?",
    "attrDialogTitle": "Редакция на атрибут",
    "catDialogTitle": "Редакция на категория",    
    "categoryUpdateParentConfirm": "Сигурни ли сте, че искате да запазите ''{0}'', като родител на тази категория?",
    "categoryDeleteConfirm": "Сигурни ли сте, че искате да изтриете тази категория?",    
    "categoryArchiveConfirm": "Внимание!!!\nТази категория не може да бъде изтрита, но може да бъде архивирана. Ако желаете да архивирате тази категория натиснете Ok.",
    "categoryProductDelete": "Сигурни ли сте, че искате дa премахнете връзката между тази категория и продукта?",
    "imageProductDelete": "Сигурни ли сте, че искате да изтриете това изображение?",
    "catDialogTitle": "Редакция на категория",
    "txtDuplicateProductAttributes": "Повтаряща се комбинация от атрибути!",
    "txtProductInventoryDeleteConfirm": "Сигурни ли сте, че искате да изтриете този инвентарен запис?",
    "txtProductInventoryDeleteError": "Този инвентарен запис не може да бъде изтрит защото участва в една или повече поръчки!",
    "txtEdit": "Редактирай",    
    "txtSelectItem": "Изберете: {0}",   
    "txtDelete": "Изтрий"   
};

var siteSettings = {
    "stateOrderFinished": "2",
    "maxPurchaseQuantity": "5",
    "outOfStock": "Няма наличност от тази стока!",
    "attributeTip": "Изберете желания цвят и размер!",
    "fieldRequired": "Задължително поле!",
    "freeShipping": "69.90"
};

var adminLangPack = {
    "deleteItem" : "Изтрий",
    "addSuccess": " беше добавен успешно!",
    "deleteError": "Грешка при изтриване на ",
    "deleteSuccess": " беше изтрит успешно!",
    "deleteConfirm": "Сигурни ли сте, че искате да изтриете ",
    "addItem" : "Добави",
    "addChildAttribute" : "Добави под-атрибут",
    "addChildCategory" : "Добави под-категория",
    "addError" : "Грешка при добавяне!",
    "editItem" : "Редактирай",
    "productBatchDelete" : "Сигурни ли сте че искате да изтриете избраните продукти?\nПродуктите, които не могат да бъдат изтрити ще бъдат архивирани!",
    "productArchiveConfirm" : "Сигурни ли сте че искате да архивирате избраните продукти?",
    "productArchiveConfirm2" : "Продукт #{0} не може да бъде изтрит. Желаете ли да бъде архивиран?", 
    "productBatchDeactivate" : "Сигурни ли сте че искате да деактивирате избраните продукти?",
    "productBatchActivate" : "Сигурни ли сте че искате да активирате избраните продукти?", 
    "productBatchArchive" : "Сигурни ли сте че искате да архивирате избраните продукти?" ,
    "productBatchUnarchive" : "Сигурни ли сте че искате да разархивирате избраните продукти?",
    "productBatchProductCategoryDelete" : "Сигурни ли сте че искате да изтриете категория ''{0}'' от избраните продукти?",
    "productBatchProductCategoryAdd" : "Сигурни ли сте че искате да добавите категория ''{0}'' към избраните продукти?",
    "categoryProductDelete": "Сигурни ли сте, че искате дa премахнете връзката между тази категория и продукта?",
    "attributeProductDelete": "Сигурни ли сте, че искате дa премахнете връзката между тaзи група атрибути и продукта?",
    "productInventoryDeleteConfirm": "Сигурни ли сте, че искате да изтриете този инвентарен запис?",
    "productInventoryDeleteError": "Този инвентарен запис не може да бъде изтрит защото участва в една или повече поръчки!",
    "duplicateProductAttributes": "Повтаряща се комбинация от атрибути!",
    "imageProductDelete": "Сигурни ли сте, че искате да изтриете това изображение?",
    "categoryProductDeleteImport": "Сигурни ли сте, че искате да изтриете тази категория от избраните продукти?",
    "attributeProductDeleteImport": "Сигурни ли сте, че искате да изтриете този атрибут от избраните продукти?",
    "productImportDelete": "Сигурни ли сте, че искате да изтриете импортирания файл?",
    "productImportImport": "Сигурни ли сте, че искате да импортирате продуктите в базата данни?",
    "productImportDeleteConfirm": "Сигурни ли сте, че искате да изтриете избраните записи?",
    "productImportFindAttributesConfirm": "Сигурни ли сте, че искате да потърсите отговарящи атрибути за избраните записи?\nТова ще премахне предишни връзки!",    
    "productImageRestore": "Сигурни ли сте, че искате да въстановите оригиналното изображение?"
};﻿$.fn.makeCollapsible = function(objects, collapsed) {
    if (collapsed == null) { collapsed = true; }
    this.each(function() {
        var container = $(this);
        if (collapsed) {
            $(".th:first", container).append("<div class='td floatRight'><a href='#' class='ui-icon ui-icon-circle-triangle-s collapseMe'></a></div>");
            container.addClass("isCollapsed");
        }
        else {
            $(".th:first", container).append("<div class='td floatRight'><a href='#' class='ui-icon ui-icon-circle-triangle-n collapseMe'></a></div>");
        }

        var collapseLink = $('.th:first .collapseMe', container);
        $('.th:first', container).attr("style", "cursor:pointer;").click(function() {

            isCollapsed = container.hasClass("isCollapsed");
            if (isCollapsed) {                
                collapseLink.removeClass('ui-icon-circle-triangle-s').addClass('ui-icon-circle-triangle-n');
                $(objects, container).show();
                container.removeClass("isCollapsed");
            }
            else {
                collapseLink.removeClass('ui-icon-circle-triangle-n').addClass('ui-icon-circle-triangle-s');
                $(objects, container).show();
                container.addClass("isCollapsed");
            }
            return false;
        });
    });
};


// Define the jID plugin
$.fn.jID = function(name){
    var returnID = null;
    //Get all classes from element
    var getElementClass = String($(this).attr("class"));
    //Regex to get all id containing classes formed like parameterID-123
    var regex = /([^\s].+?)-(\d+)/g;        
    //If name was passed modify regex to include name
    if (name != null){
     regex = eval("/([^\\s]*" + name + ")-(\\d+)/g");
    }               
    if(getElementClass.match(regex)){            
    var matches = [];
    getElementClass.replace(regex, function () {
	    matches.push(arguments[2]);
    });           
       returnID = matches[0]; //Return the first ID found     
    }                             
    return returnID;
};

 
 
//Generic function to write a cookie
function writeCookie(name, value, hours) {
    var expire = "";
    if (hours != null) {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expire;
}

//Generic function to read a cookie
function readCookie(name) {
    var cookieValue = "";
    var search = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) end = document.cookie.length;
            cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}

//Get value of key in hash querystring
//Eg. categoryQuery = getQueryString('category'); 
//Will return '2' from hash #category=2&page=3
function getHashString(key) {  
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\#&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.hash);
  if(qs == null)
    return '';
  else
    return qs[1];
}


function pageRefresh(time) {

    var Time = time * 1000 * 60; //Calculate time in minutes
    var refreshTimer;
    
    if (readCookie('pageRefresh')) {
        $('.pageRefresh :checkbox').attr('checked', true);
        refreshTimer = setTimeout('location.reload(true);', Time);
    }

    $('.pageRefresh :checkbox').change(function() {

        if ($(this).attr('checked')) {
            refreshTimer = setTimeout('location.reload(true);', Time);
            writeCookie('pageRefresh', true, 999);
        }
        else {
            clearTimeout(refreshTimer);
            writeCookie('pageRefresh', false, 999);
        }

    });

}

//Site Messaging
function showMessage(messageText, messageType, messageLog) {
    $("body").append("<div id='siteMessage' style='margin:10px;'>" + getMessage(messageText, messageType, messageLog) + "</div>");
    $("div#siteMessage").fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function() { jQuery(this).remove() });    
}

//Get message baloon
function getMessage(messageText, messageType, messageLog) {
    var Message;
    switch (messageType) {
        case 'error':
            Message = "<span class='jqwc-message-label ui-widget ui-corner-all ui-state-error jqwc-icon-left'><span class='ui-icon ui-icon-alert'></span>" + messageText + "</span>"
            break;
        default:
            Message = "<span class='jqwc-message-label ui-widget ui-corner-all ui-state-highlight jqwc-icon-left'><span class='ui-icon ui-icon-info'></span>" + messageText + "</span>"
    }
    
    //If messageLog is True then log this message to database
    if (messageLog) { setError(messageText + '<br/>jURL: ' + document.location.href) };
 
    return Message;
}

//Log Error to Database
function setError(messageText) {
    $.get("Service.ashx", { mode: "setError", data: messageText },
        function(data) {
        //Error was logged!           
        });
}
﻿function smallCartFunc() {

    jQuery('#smallCart').hoverIntent(
    function() {
        var sender = this;

        if (jQuery('.smallCartList div').length > 0 && !jQuery('div#smallCart').hasClass("isProcessing") && !jQuery('div#smallCart').hasClass("isActive")) {
            jQuery('#smallCartContent').slideDown(150);
            jQuery('#smallCart').addClass('isActive');
        }

    },
    function() {
        var sender = this;

        if (jQuery('.smallCartList div').length > 0) {
            jQuery('#smallCartContent').slideUp(250);
            jQuery('#smallCart').removeClass('isActive');            
        }

    });

}

function showShippingTip() {
    
    var tipString = langPack.cartShippingTip_1;
    var cartTotal = new Number(jQuery('#smallCartFooter .priceDigits').html());
    var freeShipping = new Number(siteSettings.freeShipping - cartTotal).toFixed(2);    
    tipString = tipString.replace("{0}", freeShipping)
    
    if(cartTotal > 0 && freeShipping > 0){    
        showSmallCartTip(tipString);    
    }
    else if(freeShipping < 0) {    
        showSmallCartTip(langPack.cartShippingTip_2);
    }
}


function showSmallCartTip(tipString) {

    if (!jQuery('div#smallCart').hasClass("isActive")) {

        jQuery('div#smallCart').addClass("isActive");
        jQuery('#smallCartFooter').hide();
        jQuery('#smallCartTipContainer').hide().html(tipString).slideDown().fadeTo(2000, 1, function callback(){ jQuery('#smallCartTipContainer').hide(); jQuery('#smallCartFooter').show(); jQuery('div#smallCart').removeClass("isActive"); });

    }
    else {
        setTimeout(function() { showSmallCartTip(tipString) }, 500)
    }

}﻿//User Login
function userLoginForm() {
    //User Login       
    $('.userLoginForm').jDotForm({ service: 'Service.ashx?mode=userLogin', onSuccess: OnLoginComplete, onError: OnLoginFailed });
    function OnLoginComplete(validCredentials) {
        if (validCredentials != 'False') {
            loadUserGUI();
            $('.userRegisterForm').slideUp(); //Hide Register Form if visible            
            $('.userLoginForm, .passwordRetreiveForm').slideUp(); //Hide Login Form if visible
            $('.userLoggedIn').slideDown();  //Show useful links
            }
        else {
            $(".userLoginForm .submit").after(getMessage(langPack2.loginFailed, 'error', false)).slideDown();
        }
    }
    function OnLoginFailed(data) {
        $(".userLoginForm .submit").after(getMessage(langPack2.errorDefault, 'error', true)).slideDown();
    }

    //Password Retreive
    $('.lostPassword').click(function() { $('.passwordRetreiveForm').slideToggle(); return false; });
    $('.passwordRetreiveForm').jDotForm({ service: 'Service.ashx?mode=passwordRetreive', onSuccess: OnRetreiveComplete, onError: OnRetreiveFailed });
    function OnRetreiveComplete(validCredentials) {
        if (validCredentials == 'True') {
            $(".passwordRetreiveForm .submit").after(getMessage(langPack2.passwordSent)).slideDown();
        }
        else {
            $(".passwordRetreiveForm  .submit").after(getMessage(langPack2.loginFailed, 'error', false)).slideDown();
        }
    }
    function OnRetreiveFailed(data) {
        $(".passwordRetreiveForm  .submit").after(getMessage(langPack2.errorDefault, 'error', true)).slideDown();
    }

}

//LogOut currently LoggedIn user 
function userLogout() {
    $.get("Service.ashx", { mode: "userLogout" },
        function(data) {
            if (data != '') {
               window.location.reload();
            }
            else { showMessage(langPack2.errorDefault, 'error', true); }
        });    
}


//Load userView
function getUserView() {
    $('.userView').addClass('ui-state-processing');
    $('.userView').load('Control.ashx?control=userControls/userControls/loginView.ascx .userView li', function() {
        $('.userView').removeClass('ui-state-processing');
    });   
}

//Load userAddress
function getUserAddress() {
    $('#userAddress').addClass('ui-state-processing');
    $('#userAddress').load('Control.ashx?control=userControls/userControls/userAddress.ascx', function() {
        $('#userAddress').removeClass('ui-state-processing');
    });   
}


function userRegisterFunc() {

    var registerForm = $('.userRegisterForm');
    registerForm.jDotForm({ service: 'Service.ashx?mode=userRegister', onSuccess: OnLoginComplete, onError: OnLoginFailed });    
    function OnLoginComplete(newUser) {
        if (newUser != 'False') {
            loadUserGUI();
            $('.userLoginForm, .passwordRetreiveForm').slideUp(); //Hide Register Form if visible
            $('.userRegisterForm').slideUp(); //Hide Login Form if visible
            $('.userLoggedIn').slideDown();  //Show useful links                        
        }
        else {
            $(".userRegisterForm .submit").after(getMessage(langPack2.loginEmailUsed.replace("{0}", $('.userRegisterForm #txtUsername').val()), 'error', true)).slideDown();
        }
    }
    function OnLoginFailed(data) {
        $(".userRegisterForm .submit").after(getMessage(langPack2.errorDefault, 'error', true)).slideDown();
    }

}


function loadUserGUI() {
    getUserView();
    getUserAddress();
    getCart();
}

function userAddressFunc() {

    $('.lnkEditProfile').click(function() {
        $('.userAddressViewPanel').slideUp(function() {
            $('.userAddressForm').slideDown();
            $('.orderConfirmMessage').html(getMessage(langPack2.orderConfirmTip, 'error', false));
            $('.confirmOrderButton').removeClass('jqwc-state-default').addClass('jqwc-state-disabled');
        });
        return false
    });
   
    var addressForm = $(".userAddressForm");
    addressForm.jDotForm({ service: 'Service.ashx?mode=setUserAddress', onSuccess: OnSetAddressComplete, onError: OnSetAddressFailed });    
    function OnSetAddressComplete(data) {
        if (data == 'True') {
            var userAddress = langPack2.userAddressView;
            userAddress = userAddress.replace("{0}", $('.firstName', addressForm).val())
            userAddress = userAddress.replace("{1}", $('.lastName', addressForm).val())
            userAddress = userAddress.replace("{2}", $('.city', addressForm).val())
            userAddress = userAddress.replace("{3}", $('.address', addressForm).val())
            userAddress = userAddress.replace("{4}", $('.phone', addressForm).val())

            $('.userAddressViewPanel .userAddress').html(userAddress);
            $(".th .iconError", addressForm).hide();

            addressForm.slideUp();
            $('.userAddressViewPanel').slideDown();
            
            getBigCart();
        }
        else {
            $(".submit", addressForm).after(getMessage(langPack2.errorDefault, 'error', true)).slideDown();
        }
    }
    function OnSetAddressFailed(data) {
        $(".submit", addressForm).after(getMessage(langPack2.errorDefault, 'error', true)).slideDown();
    }
}

function userPasswordFunc() {

    $(".passwordChangeForm").makeCollapsible($('table'), true);
    
    var passwordChangeForm = $(".passwordChangeForm");
    passwordChangeForm.jDotForm({ service: 'Service.ashx?mode=setUserPassword', onSuccess: OnPasswordComplete, onError: OnPasswordFailed });
    function OnPasswordComplete(data) {
        $(".passwordChangeForm .jqwc-message-label").remove();
        if (data == 'True') {
            $(':input', passwordChangeForm).val("");            
            $(".submit", passwordChangeForm).after(getMessage(langPack2.passwordChanged)).slideDown();
        }
        else {
            $(".submit", passwordChangeForm).after(getMessage(langPack2.errorDefault, 'error', true)).slideDown();
        }
    }
    function OnPasswordFailed(data) {
        $(".passwordChangeForm .jqwc-message-label").remove();
        $(".submit", passwordChangeForm).after(getMessage(langPack2.errorDefault, 'error', true)).slideDown();
    }    
}﻿function checkOutFunc() {
       
    $("#bigCart .delete").click(function(){  
        deleteCartItem($("#bigCart").jID('orderID'), $(this).jID('unitID'));
        return false;
        });

    $("#bigCart .update").change(function(){  
        updateCartItem($("#bigCart").jID('orderID'), $(this).jID('unitID'), this.options[this.selectedIndex].value);
        });

    $("#bigCart .confirmOrderButton").click(function(){  
        confirmOrder($("#bigCart").jID('orderID'));
        return false;
        });     
}

function getCart() {
    getSmallCart();
    getBigCart();
}

//Load smallCart
function getSmallCart() {
    var smallCartControl = $('#smallCart');
    if (smallCartControl.length > 0) {
        $('#smallCartContainer').load('Control.ashx?control=userControls/orderControls/SmallCart.ascx', function() {
            $(".cartTotalItems").html("(" + $(".smallCartTotalItems").html() + ")");
            showShippingTip();
        });
    }
}

//Load bigCart
function getBigCart() {
    var bigCartControl = $('#bigCart');
    if (bigCartControl.length > 0) {
        $('.bigOrderWrapper').load('Control.ashx?control=userControls/orderControls/orderView.ascx');
        //Load user comment for Order
        $('#orderComment').load('Control.ashx?control=userControls/orderControls/orderComment.ascx');
    }
}


function addCartItem(sender, inventoryID, quantity){

    var buttonControl = $(sender);
    if(!buttonControl.hasClass("jqwc-state-active") && !buttonControl.hasClass("jqwc-state-done") && !buttonControl.hasClass("jqwc-state-disabled")){

        $('#smallCart').addClass("isProcessing");
        $(".jqwc-button-text", buttonControl).html(langPack2.pleaseWait);
        buttonControl.addClass("jqwc-state-active");

        $.get("Service.ashx", { mode: "addCartItem", data: inventoryID + "|" + quantity },
            function(data) {
                if (data > 0) { //If unit was successfully added to cart then new ID is returned                
                    buttonControl.removeClass('jqwc-state-active').addClass('jqwc-state-done');
                    $(".jqwc-button-text", buttonControl).hide().html(langPack2.addToCartSuccess).fadeIn().fadeOut().fadeIn(function callback() { $(this).html(langPack2.addToCart); buttonControl.removeClass('jqwc-state-done'); });
                    $('.goToCart').slideDown();
                    getCart();
                }
                else {
                    showMessage(langPack2.errorDefault + ' (addCartItem)', 'error', true);
                }
            }); 
    }

}



// Update Product
function updateCartItem(orderID, inventoryID, quantity) {    
    $("#bigCart").addClass("ui-state-processing");    
    $.get("Service.ashx", { mode: "updateCartItem", data:  orderID + "|" + inventoryID + "|" + quantity },
    function(data) {
        if (data != '') {
            getCart();                    
        }
        else { 
            showMessage(langPack2.errorDefault, 'error', true);
            $("#bigCart").removeClass("ui-state-processing");
        }
    });         
}


// Delete Product
function deleteCartItem(orderID, inventoryID) {   
    $("#bigCart").addClass("ui-state-processing");
    $('#smallCart').addClass("isProcessing");
    $.get("Service.ashx", { mode: "deleteCartItem", data:  orderID + "|" + inventoryID },
    function(data) {
        if (data != '') {            
            $('#smallCart .orderItem_' + inventoryID).slideUp();
            $('#bigCart .orderItem_' + inventoryID).fadeOut();
            getCart();
        }
        else { 
            showMessage(langPack2.errorDefault, 'error', true);
            $("#bigCart").removeClass("ui-state-processing");
        }
    }); 
}

//Confirm Order order
function confirmOrder(orderID) {    

    var buttonControl = $('.confirmOrderButton');
    if(!buttonControl.hasClass("jqwc-state-disabled")){
        $("#bigCart").addClass("ui-state-processing");    
        //Disable multiple order completion        
        buttonControl.unbind('click').addClass("jqwc-state-active");
        $('.jqwc-button-text', buttonControl).html(langPack2.pleaseWait);                    

        var sendEmail;
        if($('.confirmOrderWrapper  input:checkbox').attr('checked')) { sendEmail = true }        
        else { sendEmail = false }
        
            $.get("Service.ashx", { mode: "confirmOrder", data:  orderID + "|" + sendEmail },
            function(data) {
                if (data != '') {
                
                    getSmallCart();
                    $('.orderView, .orderSpecials, .confirmOrderWrapper, .orderUserCommentForm, .userAddressViewPanel, .orderEditPanel').slideUp();                          
                    $('#bigCart').removeClass("ui-state-processing");
                    $('.orderConfirmed').slideDown();
                    
                    //Call Google Track Event for New Order
                    googleOrderTracking(orderID);            
                                        
                }
                else {            
                    
                }
            }); 
    }

}


//Google Ecommerce Tracking Code
function googleOrderTracking(orderID){                  
                           
        jQuery.get("Control.ashx", { control: "Tools/googleEcommerceTracking.ascx", parameters: "_orderID|" + orderID }, 
        function(data){
            if (data != '') {               
                $("#container").append(data);
            }
        });                        
    }  


function orderComment(orderID){

    var isCollapsed = true;
    if($('.orderUserCommentForm').hasClass('orderUserCommentReady')) {
        isCollapsed = false;        
    }    
    $(".orderUserCommentForm").makeCollapsible($('.userCommentEdit'), isCollapsed);
    
    //Edit
    $('.orderUserCommentForm .editUserComment').click(function(){     
        $(".orderUserCommentForm .userCommentEdit").slideDown();
        $(".orderUserCommentForm .userCommentView").slideUp();
    });

    //Save
    $('.orderUserCommentForm .savelUserComment').click(function(){
            var orderID = $('.orderUserCommentForm').jID('orderID');
            var orderComment = $('.userCommentEdit .commentField').val();            
            if(orderComment.length > 0){            
                $(".userCommentEdit").addClass("ui-state-processing");
                jQuery.get("Service.ashx", { mode: "setOrderComment", data: orderID + "|" + orderComment },         
                function(data){
                    if (data != '') {
                        $('.orderUserCommentForm .userCommentEdit').slideUp().removeClass("ui-state-processing");
                        $('.orderUserCommentForm .userComment').html($('.userCommentEdit .commentField').val());
                        $('.orderUserCommentForm .userCommentView').slideDown();
                        $('.orderUserCommentForm').addClass('orderUserCommentReady');
                    }
                    else {
                        showMessage(langPack2.errorDefault, 'error', true);
                    }
                });             
            }
            else{ $('.userCommentEdit .commentField').addClass(''); }        
    });

    //Delete user comment                
    $('.orderUserCommentForm .deleteUserComment').click(function(){     
        var orderID = $('.orderUserCommentForm').jID('orderID');
        $(".userCommentView").addClass("ui-state-processing");      
        jQuery.get("Service.ashx", { mode: "deleteUserComment", data: orderID },         
        function(data){
            if (data != '') {               
                $('.orderUserCommentForm .userCommentView').slideUp().removeClass("ui-state-processing");
                $('.orderUserCommentForm').removeClass('orderUserCommentReady');
                $('.userCommentEdit .commentField').val('');
                $(".orderUserCommentForm .th a").click();
            }
            else {
                showMessage(langPack2.errorDefault, 'error', true);
            }
        });        
        return false
    });    
}

﻿//This file deals with product properties and attributes.
//Image gallery, attributes

function loadRandomImageGallery(productData) {
      
    productData = eval('(' + productData + ')');
    productInfo = productData.products.product;
   
    //JSON problem Fix. Check if only one record and turn into array if so.
    if (typeof (productInfo.length) == "undefined") {
        for (var i in productInfo) {
            productInfo = new Array(productData.products.product);
        }
    };
             
   //var loadRandomImage = setTimeout('loadProductImage(' + productInfo + ')', 3000);
   var imageCounter = 0; 
   var loadRandomImage = setInterval(function () { if(imageCounter == productInfo.length - 1){imageCounter = 0} else { imageCounter++ }; loadProductImage(productInfo, imageCounter); }, 7000);
   
}

function loadProductImage(productInfo, index) {
            
    var productImage = "Image-" + productInfo[index]['@image'] + "-140,200.jpg";    
    var productID = productInfo[index]['@id'];
    var productPrice = productInfo[index]['@price'];   
    var productSale = productInfo[index]['@sale'];   
        
    //fade out the old image
    jQuery(".randomProductContainer .randomProductImage").animate({ backgroundPosition:"(0 0)", opacity: 0.0 }, 1000, 'linear', function() {
        
        var img = new Image();
      
        // wrap our new image in jQuery, then:
        jQuery(img)
        // once the image has loaded, execute this code
        .load(function () {
          
             jQuery(".randomProductContainer .randomProductImage")
             .attr('href', 'Product-Random-' + productID + '.html')
             .css({"background-image" : "url(" + productImage + ")", "background-position" : "0 -50px" })
             .animate({backgroundPosition:"(0 -25px)", opacity: 1.0}, 1000, 'linear');
             
             if(productSale > 0) { $(".randomProductContainer .priceDigits").html(productSale); }
             else{ $(".randomProductContainer .priceDigits").html(productPrice); }
             
        })    
        // if there was an error loading the image, react accordingly
        .error(function () {
          // notify the user that the image could not be loaded
        })    
        // *finally*, set the src attribute of the new image to our image
        .attr('src', productImage);

  });
  
}

function loadImageGallery(productID) {
    var productView = jQuery(".productView_" + productID);
    jQuery('.jqzoom', productView).jqueryzoom({ xzoom: 300, yzoom: 250, offset: 5, position: 'right', preload: 1, lens: 1 });
     
    //Add image gallery functionality
    jQuery('.productImageThumb a', productView).click(function() {
        loadProductImage(this);
        return false;
    });

    // Product Image Gallery
    function loadProductImage(object) {
        var imagePath = jQuery(object).attr("href");
        var image2Path = jQuery(object).attr("rel");
        var img = new Image();
        //fade out the old image
        jQuery(".jqzoom img", productView).fadeOut("fast");
        // wrap our new image in jQuery, then:
        jQuery(img)
        // once the image has loaded, execute this code
        .load(function() {
            // set the image hidden by default    
            jQuery(this).hide();
            // remove previous image
            jQuery('.jqzoom', productView).empty()
            // then insert our image
            .append(this);
            // fade in image 
            jQuery(this).fadeIn("fast");
            //Load Zoom lens
            loadLens(jQuery('.jqzoom', productView));
        })
        // if there was an error loading the image, react accordingly
        .error(function() {
            // notify the user that the image could not be loaded
        })
        // *finally*, set the src attribute of the new image to our image
        .attr('src', imagePath).addClass(image2Path);
  
    };
}


function loadProduct(productData) {

    productData = eval('(' + productData + ')');
    productInfo = productData.product;
    var productID = productInfo['@id'];
    var productView = jQuery(".productView_" + productID);
    
    jQuery('.attributeContainer li.image img', productView).hoverTip({ xTip: 150, yTip: 100, xOffset: 3, yOffset: 7, position: 'top', preload: 0 });
    
    //Disable all attribute controls. Only relevant fields will be enabled
    productGroupAttributes = productData.product.inventory.groupAttributes.groupAttribute
    
    //JSON problem Fix. Check if only one record and turn into array if so.
    if (typeof (productGroupAttributes.length) == "undefined") {
        for (var i in productGroupAttributes) {
            productGroupAttributes = new Array(productData.product.inventory.groupAttributes.groupAttribute);
        }
    };

    bindAttributeClick();

    jQuery(".addToCart", productView).click(function() {        
        addCartItem(this, getUnitCode(getSelectedAttributeIDs()), 1);
    });

    function filterOnHand(groupAttribute) {
        var selectedAttributes = new Array();

        jQuery(".groupAttribute_" + groupAttribute + " li.selected", productView).each(function(intIndex) {        
            selectedAttributes[intIndex] = getElementID(jQuery(this), "class", "productAttribute");
        });

        jQuery(".attributeContainer:not('.groupAttribute_" + groupAttribute + "') li", productView).each(function(intIndex) {

            var currentAttribute = this;
            var newSelectedAttributes = new Array(0);
            newSelectedAttributes[0] = getElementID(jQuery(this), "class", "productAttribute");
            newSelectedAttributes = newSelectedAttributes.concat(selectedAttributes);

            if (attributeOnHand(newSelectedAttributes)) {
                jQuery(currentAttribute).removeClass('disabled');
            }
            else {
                jQuery(currentAttribute).addClass('disabled').removeClass('selected');
            }
        });
        
        if (getSelectedAttributeIDs().length == productGroupAttributes.length) {
            jQuery(".addToCart", productView).removeClass('jqwc-state-disabled');
        }
        else {
            jQuery(".addToCart", productView).addClass('jqwc-state-disabled');         
        }
    }

    function getUnitCode(arrAttributeID) {
        var unitID = 0;
        productUnits = productData.product.inventory.unit
        //JSON problem Fix. Check if only one record and turn into array if so.
        if (typeof (productUnits.length) == "undefined") {
            for (var i in productUnits) {
                productUnits = new Array(productData.product.inventory.unit);
            }
        };
  
        //Loop trough product units
        for (var unit in productUnits) {
            
            //If unit has positive quantity aka is onhand
            var count = 0;
            if (productUnits[unit]['@quantity'] > 0) {

                //JSON problem Fix. Check if only one record and turn into array if so.
                var unitAttributes = productUnits[unit].attribute
                if (typeof (unitAttributes.length) == "undefined") {
                    for (var i in unitAttributes) {
                        unitAttributes = new Array(productUnits[unit].attribute);
                    }
                };
                
                //Loop trough unit attributes and check if attributeID exists
                for (var attr in unitAttributes) {

                    //For each attribute passed check if exist and iterate counter                    
                    for (var attrID in arrAttributeID) {
                        if (arrAttributeID[attrID] == unitAttributes[attr]['@id']) {
                            count++;
                        }
                    }
                }
                //If all conditions was met mark as onHand
                if (arrAttributeID.length == count) { unitID = productUnits[unit]['@id'] }
            }

        }

        return unitID
    }


    function attributeOnHand(arrAttributeID) {
        var isOnHand = false;
        
        productUnits = productData.product.inventory.unit
        //JSON problem Fix. Check if only one record and turn into array if so.
        if (typeof (productUnits.length) == "undefined") {
            for (var i in productUnits) {
                productUnits = new Array(productData.product.inventory.unit);
            }
        };
      
        //Loop trough product units
        for (var unit in productUnits) {
                       
            //If unit has positive quantity aka is onhand
            var count = 0;                
            if (productUnits[unit]['@quantity'] > 0) {
               
                //Loop trough unit attributes and check if attributeID exists
                for (var attr in productUnits[unit].attribute) {
                    
                //For each attribute passed check if exist and iterate counter                    
                    for (var attrID in arrAttributeID) {                        
                        if (arrAttributeID[attrID] == productUnits[unit].attribute[attr]['@id']) {
                            count++;
                        }
                    }
                }
                //If all conditions was met mark as onHand                
                if (arrAttributeID.length == count) { isOnHand = true }                
            }
             
        }
        return isOnHand  
    }


    //Bind click event to all not disabled attributes
    function bindAttributeClick() {

        jQuery(".inventoryContainer li", productView).click(function() {           
           var groupAttribute = getElementID(jQuery(this).parent().parent(), "class", "groupAttribute");

           if (jQuery(this).hasClass('disabled') || jQuery(this).hasClass('outOfStock')) {
                jQuery('.inventoryTip', productView).hide().html(jMessageLabel(langPack.outOfStock, "error", "alert", "left")).fadeIn().fadeOut().fadeIn();
            }

            else {
                jQuery("li", jQuery(this).parent()).removeClass('selected').removeClass('disabled');
                jQuery(this).addClass('selected');
                filterOnHand(groupAttribute);
                jQuery('.inventoryTip', productView).html(jMessageLabel(langPack.selected + " : " + getSelectedAttributeTitles(), "highlight", "info", "left"));
            }

        });

    }
    //Get all selected children attributes IDs for this groupAttribute
    function getChildrenAttributeIDs(groupAttributeID){
        var childrenAttributes = new Array();
        jQuery(".parentAttribute_" + groupAttributeID + " li", productView).each(function(intIndex){
        childrenAttributes[intIndex] = getElementID(jQuery(this), "class", "productAttribute");
        });
        return childrenAttributes;
    }

    //Get all selected attributes IDs
    function getSelectedAttributeIDs(){
        var selectedAttributes = new Array();
        jQuery(".inventoryContainer li.selected", productView).each(function(intIndex){
        selectedAttributes[intIndex] = getElementID(jQuery(this), "class", "productAttribute");
    });    
        return selectedAttributes;
    }

    //Get all selected attributes IDs
    function getSelectedAttributeTitles(){
        var selectedAttributes = new Array();
        jQuery(".inventoryContainer li.selected", productView).each(function(intIndex){
        
            if (jQuery('img', this).length > 0) {
                selectedAttributes[intIndex] = jQuery('img', this).attr('title');
            }
            else {
                selectedAttributes[intIndex] = jQuery(this).html();
            }
        
        
    });    
        return selectedAttributes;
    }

    //Get all selected group attributes IDs
    function getSelectedGroupAttributeIDs() {
        var selectedGroupAttributes = new Array();
        jQuery(".inventoryContainer li.selected", productView).parent().parent().each(function(intIndex) {
            selectedGroupAttributes[intIndex] = getElementID(jQuery(this), "class", "groupAttribute");
        });
        return selectedGroupAttributes;
    }
       
}

      
﻿ 
function sizeFilterFunc(categoryQuery, attributeQuery, searchQuery) {    
    
    $('.sizeFilterContainer li').click(function(){
        var newQuery = new Array();           
        if(categoryQuery != ''){ newQuery[newQuery.length] = "category=" + categoryQuery; }
        if(attributeQuery != ''){ newQuery[newQuery.length] = "attribute=" + attributeQuery; }
        if(searchQuery != ''){ newQuery[newQuery.length] = "search=" + searchQuery; }
               
        if($('.priceFilterContainer.active').length > 0){                
            newQuery[newQuery.length] = "price=" + $('.priceFilterSlider').slider('option', 'values');
        }            
                                   
        //Remove all current li's
        $('.sizeFilterContainer li:not(:first-child)').not(this).removeClass('current').hide();
        //Remove all active filters
        $('.sizeFilterContainer .sizeFilter').removeClass('active');
        //Select first li of all filters
        $('.sizeFilterContainer li:first-child').addClass('current').show();
        //Remove current class from current list
        $('li', $(this).parent()).removeClass('current');
        $(this).addClass('current');
        
        if($("a:first", this).jID('attributeID') > 0){
            //If size was selected set current group to active
            $(this).parent().parent().addClass('active');
            newQuery[newQuery.length] = "attribute=" +  $("a:first", this).jID('attributeID');
        }  

        $.history.add(newQuery.join("&"));
        loadProductList();        
        return false;
    });

    $('.sizeFilterContainer .showMore').click(function(){ 
        $('.sizeFilterContainer .tr.secondary').slideToggle();
        return false;
    });

    $('.dropdown-menu').hoverIntent(
	      function () {
		    $('li:not(.current)', this).slideDown(100);		    
		    $(this).css('z-index', 1500);
	      },
	      function () {
		    obj = this;
		    $('li:not(.current)', this).slideUp(100, function(){ 
		        $(obj).css('z-index', 1000);
            });
        }
	);
}

function priceFilterFunc(categoryQuery, searchQuery, maxPrice, minPrice) {
    var sliderGap = parseInt((maxPrice-minPrice)*0.10);
     $('.priceFilterSlider').slider({ range: true, values: [minPrice+sliderGap, maxPrice-sliderGap], min: minPrice, max: maxPrice, step: 1, 
     slide: function(event, ui) { priceFilterUpdate(); },
     change: function(event, ui) { priceFilter(categoryQuery, searchQuery); } 
     });
}

function priceFilter(categoryQuery, searchQuery) { 
    $('.priceFilterContainer').addClass('active');    
    var newQuery = new Array();
    if(categoryQuery != ''){ newQuery[newQuery.length] = "category=" + categoryQuery; }
    if(searchQuery != ''){ newQuery[newQuery.length] = "search=" + searchQuery; }
            
    //Get the first selected attribute
    var attributeQuery = $('.sizeFilterContainer li:not(:first-child).current a:first').jID('attributeID');
    if(attributeQuery != null){ newQuery[newQuery.length] = "attribute=" + attributeQuery; }    
        
    //Remove active state if selected range match max and min 
    if($('.priceFilterSlider').slider( 'values' , 0) == $('.priceFilterSlider').slider('option', 'min') && $('.priceFilterSlider').slider( 'values' , 1) == $('.priceFilterSlider').slider('option', 'max')) {
        $('.priceFilterContainer').removeClass('active');              
    }
    else{
        newQuery[newQuery.length] = "price=" + $('.priceFilterContainer .priceFilterSlider').slider('option', 'values');
    }
    $.history.add(newQuery.join("&"));
    loadProductList();    
}

//Updates priceFilter prices
function priceFilterUpdate(){   
    var minPrice = parseInt($('.priceFilterSlider').slider( 'values' , 0)).toFixed(2);
    var maxPrice = parseInt($('.priceFilterSlider').slider( 'values' , 1)).toFixed(2);
    $('.priceFilterString .priceFrom').html(langPack2.priceSimple.replace('{0}', minPrice)); 
    $('.priceFilterString .priceTo').html(langPack2.priceSimple.replace('{0}', maxPrice));
}

function productCatalogFunc(categoryQuery){    
       
    //Set hash information for ajax navigation       
    $("#siteBody").history(function(e, hash) {
		loadProductList();
		//TODO: Update priceFilter, sizeFilter on navigation		
	});
	    
    productListFunc(categoryQuery);
    
    //If there is hash information consider
    if(window.location.hash) {        
        //If price was filtered mark as current
        var priceQuery = getHashString('price');       
        //If attribute was filtered mark as current
        var attributeQuery = getHashString('attribute');
        if(attributeQuery.length > 0){
            var currentAttribute = $('.sizeFilterContainer li a.attributeID-' + attributeQuery);
            $('li:first-child', currentAttribute.parent().parent()).removeClass('current');
            currentAttribute.parent().addClass('current');
            currentAttribute.parent().parent().parent().addClass('active');
        }
        
        //Load list if any hash queries found
        if (getHashString('price').length > 0 || getHashString('attribute').length > 0 || getHashString('search').length > 0) {
            loadProductList();
        }
        
        //Update priceSlider. Assumes no postback will result since prev query is still working
        if(priceQuery.length > 0){
            $('.priceFilterSlider').slider( 'values' , 0 , priceQuery.split(',')[0]);
            $('.priceFilterSlider').slider( 'values' , 1 , priceQuery.split(',')[1]);
            priceFilterUpdate();
        }
    }
}

function productListFunc(categoryQuery){

    $('.clearPriceFilter').click(function(){                   
        var newQuery = new Array; //Construct new query
        newQuery[newQuery.length] =  "category=" + categoryQuery; 
        newQuery[newQuery.length] =  "search=" + getHashString('search'); 
        newQuery[newQuery.length] =  "attribute=" + getHashString('attribute');        
        $.history.add(newQuery.join("&")); //Update hash
        loadProductList(); //Reload product list        
        //Update price slider
        $('.priceFilterSlider').slider( 'values' , 0, $('.priceFilterSlider').slider('option', 'min'));
        $('.priceFilterSlider').slider( 'values' , 1, $('.priceFilterSlider').slider('option', 'max'));
        priceFilterUpdate();        
        return false;
    });
    
    $('.clearSizeFilter').click(function(){
        $('.sizeFilterContainer li:first-child').click();
        return false;
    });
    
    //Paging the Ajax way
    $('.pagerContainer.productCatalog li a').click(function(){            
        var newQuery = "category=" + categoryQuery + "&" + $(this).attr('href').split('?')[1];
        $.history.add(newQuery);
        loadProductList();
        return false;
    });
}

function loadProductList(){
    var newHash = new Array;
    var newQuery = new Array;
    if(!$("#siteBody").hasClass("ui-state-processing")) {    
        
        if(getHashString('category').length > 0){ newQuery[newQuery.length] =  "_categoryQuery|" + getHashString('category'); };        
        if(getHashString('attribute').length > 0){ newQuery[newQuery.length] =  "_attributeQuery|" + getHashString('attribute'); };        
        if(getHashString('price').length > 0){ newQuery[newQuery.length] =  "_priceQuery|" + getHashString('price'); };            
        if(getHashString('search').length > 0){ newQuery[newQuery.length] =  "_searchQuery|" + getHashString('search'); };                
        if(getHashString('page').length > 0){ newQuery[newQuery.length] =  "_pageQuery|" + getHashString('page'); };

        $("#siteBody").addClass("ui-state-processing");
        $.get("Control.ashx", { control: "userControls/catalogControls/productCatalog.ascx", parameters: newQuery.join('|') }, 
            function(data){
                if (data != '') {
                    $('#siteBody').html(data).removeClass("ui-state-processing");
                    productListFunc(getHashString('category'));
                }
                else { showMessage(langPack2.errorDefault, 'error', true); }
            });
    }
}﻿function loadHelpLauncher(){    
    jQuery('.helpMeLink, .helpMeGroup a:not(".contactMeLink")').click(function(){                
                var helpItemID = jQuery(this).jID('helpItem');                
                jQuery('.helpMe').dialog('close');
                $.get("Control.ashx", { control: "userControls/helpSystem.ascx", parameters: "_helpItemID|" + helpItemID },
                function(data) {
                    if (data != '') {                        
                        jQuery('body').append('<div class="helpMe" style="display:none;">' + data + '</div>');                    
                        var helpItemTitle = langPack.helpSystemTitle + jQuery('.helpMe .helpItemTitle').html();                    
                        jQuery('.helpMe').dialog({ width: 660, modal: true });
                        jQuery('.helpMe').dialog('option', 'title', helpItemTitle);                        
                    }
                    else { showMessage(langPack2.errorDefault, 'error', true); }
                });                
            return false;
            });
}

function loadHelpSystem(){
    
    jQuery('.helpSystemMenu a:not(".current")').click(function(){
                                
        jQuery('.helpSystemMenu a').unbind('click');
        
        var helpItemID = jQuery(this).jID('helpItem');
        
        jQuery(".helpSystemMenu a").removeClass('current');
        jQuery(this).addClass('current');                
                        
        jQuery('.helpMe .helpSystemContent').addClass("ui-state-processing");


        jQuery.get("Service.ashx", { mode: "getHelpItem", data: helpItemID },         
        function(data){
            if (data != '') {               
		        var helpItemTitle = data.split("|")[0];
                var helpItemDescription = data.split("|")[1];                                      
                
                jQuery('.helpMe').dialog('option', 'title', langPack.helpSystemTitle + helpItemTitle);
                jQuery('.helpMe .helpItemTitle').html(helpItemTitle);
                jQuery('.helpMe .helpItemDescription').html(helpItemDescription);
                
                jQuery('.helpMe .helpSystemContent').removeClass("ui-state-processing");
                
                loadHelpSystem();
            }
            else { showMessage(langPack2.errorDefault, 'error', true); }
        });
        
        return false;
    
    });
    
}

function loadContactForm(emailSubject){
    jQuery('.helpMe, contactMe').dialog('close');        
    
    $.get("Control.ashx", { control: "userControls/contactForm.ascx", parameters: "_emailSubject|" + emailSubject },
    function(data) {
        if (data != '') {                        
            jQuery('body').append('<div class="contactMe" style="display:none;">' + data + '</div>');                                    
        
            jQuery('.contactMe').dialog({ width: 400, modal: true });
            jQuery('.contactMe').dialog('option', 'title', langPack.contactForm);    
        }
        else { showMessage(langPack2.errorDefault, 'error', true); }
    });                    
}
  
function contactFormFunc(){
    
     $('.contactForm').jDotForm({ service: 'Service.ashx?mode=sendEmail', onSuccess: OnEmailComplete, onError: OnEmailFailed });
        function OnEmailComplete(data) {                
            jQuery('.contactForm').slideUp();
            jQuery('.contactForm').after(getMessage(langPack.emailSent));                
        }
        function OnEmailFailed(data) {
            showMessage(langPack2.errorDefault, 'error', true);
        }   
    }

﻿function pageSizeSelect(pageName) {

    jQuery("." + pageName + " .pageSizeSelector select").change(function(){ 
                
        writeCookie(pageName,jQuery(this).val(), 8760)
        
        location.reload(true);  
        
        });

}﻿function ping(note){
    console.log("ping: " + note)
}

function horizontalMenu() {

    jQuery('#contentHorizontalMenu li').hoverIntent(
    function() {
    var sender = this;
        jQuery('#contentHorizontalMenu li').removeClass('active');
        jQuery(this).addClass('active');
        jQuery('#contentHorizontalSubMenu div.categoryListContainer:not(.' + jQuery("a", this).attr('class') + ')').removeClass('visible').slideUp('fast', function() { jQuery('div.' + jQuery("a", sender).attr('class')).slideDown('fast'); });

    },
    function() { });

    jQuery('#contentMenuContainer_').hover(
    function() { },
    function() {
        jQuery('#contentHorizontalMenu li').removeClass('active');
        jQuery("#contentHorizontalSubMenu div.categoryListContainer", this).slideUp('fast').removeClass('visible');
    });
}

//Contains function for array alert([1, 2, 3].contains(2)); // => true
function contains(a, obj) {
    var i = a.length;
    while (i--) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}


//Max function for array alert([1, 2, 3, 2, 1].max())
function arrayMax(array) {
var max = array[0];
var len = array.length;
for (var i = 1; i < len; i++) if (array[i] > max) max = array[i];
return max;
}

//Min function for array alert([1, 2, 3, 2, 1].min())
function arrayMin(array) {
var min = array[0];
var len = array.length;
for (var i = 1; i < len; i++) if (array[i] < min) min = array[i];
return min;
}


    
    
//Gets information stored in elements class
//Example: Element_33 will return 33
//Techique used to store information in CSS classes
function getElementID(element, attribute, property) {
    var result = null;    
    
    if (attribute == "id") {
        var getElementID = element.attr("id");
        var temp = getElementID.split("_");
        //If temp lenght is more than 1 than its a valid info class
        if (temp.length > 1) {
            //Get the seccond part
            result = temp[1]
        }
    }
    else {
        //Get all classes from element
        var getElementClass = jQuery(element).attr("class");
        //Split classes in array
        getElementClass = getElementClass.split(" ");

        //Loop trough classes
        for (var x in getElementClass) {                   
            var elementClass = getElementClass[x].split("_");
            //If temp length is more than 1 than its a valid info class. 
            //Info class shoud be formed [property]_[ID]
            if (elementClass.length > 1) {
                if (elementClass[0] == property) {
                    result = elementClass[1];
                }
                else if (property == null) {
                result = elementClass[1];
                }      
            }
        }
    }
    
    return result;    
}


function ajaxFormBind(formWrapper, functionBind, functionParameters, actionName){
        
    jQuery(formWrapper).removeClass("ui-state-processing");    
    jQuery("input, textarea", formWrapper).removeAttr("disabled");
    
    jQuery('.submit', formWrapper).removeClass('jqwc-state-active').click(function() { functionBind(functionParameters); return false; });
    jQuery('.submit .jqwc-button-text', formWrapper).html(actionName);                   
               
    jQuery('input, textarea', formWrapper).keydown(function(event){

          if (event.keyCode == 13) { jQuery('.submit', formWrapper).click(); };
            
        });
}

function ajaxFormUnBind(formWrapper){
 
    jQuery('.submit', formWrapper).unbind('click');       
    jQuery('input, textarea', formWrapper).unbind('keydown');

    jQuery(formWrapper).addClass("ui-state-processing");
    jQuery("input, textarea", formWrapper).attr("disabled","disabled");
    
    jQuery('.submit', formWrapper).addClass('jqwc-state-active');         
    jQuery('.submit .jqwc-button-text', formWrapper).html(langPack.statePleaseWait);                 

}

function cssTableIsCollapsible(formWrapper){
    
 var isCollapsed = jQuery(formWrapper).hasClass("isCollapsed");
 
     if (isCollapsed) {
            jQuery(".th:first", formWrapper).append("<div class='td floatRight'><a href='#' class='ui-icon ui-icon-circle-triangle-s collapseForm'></a></div>");
            }
     else {
            jQuery(".th:first", formWrapper).append("<div class='td floatRight'><a href='#' class='ui-icon ui-icon-circle-triangle-n collapseForm'></a></div>");
        }
        
    jQuery('.collapseForm, .th .td span', formWrapper).addClass('isLink').click(function(){ 
       
        isCollapsed = jQuery(formWrapper).hasClass("isCollapsed");
        
        if (isCollapsed) {            
            jQuery('.collapseForm', formWrapper).removeClass('ui-icon-circle-triangle-s').addClass('ui-icon-circle-triangle-n');
            jQuery(".th ~ .tr", formWrapper).slideDown();
            jQuery(formWrapper).removeClass("isCollapsed");
        }
     
        else {
            jQuery('.collapseForm', formWrapper).removeClass('ui-icon-circle-triangle-n').addClass('ui-icon-circle-triangle-s');
            jQuery(".th ~ .tr", formWrapper).slideUp(); 
            jQuery(formWrapper).addClass("isCollapsed");
        }

        return false; 

    });

}

function defaultJScript() {

//    jQuery('form').keydown(function(event){

//          if (event.keyCode == 13) {                           
//                //window.event.cancelBubble = true;
//                //window.event.returnValue = false; 
//                
//                return false;
//          };
//            
//        });

    loadHelpLauncher();
}