function startAjax(context) {
    //alert(context.get_loadingElement().id+"--"+$(context.get_loadingElement().id).html());
    $(context.get_updateTarget()).empty();
    $(context.get_updateTarget()).append($(context.get_loadingElement()).html());
    //$(context.get_updateTarget()).replaceWith("<span class='red'>loading</span>");
}

function endAjax(context) {
    setTimeout(initPopUps, 500);
}


function closeFancyBox() {
    $.fancybox.close();
}



function initPopUps() {
    $(".imageWithPopUp").cluetip({ positionBy: 'mouse',
        insertionType: 'appendTo',
        showTitle: false,
        fx: { open: 'show', openSpeed: '5' },
        ajaxCache: true,
        cluetipClass: 'jtip',
        dropShadow: false,
        mouseOutClose: false,
        clickThrough: true,
        tracking: false
    });
}


function defaultAllCornersSettings() {
    settingsRC = {
        tl: { radius: 10 },
        tr: { radius: 10 },
        bl: { radius: 10 },
        br: { radius: 10 },
        antiAlias: true,
        autoPad: true,
        validTags: ["div"]
    }
    return settingsRC;
}


function defaultTopCornersSettings() {
    settingsRC = {
        tl: { radius: 10 },
        tr: { radius: 10 },
        bl: { radius: 0 },
        br: { radius: 0 },
        antiAlias: true,
        autoPad: true,
        validTags: ["div"]
    }
    return settingsRC;
}

function defaultBottomCornersSettings() {
    settingsRC = {
        tl: { radius: 0 },
        tr: { radius: 0 },
        bl: { radius: 10 },
        br: { radius: 10 },
        antiAlias: true,
        autoPad: true,
        validTags: ["div"]
    }
    return settingsRC;
}


function initZIndexMenuSuperior() {
    var zIndexNumber = 1000;
    $('#menu_superior *').each(function() {
        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    })
}


function initRoundedCorners() {
}


function initProducPagination() {
    var _start = $('div#sections').find('li a.main_color').attr('page');
    var _max = $('div#sections').find('li a.ajaxPage').size();
    if (isNaN(_max)) _max = 1;
    if (isNaN(_start)) _start = 0;
    $('#divPaginationProducts').serialScroll({
        target: '#sections',
        items: 'li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
        prev: 'img#prevPaginationButton', // Selector to the 'prev' button (absolute!, meaning it's relative to the document)
        next: 'img#nextPaginationButton', // Selector to the 'next' button (absolute too)
        axis: 'x', // The default is 'y' scroll on both ways
        duration: 10, // Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
        force: true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)

        //queue:false,// We scroll on both axes, scroll both at the same time.
        //event:'click',// On which event to react (click is the default, you probably won't need to specify it)
        //stop:false,// Each click will stop any previous animations of the target. (false by default)
        //lock:true, // Ignore events if already animating (true by default)
        start: _start, // On which element (index) to begin ( 0 is the default, redundant in this case )		
        //cycle:true,// Cycle endlessly ( constant velocity, true is the default )
        step:3, // How many items to scroll each time ( 1 is the default, no need to specify )
        //jump:false, // If true, items become clickable (or w/e 'event' is, and when activated, the pane scrolls to them)
        //lazy:false,// (default) if true, the plugin looks for the items on each event(allows AJAX or JS content, or reordering)
        //interval:100, // It's the number of milliseconds to automatically go to the next
        constant:true, // constant speed

        onBefore: function(e, elem, $pane, $items, pos) {
            /**
            * 'this' is the triggered element 
            * e is the event object
            * elem is the element we'll be scrolling to
            * $pane is the element being scrolled
            * $items is the items collection at this moment
            * pos is the position of elem in the collection
            * if it returns false, the event will be ignored
            */
            //those arguments with a $ are jqueryfied, elem isn't.
            e.preventDefault();
            if (this.blur)
                this.blur();
        },
        onAfter: function(elem) {
            //'this' is the element being scrolled ($pane) not jqueryfied
        }
    });

    $('#nextPaginationButton').bind('click', function () {
        $('#sections').trigger('next');
        var nextPage = $(this).attr('page');
        if (isNaN(nextPage)) nextPage = 0;
        $('a.ajaxPage[page=' + nextPage + ']').trigger('click');
    });

    $('#prevPaginationButton').bind('click', function () {
        $('#sections').trigger('prev');
        var prevPage = $(this).attr('page');
        if (isNaN(prevPage)) prevPage = 0;
        $('a.ajaxPage[page=' + prevPage + ']').trigger('click');
    });

/*
    $('div#printButton').corner(defaultAllCornersSettings());
    $('div#productListPaginateDiv').corner(defaultBottomCornersSettings());
*/
    $('a.ajaxPage').bind('click', function(event) {
        $('div#productosDiv').html($('<img />').attr('src', '/img/ajax-loader.gif'));
        event.preventDefault();
        $.post('/product.mvc/ajax/' + $(this).attr('page')+'/'+20, {},
                function(data) {
                    $('div#productosDivContainer').html(data);
                    initProducPagination();
                }
        );
    });


    $('select#numItemsPerPage').bind('change', function (event) {
        $('div#productosDiv').html($('<img />').attr('src', '/img/ajax-loader.gif'));
        event.preventDefault();
        $.post('/product.mvc/ajax/0/' + $('select#numItemsPerPage').val(), {},
                function (data) {
                    $('div#productosDivContainer').html(data);
                    initProducPagination();
                }
        );
    });

}

function sameBillingAsDelivery(form) {
    if ($(form).find('input#deliverySameAsBilling').attr('checked')) {
        var miArray = ['address', 'town', 'post_code', 'country'];
        for (var i = 0; i < miArray.length; i++) {
            $(form).find('input#d_' + miArray[i]).val($(form).find('input#b_' + miArray[i]).val());
        }
    }
}


function checkValidBrowser() {
    //if ($.browser.msie && $.browser.version.substr(0,1)<7) alert($('input#browserNotValidMsg').val());7	
	//if ($.browser.msie && $.browser.version.substr(0,1)<7) alert($('input#browserNotValidMsg').val());
}


function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function checkCloseBrowser() {
    $(window).unload(function () {
        //setCookie("ASP.NET_SessionId", "", -1);
        //setCookie(".YPSFORMSAUTH", "", -1);
    });
}


$(document).ready(function () {

    checkValidBrowser();

    //checkCloseBrowser();

    //initGoogleAnalytics();

    initPopUps();

    $("a#linkLegalTermsPopUp").fancybox();

    $('form#formSingInHeader').find('input#password').bind('keypress', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode
            $('#buttonSingInHeader').click();
        }
    });

    $('.fix-z-index').bgiframe();


    $("#uploadlogoformbutton").click(function () {
        $.fancybox({ href: '/image.aspx/logoUploadForm',
            centerOnScroll: true,
            autoDimensions: true
        });
    });


    $("#registerPopUpButton").click(function () {
        $.fancybox({ href: '/user.mvc/register',
            centerOnScroll: true,
            autoDimensions: true,
            onComplete: function () {
                initRegisterLogic();

            }
        });
    });



    $("#registerPopUpButtonLoginPage").click(function () {
        $.fancybox({ href: '/user.mvc/registerLoginPage',
            centerOnScroll: true,
            autoDimensions: true,
            onComplete: function () {
                initRegisterLogicLoginPage();
            }
        });
    });


    $("#forgotPasswordPopUpButton").click(function () {
        $.fancybox({ href: '/user.mvc/forgotpassword',
            centerOnScroll: true,
            autoDimensions: true,
            onComplete: function () {
                //$('div#buttonSubmitForgetPassLoginDiv').corner(defaultAllCornersSettings());
                $('#buttonSubmitForgetPass').click(function () {
                    $('form#formForgotPassword').submit();
                });
            }
        });
    });

    $("#sigInButton").click(function () {
        $('body').trigger('toggleTopToolBar');
    });


    $('body').bind('toggleTopToolBar', function () {
        $("#topToolbarDiv").toggle();
        $("#topToolbarExpandedDiv").toggle();
    });





    $('form#formForgotPassword').live('submit', function () {
        $.fancybox.showActivity();
        var datos = $('form#formForgotPassword').serialize();
        $.fancybox({
            href: "/sharedviews.mvc/loadingPopUp",
            onComplete: function () {
                $.post(
                    "/user.mvc/forgotpassword",
                    datos,
                    function (data) {
                        $.fancybox({ content: data });
                    }
                );
            }
        });
        return false;
    });


    $('#buttonSingInHeader').bind('click', function () {
        var datos = $('form#formSingInHeader').serialize();
        $.fancybox({
            href: "/sharedviews.mvc/loadingPopUp",
            modal: true,
            onComplete: function () {
                $.ajax({
                    type: "POST",
                    url: "/user.mvc/singin",
                    data: datos,
                    dataType: "json",
                    success: function (data) {
                        if (data.okey) {
                            document.location.href = data.url;
                        }
                        else {
                            $.fancybox({ content: data.msg });
                        }
                    }
                });
            }
        });
        return false;
    });


    $('#buttonSubmitShopFormLogin').bind('click', function () {
        $('form#ShopFormLogin').submit();
    });


    $('body').bind('ajaxSuccess', function (event, request, settings) {
        //alert("oo");
    });


    //Corregir bug en explorer con el z-index para eliminar problema con curvycornersw
    initZIndexMenuSuperior();
    initRoundedCorners();

    /*
    var closingBrowser = true;
    $(function () {
        $("a,input[type=submit]").click(function () { closingBrowser = false; });
        $(window).unload(function () {
            if (closingBrowser) {
                jQuery.ajax({ url: "/User.mvc/singout", async: false });
            }
        });
    });
    */

});

function initRegisterLogic() {
    $('form#formRegistration').bind('submit', function () {
        sameBillingAsDelivery('form#formRegistration');
        var datos = $('form#formRegistration').serialize();
        $.fancybox({
            href: "/sharedviews.mvc/loadingPopUp",
            onComplete: function () {
                $.post("/user.mvc/register",
                                datos,
                                function (data) {
                                    $.fancybox({ content: data });
                                    initRegisterLogic();
                                }
                        );
            }
        });
        return false;
    });

    $('#submitFormRegistrationButton').bind('click', function () {
        $('form#formRegistration').submit();
    });

    $('body').trigger('toggleTopToolBar');
}

function initRegisterLogicLoginPage() {
    $('form#formRegistration').bind('submit', function () {
        sameBillingAsDelivery('form#formRegistration');
        var datos = $('form#formRegistration').serialize();
        $.fancybox({
            href: "/sharedviews.mvc/loadingPopUp",
            onComplete: function () {
                $.post("/user.mvc/registerLoginPage",
                                datos,
                                function (data) {
                                    $.fancybox({ content: data });
                                    initRegisterLogicLoginPage();
                                }
                        );
            }
        });
        return false;
    });


    $('#submitFormRegistrationButton').bind('click', function () {
        $('form#formRegistration').submit();
    });
}


function onSaveProductJpeg(a,b) {
}


