/**
 * Mohni.ee Webshop
 * @author Mihkel Sokk
 * @description Webshop clientside logic
 */
var mShop = new function() {

    /**
     * Returns escaped hash
     */
    this.hash = function() {
        return decodeURIComponent(window.location.hash.substr(1));
    }

    /**
     * Site initialisation - dialogs, session restoration, etc.
     */
    this.init = function() {
        if(window.location.hostname.indexOf("www") != -1) {
            window.location.href = "http://mohni.ee";
        }
        this.preLoad(["submitBig.gif","submitBigActive.gif", "home.gif",
            "homeActive.gif", "closeBtn.png", "closeBtnActive.png",
            "submitSmall.png", "submitSmallActive.png", "catListArrow.gif",
            "catListArrowActive.gif"], "images");

        var dialogs = this.dialogs = function() {
            $("#dialogCheck").dialog({
                modal: true,
                autoOpen: false,
                title: "Vormista tellimus",
                width: 260,
                height: 175,
                draggable: false,
                resizable: false,
                overlay: {opacity: 0.9, background: "black"}
            });

            $("#dialogRequest").dialog({
                modal: true,
                autoOpen: false,
                title: "Küsi pakkumist",
                width: 260,
                height: 250,
                draggable: false,
                resizable: false,
                overlay: {opacity: 0.9, background: "black"}
            });

            $("#dialogComp").dialog({
                modal: true,
                autoOpen: false,
                title: "Firmast",
                width: 400,
                height: 330,
                draggable: false,
                resizable: false,
                overlay: {opacity: 1, background: "black"}
            });
            $("#dialogProd").dialog({
                modal: true,
                autoOpen: false,
                title: "Tooted",
                width: 649,
                height: 350,
                draggable: false,
                resizable: false,
                overlay: {opacity: 0.9, background: "black"}
            });
        };
        dialogs();
        this._initCart();
        $("#loadBar").ajaxStart(function(){$(this).show();});
        $("#loadBar").ajaxStop(function(){$(this).hide();});
        $(window).bind('hashchange', function(){mShop._goTo();});
        if(window.location.hash != "" && window.location.hash != "#") {
            this._goTo();
        }
    }

    this.preLoad = function(arr, path) {
        for(var i in arr) {
            tmp = new Image();
            tmp.src = path + "/" + arr[i];
        }
    }

    /////SHOPPING CART//////
    /**
     * Loads shopping cart json
     */
    this._cartData = function(json) {
        if(typeof(json) != 'undefined') {
            $.jStorage.set("cart", json);
            return true;
        } else {
            if($.jStorage.get("cart") != null) {
                return $.jStorage.get("cart");
            } else {
                return new Array();
            }
        }
    }


    /**
     * Render shopping cart
     */
    this._initCart = function() {
        cart = this._cartData();
        if(typeof(cart) != 'undefined') {
            for(var i in cart) {
                rowClass = ($(".basketWrapper div[id]:last-child").attr('class') == "row")? "odd row": "row";
                $(".basketWrapper").append('<div id="'+cart[i].id+'" class="'+rowClass+'"><div class="col w50">'
                    +'<a href="#" onclick="mShop.navigate(\''+this.hash()+'/'+cart[i].code+'\'); return false'
                    +'" >'+unescape(cart[i].code)+'</a></div><div class="col w70">'+unescape(cart[i].description)
                    +'</div><div class="col w35">'+cart[i].price+'</div><div class="col w20">'
                    +'<input class="cartQty" onblur="mShop.uCart(\''+cart[i].id+'\',this)" value="'+cart[i].qty+'" id="'
                    +cart[i].id+'" type="textbox" size="1" /></div><div class="col w15"><a class="closeBtn"'
                    +' href="javascript:void(0);" onclick="mShop.rCart(\''+cart[i].id+'\')"'
                    +' >&nbsp; &nbsp;</a></div><div class="floatsplit"></div></div>');
            }
        } else {this._cartData({});}
    }

    /**
     * Add item to cart
     */
    this.aCart = function(json) {
        json = $.evalJSON(unescape(json));
        json.qty = 1;
        cart = this._cartData();
        for(var i in cart){if(cart[i].id == json.id) {
                this.uCart(json.id);return;}}
        rowClass = ($(".basketWrapper div[id]:last-child").attr('class') == "row")? "odd row": "row";
        $(".basketWrapper").append('<div id="'+json.id+'" class="'+rowClass+'"><div class="col w50"><a '
            +'href="#" onclick="mShop.navigate(\''+this.hash()+'/'+json.code+'\'); return false'
            +'" >'+unescape(json.code)+'</a></div><div class="col w70">'+unescape(json.description)
            +'</div><div class="col w35">'+json.price+'</div><div class="col w20">'
            +'<input class="cartQty" onblur="mShop.uCart(\''+json.id+'\',true)" value="1" id="'
            +json.id+'" type="textbox" size="1" /></div><div class="col w15"><a class="closeBtn"'
            +' href="javascript:void(0);" onclick="mShop.rCart(\''+json.id+'\')"'
            +' >&nbsp; &nbsp;</a></div><div class="floatsplit"></div></div>');
        cart[json.id] = json;
        this._cartData(cart);
        $(".scrollWrapper").attr('scrollTop',
            $(".scrollWrapper").attr('scrollHeight'));
    }

    /**
     * Update cart item
     */
    this.uCart = function(id, blur) {
        blur = (typeof(blur) == 'undefined')? false : blur;
        newValue = parseInt($(".basketWrapper input[id='"+id+"']").val());
        if(!blur) {
            newValue++;
            $(".basketWrapper input[id='"+id+"']").val(newValue);
        }
        cart = this._cartData();
        cart[id].qty = newValue;
        this._cartData(cart);
    }

    /**
     * Delete item from cart
     */
    this.rCart = function(id) {
        cart = this._cartData();
        delete cart[id];
        this._cartData(cart);
        $(".basketWrapper div[id='"+id+"']").remove();
    }

    /**
     * Empty the cart
     */
    this.clearCart = function() {
        this._cartData({});
        $(".basketWrapper").empty();
    }

    /**
     * Post the order
     */
    this.doCheckOut = function() {
        cartData = $.toJSON(this._cartData());
        $.post("/", {cart: cartData, name: $("input[name=name]").val(),
            email: $("input[name=email]").val(), tel: $("input[name=tel]").val()
        },function(data){
            if(data == "0") {
                $("#checkBody table").hide();
                $("#checkBody").append("<h2 id=\"confirm\">Tellimus saadetud!</h2>");
                mShop.clearCart();
            } else {
                $("#checkBody table").hide();
                $("#checkBody").append(data);
            }
        });
    }

    /**
     * Post the request
     */
    this.doRequest = function() {
        $.post("/", {item: JSON.stringify(window.reqItem), name: $("input[name=name].reqForm").val(),
            email: $("input[name=email].reqForm").val(), tel: $("input[name=tel].reqForm").val()
        }, function(data){
            if(data == "0") {
                $("#reqBody table").hide();
                $("#reqBody").append("<h2 id=\"confirm\">Hinnapäring saadetud!</h2>");
            } else {
                $("#reqBody table").hide();
                $("#reqBody").append(data);
            }
        });
    }
    /////////////////////////////////

    //////DIALOGS//////
    this.openCheckout = function() {
        this.dialogs();
        $("#dialogCheck").dialog('open');
        $("#checkBody #confirm").hide();
        $("#checkBody table").show();
        //Simple form validator
        $('.checkoutForm').change(function() {
            if($("input[name=name].checkoutForm").val() != "" && $("input[name=email].checkoutForm").val()
              && $("input[name=tel].checkoutForm").val() != "" && mShop._cartData() != "") {
                $("#sendForm").removeAttr("disabled");
            } else { $("#sendForm").attr("disabled", "disabled"); }
        });
        $("input[name=tel]").keypress(function(e) {
          if(e.which!=43 &&e.which!=8 && e.which!=0
          && (e.which<48 || e.which>57)) return false; });
    }

    this.openRequest = function(item) {
        this.dialogs();
        $("#dialogRequest").dialog('open');
        $("#reqBody #confirm").hide();
        $("#reqBody table").show();

        window.reqItem = item = JSON.parse(unescape(item));
        $('#reqItem').html(item.code + '<br><p>' + unescape(item.description) + '</p>');

        //Simple form validator
        $('.reqForm').change(function() {
            if($("input[name=name].reqForm").val() != "" && $("input[name=email].reqForm").val()
              && $("input[name=tel].reqForm").val() != "") {
                $("#sendForm2").removeAttr("disabled");
            } else { $("#sendForm2").attr("disabled", "disabled"); }
        });
        $("input[name=tel]").keypress(function(e) {
          if(e.which!=43 &&e.which!=8 && e.which!=0
          && (e.which<48 || e.which>57)) return false; });
    }

    this.openCompany = function() {this.dialogs();$("#dialogComp").dialog('open');}
    this.openProducts = function() {this.dialogs();$("#dialogProd").dialog('open');}

    //////NAVIGATION//////
    /**
     * Render navigation
     */
    this._updateCrumbs = function() {
        crumbs = this.hash().split('/');
        $(".breadcrumb").html('<li class="home"><a href="/" onclick="mShop.navigate();'+
            ' return false" title="Algusesse">&nbsp; &nbsp; &nbsp;</a></li>');
        bCrumb = "";
        for(var i in crumbs) {
            bCrumb += ((i==0)?'' + crumbs[i]:'/' + crumbs[i]);
            $(".breadcrumb").append('<li><a href="'+bCrumb+
                '" onclick="mShop.navigate(\''+bCrumb+
                '\'); return false">'+crumbs[i]+'</a></li>');
        }
    }

    /**
     * UI navigation - change hash
     */
    this.navigate = function(url) {
        (!url)? window.location.hash = "": window.location.hash = url;
    }

    /**
     * Go to a page - Fetch JSON data
     */
    this._goTo = function(url) {
        if(!url) url = this.hash();
        $.getJSON("?format=json&q="+encodeURIComponent(url), function(json) {
            if(json.homecategories) {
                mShop._rHome(json.homecategories);
            } else if(json.subcategories || json.items) {
                if(json.items) mShop._rItems(json.items);
                if(json.subcategories) mShop._rSubcat(json.subcategories);
            } else if(json.item) {
                mShop._rItem(json.item);
            }
        });
        this._updateCrumbs();
    }

    /**
     * Render - Return to home
     */
    this._rHome = function(json) {
        $("#leftPane").empty();
        for(i = 0; i < json.length; i++) {
            $("#leftPane").append('<div class="prodCat"><a href="'
                +json[i].title+'" onclick="mShop.navigate'+
                '(\''+json[i].title+'\'); return false">'+
                '<img src="./images/cat/'+json[i].hwurl+'.jpg" alt="'+json[i].title+'" />'
                +json[i].title+'</a></div>');
            if((i+1)%4==0){$("#leftPane").append('<div class="floatsplit"></div>');}
        }
    }

    /**
     * Render - Subcategories
     */
    this._rSubcat = function(json) {
        $("#leftPane").prepend('<ul class="catList">');
        for(i=0; i<json.length; i++) {
            if(i%7 == 0 && i != 0) $(".catList").append("<br />");
            $(".catList").append('<li><a href="'+this.hash()+'/'+json[i].title+'" '+
                'onclick="mShop.navigate(\''+this.hash()+'/'+json[i].title+'\'); return false">'+
                json[i].title+'</a></li>');
        }
    }

    /**
     * Render - Item listing
     */
    this._rItems = function(json) {
        $("#leftPane").html('<div class="prodList"><div class="bt greyBg row'+
            ' underlined"><div class="col w100">Artikli kood</div><div class="col'+
            ' w320">Toote kirjeldus</div><div class="col w70">Hind</div><div '+
            'class="col w30">Lisa</div><div class="floatsplit"></div></div></div>');
        for(i=0; i<json.length; i++) {
            var askOffer = (json[i].price == 0 || json[i].price == '&nbsp;');
            offerOrAddToCart = '<div class="col w70">'+json[i].price+
                ' EUR</div><div class="col w30"><a href="#" onclick="mShop.aCart(\''
                +escape($.toJSON(json[i]))+'\'); return false" class="addToBasketBtn">'+
                '&nbsp; &nbsp;</a></div>';

            if(askOffer) {
              offerOrAddToCart = '<div class="col w100"><a class="askOfferBtn" href="#" onclick="mShop.openRequest(\''
                +escape($.toJSON(json[i]))+'\'); return false">Küsi pakkumist</a></div>';
            }

            $(".prodList").append('<div class="row underlined"><div class="col '
                +'w100"><a href="'+this.hash()+'/'+unescape(json[i].code)+'" onclick="mShop.navigate'
                +'(\''+this.hash()+'/'+unescape(json[i].code)+'\'); return false">'
                +json[i].code+'</a></div><div class="col w320">'+unescape(json[i].description)+
                '</div>'+offerOrAddToCart+'<div class="floatsplit"></div></div>');
        }
    }

    /**
     * Render - Single item
     */
    this._rItem = function(json) {
        $("#leftPane").html('<div id="prodInfo"><img src="images/items/'+json.img+
            '" alt="'+json.code+'" class="prodImg" /><div class="prodDesc">'+
            '<div class="row underlined"><span class="lbl">Kood:</span> '+json.code+
            '</div><div class="row underlined"><span class="lbl blocked">Kirjeldus:</span> '+
            unescape(json.description)+'</div><div class="priceTag"><span class="lbl">Hind:</span> '
            +json.price+' EUR </div><div class="row underlined"><a class="addBasketItem'+
            ' addToBasketBtn" href="#" onclick="mShop.aCart(\''+escape($.toJSON(json))+'\'); return false">'+
            '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Lisa ostukorvi</b>'+
            '</a></div></div></div><div id="htmlExtra">'+unescape((!json.html)?"":json.html)+
            '</div><div class="floatsplit"></div>');
    }
    ///////////////////////////////////
};

//////THIRD PARTY LIBRARIES////// - this must not change!
/** jQuery hashchange event - v1.2 - 2/11/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);

/** jQuery JSON - MIT License - Brantley Harris */
(function(e){e.toJSON=function(a){if(typeof JSON=="object"&&JSON.stringify)return JSON.stringify(a);var b=typeof a;if(a===null)return"null";if(b!="undefined"){if(b=="number"||b=="boolean")return a+"";if(b=="string")return e.quoteString(a);if(b=="object"){if(typeof a.toJSON=="function")return e.toJSON(a.toJSON());if(a.constructor===Date){var c=a.getUTCMonth()+1;if(c<10)c="0"+c;var d=a.getUTCDate();if(d<10)d="0"+d;b=a.getUTCFullYear();var f=a.getUTCHours();if(f<10)f="0"+f;var g=a.getUTCMinutes();if(g< 10)g="0"+g;var h=a.getUTCSeconds();if(h<10)h="0"+h;a=a.getUTCMilliseconds();if(a<100)a="0"+a;if(a<10)a="0"+a;return'"'+b+"-"+c+"-"+d+"T"+f+":"+g+":"+h+"."+a+'Z"'}if(a.constructor===Array){c=[];for(d=0;d<a.length;d++)c.push(e.toJSON(a[d])||"null");return"["+c.join(",")+"]"}c=[];for(d in a){b=typeof d;if(b=="number")b='"'+d+'"';else if(b=="string")b=e.quoteString(d);else continue;if(typeof a[d]!="function"){f=e.toJSON(a[d]);c.push(b+":"+f)}}return"{"+c.join(", ")+"}"}}};e.evalJSON=function(a){if(typeof JSON== "object"&&JSON.parse)return JSON.parse(a);return eval("("+a+")")};e.secureEvalJSON=function(a){if(typeof JSON=="object"&&JSON.parse)return JSON.parse(a);var b=a;b=b.replace(/\\["\\\/bfnrtu]/g,"@");b=b.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]");b=b.replace(/(?:^|:|,)(?:\s*\[)+/g,"");if(/^[\],:{}\s]*$/.test(b))return eval("("+a+")");else throw new SyntaxError("Error parsing JSON, source is not valid.");};e.quoteString=function(a){if(a.match(i))return'"'+a.replace(i, function(b){var c=j[b];if(typeof c==="string")return c;c=b.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"';return'"'+a+'"'};var i=/["\\\x00-\x1f\x7f-\x9f]/g,j={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"}})(jQuery);

/** JSTORAGE
 * Copyright (c) 2010 Andris Reinman, andris.reinman@gmail.com
 * Project homepage: www.jstorage.info
 * Licensed under MIT-style license
 */
(function(e){if(!e||!(e.toJSON||Object.toJSON||window.JSON)){throw new Error("jQuery, MooTools or Prototype needs to be loaded before jStorage!")}var f={},b={jStorage:"{}"},g=null,i=e.toJSON||Object.toJSON||(window.JSON&&(JSON.encode||JSON.stringify)),d=e.evalJSON||(window.JSON&&(JSON.decode||JSON.parse))||function(j){return String(j).evalJSON()};function h(){if(window.localStorage){try{b=window.localStorage}catch(k){}}else{if(window.globalStorage){try{b=window.globalStorage[window.location.hostname]}catch(j){}}else{g=document.createElement("link");if(g.addBehavior){g.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(g);g.load("jStorage");var l="{}";try{l=g.getAttribute("jStorage")}catch(n){}b.jStorage=l}else{g=null;return}}}if(b.jStorage){try{f=d(b.jStorage)}catch(m){b.jStorage="{}"}}else{b.jStorage="{}"}}function c(){try{b.jStorage=i(f);if(g){g.setAttribute("jStorage",b.jStorage);g.save("jStorage")}}catch(j){}}function a(j){if(!j||(typeof j!="string"&&typeof j!="number")){throw new TypeError("Key name must be string or numeric")}return true}e.jStorage={version:"0.1.3",set:function(j,k){a(j);f[j]=k;c();return k},get:function(j,k){a(j);if(j in f){return f[j]}return typeof(k)=="undefined"?null:k},deleteKey:function(j){a(j);if(j in f){delete f[j];c();return true}return false},flush:function(){f={};c();if(window.localStorage){try{localStorage.clear()}catch(j){}}return true},storageObj:function(){function j(){}j.prototype=f;return new j()}};h()})(window.jQuery||window.$);

