/*

 jQuery Tools 1.2.5 Scrollable - New wave UI design

 NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.

 http://flowplayer.org/tools/scrollable.html

 Since: March 2008
 Date:    Wed Sep 22 06:02:10 2010 +0000
*/
(function(e){function p(f,c){var b=e(c);return b.length<2?b:f.parent().find(c)}function u(f,c){var b=this,n=f.add(b),g=f.children(),l=0,j=c.vertical;k||(k=b);if(g.length>1)g=e(c.items,f);e.extend(b,{getConf:function(){return c},getIndex:function(){return l},getSize:function(){return b.getItems().size()},getNaviButtons:function(){return o.add(q)},getRoot:function(){return f},getItemWrap:function(){return g},getItems:function(){return g.children(c.item).not("."+c.clonedClass)},move:function(a,d){return b.seekTo(l+
a,d)},next:function(a){return b.move(1,a)},prev:function(a){return b.move(-1,a)},begin:function(a){return b.seekTo(0,a)},end:function(a){return b.seekTo(b.getSize()-1,a)},focus:function(){return k=b},addItem:function(a){a=e(a);if(c.circular){g.children("."+c.clonedClass+":last").before(a);g.children("."+c.clonedClass+":first").replaceWith(a.clone().addClass(c.clonedClass))}else g.append(a);n.trigger("onAddItem",[a]);return b},seekTo:function(a,d,h){a.jquery||(a*=1);if(c.circular&&a===0&&l==-1&&d!==
0)return b;if(!c.circular&&a<0||a>b.getSize()||a<-1)return b;var i=a;if(a.jquery)a=b.getItems().index(a);else i=b.getItems().eq(a);var r=e.Event("onBeforeSeek");if(!h){n.trigger(r,[a,d]);if(r.isDefaultPrevented()||!i.length)return b}i=j?{top:-i.position().top}:{left:-i.position().left};l=a;k=b;if(d===undefined)d=c.speed;g.animate(i,d,c.easing,h||function(){n.trigger("onSeek",[a])});return b}});e.each(["onBeforeSeek","onSeek","onAddItem"],function(a,d){e.isFunction(c[d])&&e(b).bind(d,c[d]);b[d]=function(h){h&&
e(b).bind(d,h);return b}});if(c.circular){var s=b.getItems().slice(-1).clone().prependTo(g),t=b.getItems().eq(1).clone().appendTo(g);s.add(t).addClass(c.clonedClass);b.onBeforeSeek(function(a,d,h){if(!a.isDefaultPrevented())if(d==-1){b.seekTo(s,h,function(){b.end(0)});return a.preventDefault()}else d==b.getSize()&&b.seekTo(t,h,function(){b.begin(0)})});b.seekTo(0,0,function(){})}var o=p(f,c.prev).click(function(){b.prev()}),q=p(f,c.next).click(function(){b.next()});if(!c.circular&&b.getSize()>1){b.onBeforeSeek(function(a,
d){setTimeout(function(){if(!a.isDefaultPrevented()){o.toggleClass(c.disabledClass,d<=0);q.toggleClass(c.disabledClass,d>=b.getSize()-1)}},1)});c.initialIndex||o.addClass(c.disabledClass)}c.mousewheel&&e.fn.mousewheel&&f.mousewheel(function(a,d){if(c.mousewheel){b.move(d<0?1:-1,c.wheelSpeed||50);return false}});if(c.touch){var m={};g[0].ontouchstart=function(a){a=a.touches[0];m.x=a.clientX;m.y=a.clientY};g[0].ontouchmove=function(a){if(a.touches.length==1&&!g.is(":animated")){var d=a.touches[0],h=
m.x-d.clientX;d=m.y-d.clientY;b[j&&d>0||!j&&h>0?"next":"prev"]();a.preventDefault()}}}c.keyboard&&e(document).bind("keydown.scrollable",function(a){if(!(!c.keyboard||a.altKey||a.ctrlKey||e(a.target).is(":input")))if(!(c.keyboard!="static"&&k!=b)){var d=a.keyCode;if(j&&(d==38||d==40)){b.move(d==38?-1:1);return a.preventDefault()}if(!j&&(d==37||d==39)){b.move(d==37?-1:1);return a.preventDefault()}}});c.initialIndex&&b.seekTo(c.initialIndex,0,function(){})}e.tools=e.tools||{version:"1.2.5"};e.tools.scrollable=
{conf:{activeClass:"active",circular:false,clonedClass:"cloned",disabledClass:"disabled",easing:"swing",initialIndex:0,item:null,items:".items",keyboard:true,mousewheel:false,next:".next",prev:".prev",speed:400,vertical:false,touch:true,wheelSpeed:0}};var k;e.fn.scrollable=function(f){var c=this.data("scrollable");if(c)return c;f=e.extend({},e.tools.scrollable.conf,f);this.each(function(){c=new u(e(this),f);e(this).data("scrollable",c)});return f.api?c:this}})(jQuery);

/*

 jQuery Tools 1.2.5 / Scrollable Autoscroll

 NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.

 http://flowplayer.org/tools/scrollable/autoscroll.html

 Since: September 2009
 Date:    Wed Sep 22 06:02:10 2010 +0000
*/
(function(b){var f=b.tools.scrollable;f.autoscroll={conf:{autoplay:true,interval:3E3,autopause:true}};b.fn.autoscroll=function(c){if(typeof c=="number")c={interval:c};var d=b.extend({},f.autoscroll.conf,c),g;this.each(function(){var a=b(this).data("scrollable");if(a)g=a;var e,h=true;a.play=function(){if(!e){h=false;e=setInterval(function(){a.next()},d.interval)}};a.pause=function(){e=clearInterval(e)};a.stop=function(){a.pause();h=true};d.autopause&&a.getRoot().add(a.getNaviButtons()).hover(a.pause,
a.play);d.autoplay&&a.play()});return d.api?g:this}})(jQuery);

/*

 jQuery Tools 1.2.5 / Scrollable Navigator

 NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.

 http://flowplayer.org/tools/scrollable/navigator.html

 Since: September 2009
 Date:    Wed Sep 22 06:02:10 2010 +0000
*/
(function(d){function p(b,g){var h=d(g);return h.length<2?h:b.parent().find(g)}var m=d.tools.scrollable;m.navigator={conf:{navi:".navi",naviItem:null,activeClass:"active",indexed:false,idPrefix:null,history:false}};d.fn.navigator=function(b){if(typeof b=="string")b={navi:b};b=d.extend({},m.navigator.conf,b);var g;this.each(function(){function h(a,c,i){e.seekTo(c);if(j){if(location.hash)location.hash=a.attr("href").replace("#","")}else return i.preventDefault()}function f(){return k.find(b.naviItem||
"> *")}function n(a){var c=d("<"+(b.naviItem||"a")+"/>").click(function(i){h(d(this),a,i)}).attr("href","#"+a);a===0&&c.addClass(l);b.indexed&&c.text(a+1);b.idPrefix&&c.attr("id",b.idPrefix+a);return c.appendTo(k)}function o(a,c){a=f().eq(c.replace("#",""));a.length||(a=f().filter("[href="+c+"]"));a.click()}var e=d(this).data("scrollable"),k=b.navi.jquery?b.navi:p(e.getRoot(),b.navi),q=e.getNaviButtons(),l=b.activeClass,j=b.history&&d.fn.history;if(e)g=e;e.getNaviButtons=function(){return q.add(k)};
f().length?f().each(function(a){d(this).click(function(c){h(d(this),a,c)})}):d.each(e.getItems(),function(a){n(a)});e.onBeforeSeek(function(a,c){setTimeout(function(){if(!a.isDefaultPrevented()){var i=f().eq(c);!a.isDefaultPrevented()&&i.length&&f().removeClass(l).eq(c).addClass(l)}},1)});e.onAddItem(function(a,c){c=n(e.getItems().index(c));j&&c.history(o)});j&&f().history(o)});return b.api?g:this}})(jQuery);

/* Notifications */

(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);
(function(A){A.jScrollPane={active:[]};A.fn.jScrollPane=function(C){C=A.extend({},A.fn.jScrollPane.defaults,C);var B=function(){return false};return this.each(function(){var O=A(this);O.css("overflow","hidden");var X=this;if(A(this).parent().is(".jScrollPaneContainer")){var Ac=C.maintainPosition?O.position().top:0;var L=A(this).parent();var d=L.innerWidth();var Ad=L.outerHeight();var M=Ad;A(">.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown",L).remove();O.css({top:0})}else{var Ac=0;this.originalPadding=O.css("paddingTop")+" "+O.css("paddingRight")+" "+O.css("paddingBottom")+" "+O.css("paddingLeft");this.originalSidePaddingTotal=(parseInt(O.css("paddingLeft"))||0)+(parseInt(O.css("paddingRight"))||0);var d=O.innerWidth();var Ad=O.innerHeight();var M=Ad;O.wrap(A("<div></div>").attr({className:"jScrollPaneContainer"}).css({height:Ad+"px",width:d+"px"}));A(document).bind("emchange",function(Ae,Af,p){O.jScrollPane(C)})}if(C.reinitialiseOnImageLoad){var N=A.data(X,"jScrollPaneImagesToLoad")||A("img",O);var G=[];if(N.length){N.each(function(p,Ae){A(this).bind("load",function(){if(A.inArray(p,G)==-1){G.push(Ae);N=A.grep(N,function(Ag,Af){return Ag!=Ae});A.data(X,"jScrollPaneImagesToLoad",N);C.reinitialiseOnImageLoad=false;O.jScrollPane(C)}}).each(function(Af,Ag){if(this.complete||this.complete===undefined){this.src=this.src}})})}}var o=this.originalSidePaddingTotal;var l={height:"auto",width:d-C.scrollbarWidth-C.scrollbarMargin-o+"px"};if(C.scrollbarOnLeft){l.paddingLeft=C.scrollbarMargin+C.scrollbarWidth+"px"}else{l.paddingRight=C.scrollbarMargin+"px"}O.css(l);var m=O.outerHeight();var i=Ad/m;if(i<0.99){var H=O.parent();H.append(A("<div></div>").attr({className:"jScrollPaneTrack"}).css({width:C.scrollbarWidth+"px"}).append(A("<div></div>").attr({className:"jScrollPaneDrag"}).css({width:C.scrollbarWidth+"px"}).append(A("<div></div>").attr({className:"jScrollPaneDragTop"}).css({width:C.scrollbarWidth+"px"}),A("<div></div>").attr({className:"jScrollPaneDragBottom"}).css({width:C.scrollbarWidth+"px"}))));var z=A(">.jScrollPaneTrack",H);var P=A(">.jScrollPaneTrack .jScrollPaneDrag",H);if(C.showArrows){var g;var Ab;var S;var r;var j=function(){if(r>4||r%4==0){y(u+Ab*b)}r++};var K=function(p){A("html").unbind("mouseup",K);g.removeClass("jScrollActiveArrowButton");clearInterval(S)};var Z=function(){A("html").bind("mouseup",K);g.addClass("jScrollActiveArrowButton");r=0;j();S=setInterval(j,100)};H.append(A("<a></a>").attr({href:"javascript:;",className:"jScrollArrowUp"}).css({width:C.scrollbarWidth+"px"}).html("Scroll up").bind("mousedown",function(){g=A(this);Ab=-1;Z();this.blur();return false}).bind("click",B),A("<a></a>").attr({href:"javascript:;",className:"jScrollArrowDown"}).css({width:C.scrollbarWidth+"px"}).html("Scroll down").bind("mousedown",function(){g=A(this);Ab=1;Z();this.blur();return false}).bind("click",B));var Q=A(">.jScrollArrowUp",H);var J=A(">.jScrollArrowDown",H);if(C.arrowSize){M=Ad-C.arrowSize-C.arrowSize;z.css({height:M+"px",top:C.arrowSize+"px"})}else{var s=Q.height();C.arrowSize=s;M=Ad-s-J.height();z.css({height:M+"px",top:s+"px"})}}var w=A(this).css({position:"absolute",overflow:"visible"});var D;var Y;var b;var u=0;var V=i*Ad/2;var a=function(Ae,Ag){var Af=Ag=="X"?"Left":"Top";return Ae["page"+Ag]||(Ae["client"+Ag]+(document.documentElement["scroll"+Af]||document.body["scroll"+Af]))||0};var f=function(){return false};var v=function(){n();D=P.offset(false);D.top-=u;Y=M-P[0].offsetHeight;b=2*C.wheelSpeed*Y/m};var E=function(p){v();V=a(p,"Y")-u-D.top;A("html").bind("mouseup",T).bind("mousemove",h);if(A.browser.msie){A("html").bind("dragstart",f).bind("selectstart",f)}return false};var T=function(){A("html").unbind("mouseup",T).unbind("mousemove",h);V=i*Ad/2;if(A.browser.msie){A("html").unbind("dragstart",f).unbind("selectstart",f)}};var y=function(Ae){Ae=Ae<0?0:(Ae>Y?Y:Ae);u=Ae;P.css({top:Ae+"px"});var Af=Ae/Y;w.css({top:((Ad-m)*Af)+"px"});O.trigger("scroll");if(C.showArrows){Q[Ae==0?"addClass":"removeClass"]("disabled");J[Ae==Y?"addClass":"removeClass"]("disabled")}};var h=function(p){y(a(p,"Y")-D.top-V)};var q=Math.max(Math.min(i*(Ad-C.arrowSize*2),C.dragMaxHeight),C.dragMinHeight);P.css({height:q+"px"}).bind("mousedown",E);var k;var R;var I;var t=function(){if(R>8||R%4==0){y((u-((u-I)/2)))}R++};var Aa=function(){clearInterval(k);A("html").unbind("mouseup",Aa).unbind("mousemove",e)};var e=function(p){I=a(p,"Y")-D.top-V};var U=function(p){v();e(p);R=0;A("html").bind("mouseup",Aa).bind("mousemove",e);k=setInterval(t,100);t()};z.bind("mousedown",U);H.bind("mousewheel",function(Ae,Ag){v();n();var Af=u;y(u-Ag*b);var p=Af!=u;return !p});var F;var W;function c(){var p=(F-u)/C.animateStep;if(p>1||p<-1){y(u+p)}else{y(F);n()}}var n=function(){if(W){clearInterval(W);delete F}};var x=function(Af,p){if(typeof Af=="string"){$e=A(Af,O);if(!$e.length){return}Af=$e.offset().top-O.offset().top}H.scrollTop(0);n();var Ae=-Af/(Ad-m)*Y;if(p||!C.animateTo){y(Ae)}else{F=Ae;W=setInterval(c,C.animateInterval)}};O[0].scrollTo=x;O[0].scrollBy=function(Ae){var p=-parseInt(w.css("top"))||0;x(p+Ae)};v();x(-Ac,true);A("*",this).bind("focus",function(Ah){var Ag=A(this);var Aj=0;while(Ag[0]!=O[0]){Aj+=Ag.position().top;Ag=Ag.offsetParent()}var p=-parseInt(w.css("top"))||0;var Ai=p+Ad;var Af=Aj>p&&Aj<Ai;if(!Af){var Ae=Aj-C.scrollbarMargin;if(Aj>p){Ae+=A(this).height()+15+C.scrollbarMargin-Ad}x(Ae)}});if(location.hash){x(location.hash)}A(document).bind("click",function(Ae){$target=A(Ae.target);if($target.is("a")){var p=$target.attr("href");if(p.substr(0,1)=="#"){x(p)}}});A.jScrollPane.active.push(O[0])}else{O.css({height:Ad+"px",width:d-this.originalSidePaddingTotal+"px",padding:this.originalPadding});O.parent().unbind("mousewheel")}})};A.fn.jScrollPane.defaults={scrollbarWidth:10,scrollbarMargin:5,wheelSpeed:18,showArrows:false,arrowSize:0,animateTo:false,dragMinHeight:1,dragMaxHeight:99999,animateInterval:100,animateStep:3,maintainPosition:true,scrollbarOnLeft:false,reinitialiseOnImageLoad:false};A(window).bind("unload",function(){var C=A.jScrollPane.active;for(var B=0;B<C.length;B++){C[B].scrollTo=C[B].scrollBy=null}})})(jQuery);
(function($){var template;var counter=0;$.notifications=function(msg,options){counter++;var settings=$.extend({},$.notifications.defaults,options);if(!template){template=$('<div id="jquery-notifications"></div>').appendTo(document.body);}
var n=$('<div class="'+settings.type+'" id="jquery-notifications-'+counter+'">'+msg+'</div>').hide().appendTo("#jquery-notifications");if(settings.effect=="fade"){n.fadeIn(settings.fadeSpeed);}else{n.slideDown(settings.fadeSpeed);}
if(settings.stick){var close=$('<a href="javascript:void(0);">'+settings.close+'</a>').click(function(){if(settings.effect=="fade"){$(this.parentNode).fadeOut(settings.fadeSpeed,function(){$(this).remove();});}
else{$(this.parentNode).slideUp(settings.fadeSpeed,function(){$(this).remove();});}});close.appendTo(n);}
if(!settings.stick){var notificationsDelayer=delayTimer(settings.timeout);notificationsDelayer(update,{counter:counter,effect:settings.effect,fadeSpeed:settings.fadeSpeed});}};$.notifications.success=function(msg,options){return $.notifications(msg,$.extend({},options,{type:"success"}));};$.notifications.error=function(msg,options){return $.notifications(msg,$.extend({stick:true},options,{type:"error"}));};$.notifications.warning=function(msg,options){return $.notifications(msg,$.extend({},options,{type:"warning"}));};function update(params){if(params.effect=="fade"){$("#jquery-notifications-"+params.counter).fadeOut(params.fadeSpeed,function(){$(this).remove();});}else{$("#jquery-notifications-"+params.counter).slideUp(params.fadeSpeed,function(){$(this).remove();});}}
function delayTimer(delay){var timer;return function(fn,params){timer=clearTimeout(timer);if(fn)
timer=setTimeout(function(){fn(params);},delay);return timer;};}
$.notifications.defaults={type:"notice",timeout:10000,stick:false,fadeSpeed:800,close:"x",effect:"fade"};$.n=$.notifications;})(jQuery);


$(function(){
    var DEBUG_MODE = true; // Set this value to false for production

    if(typeof(console) === 'undefined') {
        console = {}
    }

    if(!DEBUG_MODE || typeof(console.log) === 'undefined') {
        // FYI: Firebug might get cranky...
        console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
    }
    if($("#slideshow").length)
        $("#slideshow").scrollable({circular:true}).autoscroll({autoplay:true, interval:5000, autopause:true}).navigator({navi:".controls .pos_indicator"});

    loop_time = 5000;
    pageimage_last = $("#slides").children("li").size() - 1;
    pageimages = $("#slides li").length
    //console.log("page images:",pageimages);
    if (pageimages){
        loop_pageimages();
    }

    $("#slides li a").hover(
        function(){
            $("#slides li").stop();
            if (pageimages_timer)
                clearTimeout(pageimages_timer);
        },
        function(){
            if (pageimages)
                loop_pageimages();
        }
    );

    function loop_pageimages(){
        var current=$("#slides").children(".current");
        var first=$("#slides").children("li").eq(0);

        current.fadeOut("slow").toggleClass("current");

        if (current.index() != pageimage_last){
            current.next().fadeIn("slow").toggleClass("current");
        }
        else{
            first.fadeIn("slow").toggleClass("current");
        }
        pageimages_timer = setTimeout(loop_pageimages,loop_time);
    }

    $("#id_copy_address").change(function(){
        $next_btn = $(this).parents("tr").siblings("tr").find(".right");
        $nav = $(this).parents("tr").next().find(".checkout_nav");
        $tbody = $(this).parents("tbody").next();
        //console.log("Text on the right button",$next_btn.text());
        if($(this).is(":checked") && $next_btn.is(":contains('shipping')")){
            //console.log("Shipping = billings; removing shipping tbody");
            $temp_btn = $next_btn.detach();
            $t = $tbody.find(".right").clone(true);
            $nav.append($t);
            $temp_tbody = $tbody.detach();
        }
        else{
            $nav.append($tbody.find(".right"));
            $temp_tbody.insertAfter($(this).parents("tbody"));
            $nav.find(".right").replaceWith($temp_btn);
        }
    });

    $("#checkout_info .checkout_nav a").click(function(){
        if($(this).hasClass("left")){
            //console.log("clicked on back ...");
            $(this).parents("tbody").slideUp().queue(function(){
               //console.log("number of tbody siblings:",$(this).siblings("tbody").size());
               //console.log("section to be shown is:",$(this).next().find("h4").text());
               $(this).prev().slideDown();
               $(this).dequeue();
            });
        }
        else{
            //console.log("clicked on continue ...");
            $(this).parents("tbody").slideUp().queue(function(){
               //console.log("number of tbody siblings:",$(this).siblings("tbody").size());
               //console.log("section to be shown is:",$(this).next().find("h4").text());
               $(this).next().slideDown();
               $(this).dequeue();
            });
        }
        return false;
    });

    last = $(".featured ul").children("li").eq($(".featured ul").children("li").size() - 1);
    first=$(".featured ul").children("li").eq(0);

    $(".featured .prev").click(function(){
        previtem();
        return false;
    });

    $(".featured .next").click(function(){
        nextitem();
        return false;
    });

    function nextitem(){
        current=$(".featured ul").children(".current");

        $(".featured ul").children("li").stop();
        current.fadeOut("slow").toggleClass("current");

        if (current.index() != last.index()){
            current.next().fadeIn("slow").toggleClass("current");
        }
        else{
            first.fadeIn("slow").toggleClass("current");
        }
    }

    function previtem(){
        current=$(".featured ul").children(".current");

        $(".featured ul").children("li").stop();
        current.fadeOut("slow").toggleClass("current");

        if (current.index() != first.index()){
            current.prev().fadeIn("slow").toggleClass("current");
        }
        else{
            last.fadeIn("slow").toggleClass("current");
        }
    }

    $.fn.equalizeHeights = function(){
      return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) )
    }

    if($("div#var_attributes").children("ul.productattributes").length){
        height = Math.max.apply(Math, $("div#var_attributes").children("ul.productattributes").map(function(i,e){ return $(e).height() }).get());
        //console.log("Computed height is :",height);
        $("div#var_attributes").height(height)
    }

    $(".featured li").equalizeHeights();
    if($(".featured").size() > 0){
        $(".featured ul").height($(".featured li").height().toString()+'px');
    }

    $("#category_tree a.current:hidden").parents("ul").show();
    $("#category_tree a.current").each(function(){
        $(this).siblings("ul:hidden").show();
    })

    if(($("#main").height() < $("#sidebar-left").height()) || ($("#main").height() < $("#sidebar-right").height())){
        if ($("#sidebar-left").height() < $("#sidebar-right").height()){
            $("#main").height($("#sidebar-right").outerHeight());
        }
        else{
            $("#main").height($("#sidebar-left").height());
        }
    }

    $(".ajax_form").submit(function(){
        var f = $(this);
        var fld = f.find("input[type=hidden]");
        var s = fld[0].name;
        var r = s.split("").reverse().join("");
        fld[0].value = r;
        f.find("input.submit")
            .val('Sending...')
            .attr('disabled', 'disabled');
        $.post(f.attr("action"),
            f.serialize(),
            function(data) {
                f.find("input.submit")
                    .removeAttr('disabled')
                    .val('Sent');
                if(data.type == 'error'){
                    $.n(data.msg);
                    //console.log("received error");
                }
                else
                {
                    //console.log("received success");
                    $.n.success(data.msg);
                }
            },
            'json'
        );
        return false;
    });

    function addCommas(nStr) {
        nStr += '';
        var x = nStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }

    $("#add2cart form").submit(function(){
        var f = $(this);
        $.post(f.attr("action"),
            f.serialize(),
            function(data) {
                if(data.results == 'Success'){
                    amt = parseFloat(data.cart_total.toString()).toFixed(2);
                    amt = addCommas(amt.toString())
                    cart_link = "Go to cart";
                    msg = "You have successfully added "+data.name+" to your cart. Your cart total is now KShs. "+amt+cart_link.link("/cart/");
                    //console.log("received success");
                    //console.log("data is:",data);
                    $.n.success(msg);
                    pl = data.cart_count > 1 ? "S" : "";
                    cart_count = data.cart_count + " ITEM" + pl;
                    //console.log(cart_count);
                    $(".header .cart_count").text(cart_count);
                }
                else
                {
                    $.n(data);
                    //console.log("Error!!!!!");
                }
            },
            'json'
        );
        return false;
    });


    $("#id_wallet_type").change(function(){
        var cur = $(this).find("option:selected").attr("id");
        var wallet = $("div.wallet."+cur);
        if (!wallet.is(":visible")){
            $("div.wallet").stop().slideUp();
            wallet.slideDown();
        }
    });

    $(".pageimages .caption").parent().hover(
        //console.log("hovered on a page image");
        function(){
            $(this).find(".caption").fadeIn();
        },
        function(){
            $(this).find(".caption").fadeOut();}
    );

    $('#category_tree li:last-child').addClass('last');

    //~ $("#category_tree ul ul li").mouseenter(function(){
        //~ $(this).find("ul").slideDown();
    //~ });

    //~ $("#category_tree ul ul li:not(:has(.current))").mouseleave(function(){
        //~ $(this).find("ul").slideUp();
    //~ });

});

