﻿$('#settings').live('pagebeforeshow', function (event, ui) {
    //Move background a bit
    $("div:jqmData(role='content')", this).addClass('transition0');

    $("#settings .spinning").spin();

});

$('#settings').live('pageshow', function (event, data) {
    //Load Merchant list
    ajaxMaster("F003", "");
});

$('#main').live('pageshow', function (event, ui) {
    //Move background a bit
    $("div:jqmData(role='content')", this).removeClass('transition0');

    //Set merchant name
    $("#main h1")[0].innerText = getCurrentMN();

    //
    $("#main .spinning").spin('small');

    //Load categories
    ajaxMaster("F001", "mid:" + getCurrentMID());
});

$('#menulist').live('pageshow', function (event, ui) {
    //Move background a bit
    $("div:jqmData(role='content')", this).addClass('transition');

    //
    $('#SubCategories').empty();

    //Set merchant name
    //$("#menulist > div[role=banner] > div > h1")[0].innerText = getCurrentMN();

    //Set category name
    document.getElementById("MenulistTitle").innerText = getCurrentCN();

    $("#menulist .spinning").spin();

    //Load items
    //if (localStorage["category.id." + getCurrentCID() + ".data"] == undefined) {
    ajaxMaster("F002", "cid:" + getCurrentCID());
    //}
    //else {
    //    process("F002", localStorage["category.id." + getCurrentCID() + ".data"]);
    //}

});

$('#menulist').live('pagehide', function (event, ui) {

    //Move background a bit
    $("div:jqmData(role='content')", this).removeClass('transition');

    //    var photoSwipeInstance = window.Code.PhotoSwipe.getInstance($(event.target)[0].id);

    //    if (typeof photoSwipeInstance != "undefined" && photoSwipeInstance != null) {
    //        window.Code.PhotoSwipe.detatch(photoSwipeInstance);
    //    }
});

$('#favelist').live('pagebeforeshow', function (event, ui) {
    //Set merchant name
    $("#favelist > div:jqmData(role='header') > h1")[0].innerText = getCurrentMN();

    //Load items
    process("F004", localStorage["merchant.id." + getCurrentMID() + ".category.ids"]);

    //Update total amount & number
    updateFaveAmount();

    //Move background a bit
    $("div:jqmData(role='content')", this).addClass('transition2');
});

$('#favelist').live('pagebeforehide', function (event, ui) {

    //Move background a bit
    $("div:jqmData(role='content')", this).removeClass('transition2');
});

$('#main').live('pageinit', function (event) {
    //Set default merchant ID
    if (getCurrentMID() == undefined) {
        $.mobile.changePage($("#settings"), { reverse: true });
        return;
    }

    //Bind events
    $('#MainCategories li').live('click', function () {
        setCurrentCID(this.id);
        setCurrentCN(this.innerText);
    });
});

$('#settings').live('pageinit', function (event) {
    //Bind events
    $('#Merchantlist li').live('click', function () {
        //Set merchant ID 
        setCurrentMID(this.id.slice(2));
        //Set merchant name
        setCurrentMN(this.innerText);
        //Load categories
        ajaxMaster("F001", "mid:" + getCurrentMID());
    });
});

$('#favelist').live('pageinit', function (event) {
    $('#FaveItems li .like').live('click', function () {
        //Remove Item
        //Remove from favourate list
        var itemID = this.parentNode.id;
        var delNote = $("#" + itemID)[0];
        if (delNote !== undefined) {
            delNote.parentNode.removeChild(delNote);
        }

        //Update total amount & number
        updateFaveAmount();

        //Remove Item ID
        removeFromFavelist(itemID.slice(1));
    });
});

$('#menulist').live('pageinit', function (event) {
    function setPosition(status) {
        var sh = document.getElementById("slideHeader"),
            isOpen = getData("current.menulist.sh.pos", "s") == "115";

//        if (isOpen) {
//            $('#btnToggleMenu').attr('data-icon', 'arrow-u').button('refresh');
//        } else {
//            $('#btnToggleMenu').attr('data-icon', 'arrow-d').button('refresh');
//        }

        switch (status) {
            case 'o':
                //Open
                if (!isOpen) {
                    setData("current.menulist.sh.pos", 115, "s");
                }
                break;
            case 'c':
                if (isOpen) {
                    setData("current.menulist.sh.pos", 0, "s");
                }
                break;
            default:
                //Toggle
                if (isOpen) {
                    setData("current.menulist.sh.pos", 0, "s");
                }
                else {
                    setData("current.menulist.sh.pos", 115, "s");
                }
                break;
        }

        sh.style.webkitTransform = 'translate3d(0,' + getData("current.menulist.sh.pos", "s") + 'px,0)';
    }

    //Bind events
    $('#btnToggleMenu').on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        setPosition();
    });

    $('#btnSettings').on("click", function () {
        $.mobile.changePage("#main");
        setPosition("c");
    });

    $("input[type='radio']", this).on("change", function (event, ui) {
        var currentFontsize = event.target.defaultValue;

        //Set new font-size
        $('#SubCategories li h3').css('font-size', currentFontsize + 'px');
        $('#SubCategories span .price-tag-bucks').css('font-size', parseFloat(currentFontsize / 13.3).toFixed(1) + 'em');
        $('#SubCategories span .price-tag-cents').css('font-size', parseFloat(currentFontsize / 20).toFixed(1) + 'em');
        $('#SubCategories .price-tag-from').css('font-size', parseFloat(currentFontsize / 25).toFixed(1) + 'em');

        setCurrentFS(currentFontsize);
    });

    $('#ShowMenu').on('click', function () {
        $('#MenulistLinks').toggleClass('Show');

    });

    $('#ToogleImage').on('click', function () {
        $('#MenulistLinks').toggleClass('Show');
        var items = $('#SubCategories li[id^=st] .ui-btn-text');

        if (items.hasClass('ui-li-has-thumb')) {
            $('img', items).addClass('hidden');
            items.removeClass('ui-li-has-thumb');
            setCurrentImgStatus(0);
        }
        else {
            items.addClass('ui-li-has-thumb');
            setCurrentImgStatus(1);
        }

        $(this).toggleClass('ui-btn-up-a').toggleClass('ui-btn-active');
    });

    $('#SubCategories li .like').live('click', function () {
        var likeribbon = $(this).next();
        likeribbon.toggleClass('bg-yellow');

        //Add or remove item from favelist
        if (likeribbon.hasClass('bg-yellow')) {

            //Add Item ID     
            addToFavelist(likeribbon[0].parentNode.id);
        } else {

            //Remove Item ID
            removeFromFavelist(likeribbon[0].parentNode.id);
        }
    });

    $('#SubCategories li[id^=st]:first .ui-btn-text').live('webkitTransitionEnd', function (evt) {
        evt.stopPropagation();
        if ($(this).hasClass('ui-li-has-thumb')) {
            $('#SubCategories > li[id^=st] > div > div > a > img').removeClass('hidden');
        }
    });
});

$('.gototop').live('click', function () {
    $('html, body').scrollTop(0);
    return false;
});

function getData(name, location, parseType, defaultValue) {
    var result,
        parseResult = function (value, parseType) {
            result = value;
            if (parseType != undefined) {
                switch (parseType) {
                    case 'int':
                        result = parseInt(result);
                        break;
                    case 'float':
                        result = parseFloat(result);
                        break;
                    default:
                        break;
                }
            }

            return result;
        };

    if (location == undefined) {
        //localStorage
        result = parseResult(localStorage.getItem(name), parseType);
    }
    else {
        //sessionStorage
        result = parseResult(sessionStorage.getItem(name), parseType);
    }

    return result;
}

function setData(name, value, location) {
    if (location == undefined) {
        //localStorage
        localStorage.setItem(name, value);
    }
    else {
        //sessionStorage
        sessionStorage.setItem(name, value);
    }
}

function refreshFaveStatus() {
    $('#SubCategories li[id^=st]').each(function () {
        if (IsFavourite(this.id)) {
            if (!$('.likeRibbon', this).hasClass('bg-yellow')) {
                $('.likeRibbon', this).addClass('bg-yellow');
            }
        }
        else {
            $('.likeRibbon', this).removeClass('bg-yellow');
        }
    });
}

function processFontsizeButtons(cfs) {
    if (cfs == 16) {
        //disable downsize button
        $('#FontsizeDown').button('disable');
    }
    else if (cfs == 28) {
        //disable upsize button
        $('#FontsizeUp').button('disable');
    }
    else {
        //enable buttons
        $('#FontsizeDown').button('enable');
        $('#FontsizeUp').button('enable');
    }
}

function IsFavourite(iid) {
    if (getFavelist().split(',').indexOf(iid) == -1) {
        return false;
    }
    else {
        return true;
    }
}

function addToFavelist(iid) {
    if (!IsFavourite(iid)) {
        setFavelist(getFavelist() + iid + ",");
    }
}

function removeFromFavelist(iid) {
    var faveArray = getFavelist().split(',');
    var index = faveArray.indexOf(iid);
    if (index != -1) {
        faveArray.splice(index, 1);
        setFavelist(faveArray.toString());
    }
}

function getFavelist() {
    if (sessionStorage["merchant.id." + getCurrentMID() + ".faves"] == undefined) {
        sessionStorage["merchant.id." + getCurrentMID() + ".faves"] = "";
        return "";
    }
    else {
        return sessionStorage["merchant.id." + getCurrentMID() + ".faves"];
    }
}

function setFavelist(favelist) {
    sessionStorage["merchant.id." + getCurrentMID() + ".faves"] = favelist;
}

function setCurrentMID(mid) {
    localStorage["current.merchant.id"] = mid;
};

function getCurrentMID() {
    return localStorage["current.merchant.id"];
};

function setCurrentCID(cid) {
    localStorage["current.category.id"] = cid;
};

function getCurrentCID() {
    return localStorage["current.category.id"];
};

function setCurrentCN(cn) {
    localStorage["current.category.name"] = cn;
};

function getCurrentCN() {
    return localStorage["current.category.name"];
};

function setCurrentMN(mn) {
    localStorage["current.merchant.name"] = mn;
};

function getCurrentMN() {
    return localStorage["current.merchant.name"];
};

function getFaveTotalNumber() {
    return document.getElementById('FaveItems').childNodes.length;
}

function getFaveTotalAmount() {
    var totalamount = 0;
    $('#FaveItems li').each(function (index) {
        totalamount = totalamount + parseFloat($(this).find('.price-tag').text().slice(1));
    });

    return totalamount;
}

function getCurrentFS() {
    if (sessionStorage["current.fontsize"] == undefined) {
        sessionStorage["current.fontsize"] = 16;
    }

    return sessionStorage["current.fontsize"];
}

function setCurrentFS(fs) {
    sessionStorage["current.fontsize"] = fs;
}

function getCurrentImgStatus() {
    if (sessionStorage["current.imgStatus"] == undefined) {
        sessionStorage["current.imgStatus"] = 0;
    }

    return sessionStorage["current.imgStatus"];
}

function setCurrentImgStatus(is) {
    sessionStorage["current.imgStatus"] = is;
}

function updateFaveAmount() {
    //Update total amount & number
    $('#fsi').find('.sin').text("Total amount: $" + (parseFloat(getFaveTotalAmount()) / 100).toFixed(2) + " (" + getFaveTotalNumber() + " items)");
}

function initPhotoswipe() {
    //Photoswip
    var options = {

        getToolbar: function () {
            return '<div class="ps-toolbar-close"><div class="ps-toolbar-content"></div></div><div class="ps-toolbar-play"><div class="ps-toolbar-content"></div></div><div class="ps-toolbar-previous"><div class="ps-toolbar-content"></div></div><div class="ps-toolbar-next"><div class="ps-toolbar-content"></div></div><div class="ps-toolbar-star"><div class="ps-toolbar-content"></div></div>'
        },
        getImageMetaData: function (el) {
            return {
                stid: el.getAttribute('data-stid')
            }
        },
        getImageCaption: function (el) {

            var price, captionEl, captionTitle, captionDisp, captionPrice;

            // Get the caption from the alt tag
            if (el.nodeName === "IMG") {
                price = el.getAttribute('alt');
            }
            var i, j, childEl;
            for (i = 0, j = el.childNodes.length; i < j; i++) {
                childEl = el.childNodes[i];
                if (el.childNodes[i].nodeName === 'IMG') {
                    price = childEl.getAttribute('alt');
                }
            }

            // Return a DOM element with custom styling
            captionEl = document.createElement('div');
            captionEl.className = 'ps-cs-caption';
            function CreateSpan(text, className) {
                var item = document.createElement('span');
                item.className = className;
                item.appendChild(document.createTextNode(text));
                captionEl.appendChild(item);
            };

            CreateSpan($(el).next().text(), 'ps-cs-caption-title');
            CreateSpan('$' + price, 'ps-cs-caption-price');
            CreateSpan($(el).nextAll('p').text(), 'ps-cs-caption-disp');
            return captionEl;

            // Alternatively you can just pass back a string. However, any HTML 
            // markup will be escaped

        },
        allowUserZoom: false,
        captionAndToolbarFlipPosition: true,
        captionAndToolbarAutoHideDelay: 0,
        enableMouseWheel: false,
        enableKeyboard: false
    };

    return options;
}

function bindPhotoswip(options) {
    var markFaveEl;
    instance = $("#SubCategories a").photoSwipe(options);

    // onShow - store a reference to our "say hi" button
    instance.addEventHandler(window.Code.PhotoSwipe.EventTypes.onShow, function (e) {
        markFaveEl = window.document.querySelectorAll('.ps-toolbar-star')[0];
    });

    // onToolbarTap - listen out for when the toolbar is tapped
    instance.addEventHandler(window.Code.PhotoSwipe.EventTypes.onToolbarTap, function (e) {
        if (e.toolbarAction === window.Code.PhotoSwipe.Toolbar.ToolbarAction.none) {
            if (e.tapTarget === markFaveEl || window.Code.Util.DOM.isChildOf(e.tapTarget, markFaveEl)) {
                //alert('hi!');
                $(markFaveEl).toggleClass('bg-yellow');
                if ($(markFaveEl).hasClass('bg-yellow')) {
                    addToFavelist(instance.getCurrentImage().metaData.stid);
                }
                else {
                    removeFromFavelist(instance.getCurrentImage().metaData.stid);
                }
            }
        }
        else if (e.toolbarAction === window.Code.PhotoSwipe.Toolbar.ToolbarAction.close) {
            refreshFaveStatus();
        }
    });

    // onBeforeHide - clean up
    instance.addEventHandler(window.Code.PhotoSwipe.EventTypes.onBeforeHide, function (e) {
        markFaveEl = null;
    });

    // Set position
    //instance.addEventHandler(window.Code.PhotoSwipe.EventTypes.onHide, function (e) {
    //    $('html body').scrollTop(parseInt(localStorage["current.positon.top"])); 
    //});

    //Show mark or not
    instance.addEventHandler(window.Code.PhotoSwipe.EventTypes.onCaptionAndToolbarShow, function (e) {
        var currentImage = instance.getCurrentImage();

        if (IsFavourite(currentImage.metaData.stid)) {
            $('div.ps-toolbar-star').addClass('bg-yellow');
        }
    });


    //Show mark or not
    instance.addEventHandler(window.Code.PhotoSwipe.EventTypes.onDisplayImage, function (e) {
        var currentImage = instance.getCurrentImage();

        if (IsFavourite(currentImage.metaData.stid)) {
            if (!$(markFaveEl).hasClass('bg-yellow')) {
                $(markFaveEl).addClass('bg-yellow');
            }
        }
        else {
            if ($(markFaveEl).hasClass('bg-yellow')) {
                $(markFaveEl).removeClass('bg-yellow')
            }
        }
    });
}

function process(code, data) {
    switch (code) {
        case "F001":
            localStorage["merchant.id." + getCurrentMID() + ".category.ids"] = data;

            var categories = jQuery.parseJSON(data);
            $('#MainCategories').empty();
            for (var i = 0; i < categories.length; i++) {
                var row = categories[i];
                var newEntryRow = $('#ct').clone(true);
                newEntryRow.data('entryId', row.CategoryID);
                newEntryRow[0].id = row.CategoryID;
                newEntryRow.find('.cn').text(row.CateogryName);
                newEntryRow.appendTo('#MainCategories');
            };

            //hide loading image and show list
            $("#main .spinning").spin(false);

            $('#MainCategories').listview('refresh').removeClass('hidden');
            break;
        case "F002":
            localStorage["category.id." + getCurrentCID() + ".data"] = data
            var items = jQuery.parseJSON(data);

            var j = 0;
            for (var i = 0; i < items.length; i++) {
                var row = items[i];
                if (row.type == 1) {
                    var newEntryRow = $('#st').clone(true);
                    newEntryRow[0].id = "st" + row.id;
                    newEntryRow.find('.stn').text(row.name);
                    newEntryRow.find('a').attr('href', 'images/bg/11' + (j + 1) + '.jpg').attr('data-stid', newEntryRow[0].id);
                    var price = row.price.toString();
                    newEntryRow.find('img').attr('alt', parseFloat(price) / 100).attr('src', 'images/bg/11' + (j + 1) + '.jpg');
                    price = "<span class='price-tag'>$<span class='price-tag-bucks'>" + price.slice(0, price.length - 2) + "</span><span class='price-tag-cents'>" + price.slice(price.length - 2) + "</span></span>"
                    if (row.isfrom) {
                        price = "<span class='price-tag-from'>From</span> " + price;
                    }
                    newEntryRow.find('.like').html(price);
                    newEntryRow.find('.std').text(row.disp);
                    if (IsFavourite("st" + row.id)) {
                        newEntryRow.find('.likeRibbon').addClass('bg-yellow');
                    }
                    newEntryRow.appendTo('#SubCategories');
                    j += 1;
                    if (j == 10) { j = 0 };
                } else if (row.type == 0) {
                    var newEntryRow = $('#si').clone(true);
                    newEntryRow[0].id = "si" + row.id;
                    newEntryRow.find('.sin').html(row.name + " <span class='subcate'>(" + row.rrp + ")</span>");
                    newEntryRow.appendTo('#SubCategories');
                }
            };

            //Style list
            //$('#SubCategories').listview('refresh');

            //Set fontsize
            var currentFontsize = getCurrentFS();
            processFontsizeButtons(parseInt(currentFontsize));

            if (currentFontsize != "16") {
                $('#SubCategories li .stn').css('font-size', currentFontsize + 'px');
                $('#SubCategories span .price-tag-bucks').css('font-size', parseFloat(currentFontsize / 13.3).toFixed(1) + 'em');
                $('#SubCategories span .price-tag-cents').css('font-size', parseFloat(currentFontsize / 20).toFixed(1) + 'em');
                $('#SubCategories .price-tag-from').css('font-size', parseFloat(currentFontsize / 25).toFixed(1) + 'em');
            }

            //show images or not
            if (getCurrentImgStatus() == '1') {
                //Show image
                $('#SubCategories li[id^=st] .ui-btn-text img').removeClass('hidden');
                $('#SubCategories li[id^=st] .ui-btn-text').addClass('ui-li-has-thumb');
                $('#ToogleImage').removeClass('ui-btn-up-a').addClass('ui-btn-active');
            }
            else {
                //Hide images by default
                $('#SubCategories li[id^=st] .ui-btn-text').removeClass('ui-li-has-thumb');
                $('#ToogleImage').removeClass('ui-btn-active').addClass('ui-btn-up-a');
            };

            //hide loading image and show list
            $("#menulist .spinning").spin(false);
            $('#SubCategories').removeClass('hidden');

            bindPhotoswip(initPhotoswipe());

            break;
        case "F003":
            var merchants = jQuery.parseJSON(data);
            $('#Merchantlist').empty();
            for (var i = 0; i < merchants.length; i++) {
                var row = merchants[i];
                var newEntryRow = $('#mt').clone(true);
                newEntryRow[0].id = "mt" + row.MerchantID;
                newEntryRow.find('.mn').text(row.MerchantName);
                newEntryRow.appendTo('#Merchantlist');
            };

            //hide loading image and show list
            $("#settings .spinning").spin(false);
            $('#Merchantlist').listview('refresh').removeClass('hidden');
            break;
        case "F004":
            //Get categories ids
            var items = jQuery.parseJSON(data);
            var currentFontsize = getCurrentFS();
            $('#FaveItems').empty();
            for (var i = 0; i < items.length; i++) {
                var category = localStorage["category.id." + items[i].CategoryID + ".data"];
                if (category != undefined) {
                    var getItems = jQuery.parseJSON(category);
                    var j = 0;
                    for (j = 0; j < getItems.length; j++) {
                        var row = getItems[j];
                        if (row.type == 1 && IsFavourite("st" + row.id)) {
                            var newEntryRow = $('#st').clone(true);
                            newEntryRow[0].id = "fst" + row.id;
                            if (currentFontsize != "16") {
                                newEntryRow.find('.stn').text(row.name).css('font-size', currentFontsize + 'px');
                            }
                            else {
                                newEntryRow.find('.stn').text(row.name);
                            }
                            var price = row.price.toString();
                            price = "<span class='price-tag'>$<span class='price-tag-bucks'>" + price.slice(0, price.length - 2) + "</span><span class='price-tag-cents'>" + price.slice(price.length - 2) + "</span></span>"
                            if (row.isfrom) {
                                price = "<span class='price-tag-from'>From</span> " + price;
                            }
                            newEntryRow.find('.like').html(price);
                            newEntryRow.find('.std').text(row.disp);
                            newEntryRow.find('.likeRibbon').addClass('bg-yellow');
                            newEntryRow.appendTo('#FaveItems');
                        };
                    };
                };
            };
            break;
        default:
            break;
    };
};

function ajaxMaster(code, reqData) {
    var ufn = "";
    switch (code) {
        case "F001":
            ufn = "getcategory";
            break;
        case "F002":
            ufn = "getitems";
            break;
        case "F003":
            ufn = "getmerchant";
            break;
        default:
            break;
    };

    if (ufn != "") {
        $.ajax({
            type: "POST",
            url: "../control/customer.asmx/" + ufn,
            data: '{' + reqData + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                process(code, msg.d);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + " Code: " + code);
            }
        });
    };
};

