var atc = false;
var lastSub = null;
var subreset = 0;
var itemcount;
var ma0 = null;
var itemsWidth;
var scat = null;

deepremove = function (src, prop) {
    var newobj = {};
    src[prop] = null;
    for (property in src) {
        if (property != prop) {
            if ((src[property] != {} && src[property] != null && src[property] != undefined)) {
                newobj[property] = src[property];
            }
        }
    }
    delete src;
    return newobj;
};


$(function () {

    jQuery.fx.interval = 20;

    ma0 = $("div#ma0");
    ma0.show();
    updateCart();


    /* begin navigation code */
    $('div#header div#submenu ul li div').each(function () {
        var largest = 0;
        $(this).children('a').each(function () {
            var mw = parseInt($(this).innerWidth(), 10);
            if (mw > largest)  largest = mw;
        });
        $(this).css('width', (largest + 20) + 'px');
    });

    $("nav ul#main>li").mouseover(function (ev) {
        var cn = $("li#" + $(this).attr('data-child'));
        $(this).css("color", "#ce0404");
        $(this).siblings().css("color", "black");
        if (lastSub != null) {
            lastSub.hide(0);
            clearTimeout(subreset);
        }
        lastSub = cn;
        cn.parent().stop();
        var offset = cn.children(':first-child').outerWidth();
        cn.parent().css({width:parseInt($(this).position().left, 10) + offset - 12});
        cn.parent().animate({height:"80px"}, 500);
        cn.fadeIn('fast');
        cn.siblings().hide();
        showLines.apply(this);
    });


    $('.atn').live('click', function () {
        var fsrc = $(this).data('fsrc');
        $(this).hide();
        $(this).siblings().show();
        $('img.fs').attr('src', fsrc);
    });

    $("div#submenu.inner ul.sub").hover(
        function () {
            clearTimeout(subreset);
        },
        function () {
            subreset = setTimeout(hideSub, 500);
        });
    $("nav").noSelect();
    $('.sidescroller .ss_drag').draggable({
        containment:"parent",
        scroll:false,
        axis:'x',
        drag:function (ev, ui) {
            updateCounterStatus(ui);
        }
    });


    $('a.moreposts').click(function (e) {
        e.preventDefault();
        $('.blog .hidden, div.blogpagination.hidden').removeClass('hidden');
        $(this).hide();
        contentheight = -1;
        setContentArea();
    });

    window.addEvent('onAfterAjaxUpdate', function (element,id) {
        contentheight = -1;
        setContentArea();
        if(atc && id=='cart') {
            atc = false;
            $('div#header span#mini_cart').addClass('active');
            setTimeout(function(){ $('div#header span#mini_cart').removeClass('active'); },4000)
        }
    });

    $('a.blrm').click(function (ev) {
        ev.preventDefault();
        var $p = $(this).parent().parent();
        $p.find('.blrm').hide();
        $p.find('.blbk').show();

        var $ho = $p.children('.bldesc').outerHeight();
        var $h = $p.children('.blbody').outerHeight();
        $h = ($h + 20 ) + 'px';
        $p.children('.blbody').css({height:$ho});
        $p.children('.bldesc').hide();
        $p.children('.blbody').show();
        $p.children('.blbody').animate(
            {height:$h},
            {
                duration:200,
                step:function () {
                    contentheight = -1;
                    setContentArea();
                }
            }
        );
    });
    $('a.blbk').click(function (ev) {
        ev.preventDefault();
        var $p = $(this).parent().parent();
        $p.find('.blrm').show();
        $p.find('.blbk').hide();

        $p.children('.blbody').slideUp();
        $p.children('.bldesc').slideDown(200, function () {
            contentheight = -1;
            setContentArea();
        });
    });

    $('input[name=query]').keyup(function () {
        $('#searchbottomr input').val($(this).val());
    });

    $('#searchbottomr input').live('keyup', function (e) {
        if (e.keyCode == 13) {
            $("#applysearchfilters").click();
        } else {
            $('input[name=query]').val($(this).val());
        }
    });


    $('li.product').live('click', function (ev) {
        // ajaxify product page
        var $p = $(this);//.closest('li.product');
        ev.preventDefault();
        currpidx = $p.data('idx');
        popup.showPageContent($p.data('href'));
    });
    $('li.product').live('mouseover',
        function () {
            lastScrollHoverItem = $(this);
            if(isScrolling) return false;
            $(this).stop(true, true).animate({opacity:1});
            $(this).children('div.info').stop(true, true).slideDown(150);
        });
    $('li.product').live('mouseleave',
        function () {
            if(isScrolling) return false;
            $(this).stop(true, true).animate({opacity:0.7});
            $(this).children('div.info').stop(true, true).slideUp(150);
        }
    );
    var delayitvl = 0;
    var imgsloaded = 0;
    //$('li.product div.image a img').load(function(){
    //    imgsloaded++;
    //    if(imgsloaded == itemcount) {
    $('ul.product_list').waitForImages(function () {
    }, function (el, n1, n2) {
        if (imgsloaded == 0) $('.sidescroller').animate({opacity:1});
        imgsloaded++;
        $(this).parent().parent().parent().fadeTo(200, 0.7);
    });
    // }
    //});

    $('#selectwatches').click(function (ev) {
        ev.preventDefault();
        $('#home').fadeOut(200, function () {
            $('#select').fadeIn();
        })
    });


    $('.uao .navsprite').click(function (ev) {

        scrollProducts($(this).is('.left'));

    });

    $('.product_details .thumbs .thumb img').live('click', function (ev) {
        var bigimg = $(this).closest('.product_details').children('div.image').children('img');
        bigimg.attr('src', $(this).data('largesrc'));
    });

    itemcount = $('ul.sscontainer li').length;
    $('.side_by_side_products').fadeIn(100);
    itemsWidth = parseFloat($('.sscontainer form').outerWidth()) - 960;


    setup_searchFunctionality();


    updateCounterStatus({position:{left:0}});
    setContentArea();

    $(window).resize(function () {
        clearTimeout(scat);
        scat = setTimeout(setContentArea, 10);
    });
    $('ul.product_list').mousewheel(function (event, delta) {
        scrollProducts(delta < 0 ? false : true);
    });


});
var currpidx = null;
var currscrollidx = 0;
var contentheight = -1;
var lastpos = 0;
var isScrolling = false;
var isScrolling_timer = null;
var lastScrollHoverItem = null;

var scrollProducts = function (isLeft) {
    var ui = $('.ss_drag');
    var nl = 0;
    $('.sscontainer').stop(true, true);
    ui.stop(true, true);

    jumpsize = (836 / (itemcount - 4));
    if (isLeft) {
        if (currscrollidx == 0) return;
        // go left
        currscrollidx -= 1;
    } else {
        if (currscrollidx >= itemcount-4) return;
        // go right
        currscrollidx += 1;
    }
    nl = jumpsize * currscrollidx;
if(!isScrolling) lastScrollHoverItem.mouseleave();
    if (nl < 0) nl = 0;
    if (nl > 836) nl = 836;
    var l = nl / 836;
    var pos = l * (itemsWidth);
    lastpos = pos;
    checknavsprites();
    ui.animate({'left':nl + "px"});
    var newml = 240 * currscrollidx;
    if (currscrollidx<=itemcount) $('.sscontainer').animate({'margin-left':'-' + newml + "px"},250,'easeOutQuad');
    isScrolling = true;
    clearTimeout(isScrolling_timer);
    isScrolling_timer = setTimeout(function(){
        isScrolling=false;
        $(lastScrollHoverItem).mouseover();
    }, 150);
}


var checknavsprites = function () {
    if (currscrollidx == 0) {
        $('.uao .navsprite.left').fadeOut();
    } else {
        $('.uao .navsprite.left').fadeIn();
    }
    if (currscrollidx >= itemcount - 4) {
        $('.uao .navsprite.right').fadeOut();
    } else {
        $('.uao .navsprite.right').fadeIn();
    }
}


var setContentArea = function () {
    var windowHeight = $(window).height();
    if (contentheight == -1) {
        contentheight = $('#content.inner').outerHeight();
    }
    windowHeight -= 208 - 38;
    if (contentheight < windowHeight) {
        $('div#footer').css({bottom:0, position:'absolute'});
    } else {
        $('div#footer').css({bottom:'auto', top:'auto', position:'relative'});
    }
    updateLines();
}

var parentcat = null;
function updateLines() {
    /* functionality for highlighting the selected page's parent category */
    if (parentcat != null) {
        var pc = parentcat.toLowerCase();
        var o = $('ul#main li[data-child="' + pc + '"]');
        if (o.length > 0) {
            o.css("color", "#ce0404");
            o.siblings().css("color", "black");
            showLines.apply(o);
        }
    }
}

function updateCounterStatus(ui) {
    var l = parseFloat(ui.position.left, 10) / 836;
    var pos = l * itemsWidth;
    var pv = (0 - pos) + 'px';
    $('.sscontainer').css('margin-left', pv);
    if (pos == 0) {
        $('.uao .navsprite.left').fadeOut();
    } else {
        $('.uao .navsprite.left').fadeIn();
    }
    if (pos >= itemsWidth - 20) {
        $('.uao .navsprite.right').fadeOut();
    } else {
        $('.uao .navsprite.right').fadeIn();
    }
}

function hideSub() {
    lastSub.parent().animate({height:"0px"}, 500);
    updateLines();
}

function updateCart() {
    $("#cart").sendRequest('core:on_null', { update:{'cart':'shop:mini_cart'}, loadIndicator:{show:false} });
}


var ln_lc = 0;
var ln_lt = 0;
var ln_timer = null;

function showLines() {
    /* show the line animation */
    var speed = 20;
    var newLeft = parseInt($(this).position().left);
    var newWidth = parseInt($(this).outerWidth(), 10);
    var numlines = Math.ceil(newWidth / 10);
    ma0.css({opacity:0.4, "left":(newLeft - 30) + "px", "width":"100px"});
    if (ln_timer != null) clearInterval(ln_timer);
    ln_lc = numlines;
    ln_lt = 0;
    ln_timer = setInterval(nextLine, speed);
}

function nextLine() {
    ln_lt++;
    if (ln_lt >= ln_lc) clearInterval(ln_timer);
    ma0.css({"width":100 + (ln_lt * 10) + "px"});

}


/**
 * jQuery Masonry v2.0.110526
 * A dynamic layout plugin for jQuery
 * The flip-side of CSS Floats
 * http://masonry.desandro.com
 *
 * Licensed under the MIT license.
 * Copyright 2011 David DeSandro
 */
//(function(a,b,c){var d=b.event,e;d.special.smartresize={setup:function(){b(this).bind("resize",d.special.smartresize.handler)},teardown:function(){b(this).unbind("resize",d.special.smartresize.handler)},handler:function(a,b){var c=this,d=arguments;a.type="smartresize",e&&clearTimeout(e),e=setTimeout(function(){jQuery.event.handle.apply(c,d)},b==="execAsap"?0:100)}},b.fn.smartresize=function(a){return a?this.bind("smartresize",a):this.trigger("smartresize",["execAsap"])},b.Mason=function(a,c){this.element=b(c),this._create(a),this._init()};var f=["position","height"];b.Mason.settings={isResizable:!0,isAnimated:!1,animationOptions:{queue:!1,duration:500},gutterWidth:0,isRTL:!1,isFitWidth:!1},b.Mason.prototype={_filterFindBricks:function(a){var b=this.options.itemSelector;return b?a.filter(b).add(a.find(b)):a},_getBricks:function(a){var b=this._filterFindBricks(a).css({position:"absolute"}).addClass("masonry-brick");return b},_create:function(c){this.options=b.extend(!0,{},b.Mason.settings,c),this.styleQueue=[],this.reloadItems();var d=this.element[0].style;this.originalStyle={};for(var e=0,g=f.length;e<g;e++){var h=f[e];this.originalStyle[h]=d[h]||null}this.element.css({position:"relative"}),this.horizontalDirection=this.options.isRTL?"right":"left",this.offset={};var i=b(document.createElement("div"));this.element.prepend(i),this.offset.y=Math.round(i.position().top),this.options.isRTL?(i.css({"float":"right",display:"inline-block"}),this.offset.x=Math.round(this.element.outerWidth()-i.position().left)):this.offset.x=Math.round(i.position().left),i.remove();var j=this;setTimeout(function(){j.element.addClass("masonry")},0),this.options.isResizable&&b(a).bind("smartresize.masonry",function(){j.resize()})},_init:function(a){this._getColumns("masonry"),this._reLayout(a)},option:function(a,c){b.isPlainObject(a)&&(this.options=b.extend(!0,this.options,a))},layout:function(a,c){var d,e,f,g,h,i;for(var j=0,k=a.length;j<k;j++){d=b(a[j]),e=Math.ceil(d.outerWidth(!0)/this.columnWidth),e=Math.min(e,this.cols);if(e===1)this._placeBrick(d,this.colYs);else{f=this.cols+1-e,g=[];for(i=0;i<f;i++)h=this.colYs.slice(i,i+e),g[i]=Math.max.apply(Math,h);this._placeBrick(d,g)}}var l={};l.height=Math.max.apply(Math,this.colYs)-this.offset.y,this.options.isFitWidth&&(l.width=this.cols*this.columnWidth-this.options.gutterWidth),this.styleQueue.push({$el:this.element,style:l});var m=this.isLaidOut?this.options.isAnimated?"animate":"css":"css",n=this.options.animationOptions,o;for(j=0,k=this.styleQueue.length;j<k;j++)o=this.styleQueue[j],o.$el[m](o.style,n);this.styleQueue=[],c&&c.call(a),this.isLaidOut=!0},_getColumns:function(){var a=this.options.isFitWidth?this.element.parent():this.element,b=a.width();this.columnWidth=this.options.columnWidth||this.$bricks.outerWidth(!0)||b,this.columnWidth+=this.options.gutterWidth,this.cols=Math.floor((b+this.options.gutterWidth)/this.columnWidth),this.cols=Math.max(this.cols,1)},_placeBrick:function(a,b){var c=Math.min.apply(Math,b),d=0;for(var e=0,f=b.length;e<f;e++)if(b[e]===c){d=e;break}var g={top:c};g[this.horizontalDirection]=this.columnWidth*d+this.offset.x,this.styleQueue.push({$el:a,style:g});var h=c+a.outerHeight(!0),i=this.cols+1-f;for(e=0;e<i;e++)this.colYs[d+e]=h},resize:function(){var a=this.cols;this._getColumns("masonry"),this.cols!==a&&this._reLayout()},_reLayout:function(a){var b=this.cols;this.colYs=[];while(b--)this.colYs.push(this.offset.y);this.layout(this.$bricks,a)},reloadItems:function(){this.$bricks=this._getBricks(this.element.children())},reload:function(a){this.reloadItems(),this._init(a)},appended:function(a,b,c){if(b){this._filterFindBricks(a).css({top:this.element.height()});var d=this;setTimeout(function(){d._appended(a,c)},1)}else this._appended(a,c)},_appended:function(a,b){var c=this._getBricks(a);this.$bricks=this.$bricks.add(c),this.layout(c,b)},remove:function(a){this.$bricks=this.$bricks.not(a),a.remove()},destroy:function(){this.$bricks.removeClass("masonry-brick").each(function(){this.style.position=null,this.style.top=null,this.style.left=null});var c=this.element[0].style;for(var d=0,e=f.length;d<e;d++){var g=f[d];c[g]=this.originalStyle[g]}this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"),b(a).unbind(".masonry")}},b.fn.imagesLoaded=function(a){var b=this.find("img"),d=b.length,e="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",f=this,g=function(){--d<=0&&this.src!==e&&(a.call(f),b.unbind("load",g))};if(!d){a.call(this);return this}b.bind("load",g).each(function(){if(this.complete||this.complete===c){var a=this.src;this.src=e,this.src=a}});return this};var g=function(a){this.console&&console.error(a)};b.fn.masonry=function(a){if(typeof a=="string"){var c=Array.prototype.slice.call(arguments,1);this.each(function(){var d=b.data(this,"masonry");if(!d)g("cannot call methods on masonry prior to initialization; attempted to call method '"+a+"'");else{if(!b.isFunction(d[a])||a.charAt(0)==="_"){g("no such method '"+a+"' for masonry instance");return}d[a].apply(d,c)}})}else this.each(function(){var c=b.data(this,"masonry");c?(c.option(a||{}),c._init()):b.data(this,"masonry",new b.Mason(a,this))});return this}})(window,jQuery);




/* search functionality */

var lastfilter = null;
var lastfilteridx = null;
var searchfilters = {};

function setup_searchFunctionality() {

    /* ajax load search results */
    $('#searchpage span.numbers a').live('click', function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        $.ajax({
            url:url,
            success:function (data) {
                var newsp = $(data).find('#searchpage');
                $('#searchpage').fadeOut(100, function () {
                    $('#searchpage').replaceWith($(newsp));
                    $('#searchpage').fadeIn(100);
                })
            }
        })
    });

    $('#filters #selectors li').click(
        function () {
            //$(this).stop(true,true).animate({opacity:1});
            $(this).siblings().removeClass('selected prev next');
            $(this).addClass('selected');

            $(this).prev('span').addClass('selected prev');
            $(this).next('span').addClass('selected next');


            var idx = $(this).attr('idx');
            lastfilteridx = idx;
            lastfilter = $(this).data('name').trim();
            var child = $(this).parent().parent().find('.options_' + idx);
            child.siblings().hide();
            child.stop(true, true).show();
        });


    $('#filters #selectors li span.mx').live('click', function () {

        var par = $(this).parent();
        var idx = $(par).attr('idx');
        $(this).remove();
        var txt = par.data('name').trim();
        searchfilters = deepremove(searchfilters, txt);
        par.removeClass('active');
        $('#options li.options_' + idx).find('.active').removeClass('active');

    });


    $('#filters #options li div').click(
        function () {
            var opt = $(this).text().trim();

            // create if not exists, default to false
            if (searchfilters[lastfilter] == null) searchfilters[lastfilter] = [];

            // toggle
            var idx = searchfilters[lastfilter].indexOf(opt);
            if (idx == -1) {
                $(this).addClass('active');
                searchfilters[lastfilter].push(opt);
            } else {
                $(this).removeClass('active');
                searchfilters[lastfilter].splice(idx, 1);
            }
            var par = $('#filters #selectors li[idx="' + lastfilteridx + '"]');
            if (searchfilters[lastfilter].length < 1) {
                searchfilters = deepremove(searchfilters, lastfilter);
                par.removeClass('active');
                par.children('.mx').remove();
            } else {
                if (!par.is('.active')) {
                    par.addClass('active');
                    par.append('<span class="mx">x</span>');
                }
            }
        });

    $("#applysearchfilters").live('click', function (e) {
        e.preventDefault();
        var query = $('input[name="query"]').val();
        var url = '/search/';

        $.ajax({
            url:url,
            data:{
                filters:searchfilters,
                query:query
            },
            //type: 'POST',
            success:function (data) {
                var newsp = $(data).find('#searchpage');
                $('#searchpage').fadeOut(100, function () {
                    $('#searchpage').replaceWith($(newsp));
                    $('#searchpage').fadeIn(100);
                })
            }
        })

    });
}

