﻿$(document).ready(function () {


    //$("#shop-holder .item .desc .pds .btns a,.shpBsk .delete,.updatePrice").shp_Buy();

    if ($("#XPT-ticker").length > 0) {
        $("#XPT-ticker").ClackerTicker("XPTUSD",5);
        $("#XPD-ticker").ClackerTicker("XPDUSD",5);        
    }

    if ($(".sptPrice").length > 0) {
        $(".sptPrice").feedCollect(5000);
    }

    if ($("#shop-holder").length > 0) {
        $("#shop-holder").feedShop();

        $(".manyImages").slider();
    }

    if ($(".LogIn").length > 0) {

        $("#lgDets").css("margin-left", "-200px").css("top", "150px");

        var divMB = $("<div id=\"ModalBackground\"/>");

        var _docHeight = document.height || document.body.offsetHeight;
        var _windowHeight = document.documentElement.clientHeight
        var theHeight = 0;
        if (_docHeight > _windowHeight) {
            theHeight = _docHeight;
        }
        else {
            theHeight = _windowHeight;
        }

        divMB.css({ "height": theHeight + 15, "opacity": "0.4" }).hide();

        $("body").append(divMB);

        $(".LogIn").click(function (e) {
            e.preventDefault();
            divMB.show();
            $("#lgDets").show();
        });

        $(".cancel").click(function (e) {
            e.preventDefault();
            divMB.hide();
            $("#lgDets input").val("");
            $("#lgDets").hide();
        });

    }


    var styleButtons = function (container) {
        container.find('a').wrapInner('<span><span></span></span>').addClass('btn');
    };


    $.each($(".chartItem"), function () {
        var chrt = $(this);
        //var idc = chrt.attr("id");
        var cid = chrt.text();
        chrt.text("");

        $(chrt).goldChart({
            url: 'xml/chartFeed.ashx?chrt=' + cid,
            onPostRender: styleButtons,
            settings: {
                chart: {
                    margin: [20, 10, 80, 35],
                    width: 295
                },
                title: { style: { 'font-size': '12px'} },
                labels: { style: { 'font-size': '10px'} },
                xAxis: { labels: { style: { 'font-size': '10px'}} },
                yAxis: { labels: { style: { 'font-size': '10px'}} },
                legend: {
                    enabled: true,
                    borderWidth: 0,
                    lineHeight: 12,
                    symbolPadding: 2,
                    symbolWidth: 10,
                    style: {
                        'font-size': '8px'
                    }
                } // legend end 
            }// settings end
        }); // gold chart end

        chrt.slideDown();
    }); // foreach loop end

    $.each($(".chartItemLarge"), function () {
        var chrt = $(this);
        var idc = chrt.attr("id");
        var cid = chrt.text();
        chrt.text("");
        chrt.slideDown();
        $('#' + idc).goldChart(
		    {
		        url: 'xml/chartFeed.ashx?chrt=' + cid,
		        onPostRender: styleButtons,
		        settings: // this can be any of the settings: http://www.highcharts.com/ref/
			    {
			    chart: { margin: [20, 10, 80, 35] },
			    legend: { enabled: true,
			        borderWidth: 0,
			        lineHeight: 12,
			        symbolPadding: 2,
			        symbolWidth: 10,

			        style: {
			            'font-size': '8px'
			        }
			    },

			    title: { style: { 'font-size': '12px'} },
			    labels: { style: { 'font-size': '10px'} },
			    xAxis: { labels: { style: { 'font-size': '10px'}} },
			    yAxis: { labels: { style: { 'font-size': '10px'}} }
			}


		    }
        );

    });

    $(".chartToggle a").click(function (e) {
        e.preventDefault();
        var btn = $(this);
        var chrt = btn.parent().prev(".chrt");
        if (chrt.is(":visible")) {
            chrt.slideUp(200, function () { btn.text("show") });
        }
        else {
            chrt.slideDown(200, function () { btn.text("hide") });
        }
    })

























    var menuTimer = null;

    $("#Header #mainMenu ul li ul").hide();

    $("#Header #mainMenu ul li a:not(#Header #mainMenu ul li ul li a)").hover(function () {
        clearTimeout(menuTimer);
        $("#Header #mainMenu ul li ul").hide();
        $(this).parent().find("ul").show();
    }, function () {
        clearTimeout(menuTimer);
        menuTimer = setTimeout(function () {
            $("#Header #mainMenu ul li ul").hide();
            $("#Header #mainMenu ul li.Selected ul").show();
        }, 200);
    });

    $("#Header #mainMenu ul li ul").hover(function () {
        clearTimeout(menuTimer);
    }, function () {
        clearTimeout(menuTimer);
        menuTimer = setTimeout(function () {
            $("#Header #mainMenu ul li ul").hide();
            $("#Header #mainMenu ul li.Selected ul").show();
        }, 200);
    });

    $("#Header #mainMenu ul li ul li a").hover(function () {
        clearTimeout(menuTimer);
    }, function () {
        clearTimeout(menuTimer);
        menuTimer = setTimeout(function () {
            $("#Header #mainMenu ul li ul").hide();
            $("#Header #mainMenu ul li.Selected ul").show();
        }, 200);
    });





    var path = location.href;
    var FileName = path.split("/");

    var parent = "";
    var child = "";


    for (var i = 3; i < FileName.length; i++) {
        if (FileName[i].toLowerCase() != "sp.v3") {
            parent += FileName[i].toLowerCase();
            if (i < FileName.length - 1) {
                parent += "/";
            }
        }
    }

    if (parent != "default.aspx") {
        var thisEl = $("#mainMenu ul li a[href~='" + parent + "']").parent();

        if (thisEl.find("ul").length == 0) {
            thisEl.parent().parent().addClass("Selected");
            thisEl.addClass("Selected");
            thisEl.parent().parent().find("ul").show();
        }
        else {
            thisEl.addClass("Selected");
            thisEl.find("ul").show();
        }


    }



















    var divHwrapper = $("<div class=\"titleHWrapper\"></div>");

    $(".titleH").wrap(divHwrapper);

    // NEWS ITEMS
    $(".NewsItem").click(function () {
        var ID = $(this).attr("id").substring(4);
        $.post("__dta/NewsCounter.ashx", { id: ID }, function (xml) {

            if ($("Result", xml).text() == "true") {

            }
        });
    });

    // News Stats
    $(".StatsNews:first").css("display", "block");
    $(".NewsStat:first").addClass("nsSelected");

    $(".NewsStat").click(function (e) {
        e.preventDefault();
        var id = $(this).attr("id").substring(3);
        $(".NewsStat").removeClass("nsSelected");
        $(this).addClass("nsSelected");

        $(".StatsNews[id!='STR" + id + "']").css("display", "none");
        $(".StatsNews[id='STR" + id + "']").css("display", "block");

    });




















    if ($(".tblData").length > 0) {
        $(".tblData").each(function () {
            var el = $(this);
            var pn = el.attr("pn");
            var did = el.attr("did");
            var ps = el.attr("ps");
            var pm = el.attr("pm");
            $.post("__dta/_fixratedata.ashx", { pn: pn, did: did, ps: ps, pm: pm }, function (txt) {
                var tbl = $(txt);
                el.append(tbl);
                tbl.show();
            });
        })

        $(".tblData .page").live("click", function (e) {
            e.preventDefault();
            var el = $(this);
            var pn = el.attr("id").substring(3);
            var div = el.parent().parent().parent().parent().parent();
            var did = div.attr("did");

            var tbl = $("#tbl_" + did + "_" + pn);

            if (tbl.length == 0) {

                var ps = div.attr("ps");
                var pm = div.attr("pm");
                $.post("__dta/_fixratedata.ashx", { pn: pn, did: did, ps: ps, pm: pm }, function (txt) {
                    $(".tblData table").hide();
                    var tbl = $(txt);
                    div.append(tbl);
                    tbl.show();
                });
            }
            else {
                $(".tblData table").hide();
                tbl.show();
            }
        });
    }

    if ($(".newsTable").length > 0) {

        $(".newsPaging .page").live("click", function (e) {
            e.preventDefault();
            var el = $(this),
                pn = el.attr("id").substring(3),
                div = el.parent().parent(),
                zn = div.attr("zn"),
                st = $(".search-box input[type=text]", div.parent()).val();

            var tbl = $("#ntbl_" + zn + "_" + pn);

            if (tbl.length == 0) {

                var ps = div.attr("ps");
                $.post("__dta/_nt.ashx", { pn: pn, zn: zn, ps: ps, st: st }, function (txt) {
                    var tbl = $(txt);
                    $(".newsTable").hide();
                    div.parent().append(tbl);
                    tbl.show();
                });
            }
            else {
                $(".newsTable").hide();
                tbl.show();
            }
        });

        $(".search-box a").click(function (e) {
            e.preventDefault();
            var el = $(this).parent(),
                pn = 1,
                zn = el.attr("zn"),
                st = $("input[type=text]", el).val();

            var ps = el.attr("ps");
            $.post("__dta/_nt.ashx", { pn: pn, zn: zn, ps: ps, st: st }, function (txt) {
                $(".newsTable").remove();
                var tbl = $(txt);
                $(".newsTable").hide();
                tbl.insertAfter(el);
                tbl.show();
            });

        });

        $("div.search-box input[type=text]").keypress(function (e) {

            if (e.keyCode == 13) {
                // enter     
                e.preventDefault();

                var el = $(this).parent(),
                pn = 1,
                zn = el.attr("zn"),
                st = $("input[type=text]", el).val();

                var ps = el.attr("ps");
                $.post("__dta/_nt.ashx", { pn: pn, zn: zn, ps: ps, st: st }, function (txt) {
                    $(".newsTable").remove();
                    var tbl = $(txt);
                    $(".newsTable").hide();
                    tbl.insertAfter(el);
                    tbl.show();
                });

            }


        });



    }


    $("div.search-box-small input[type=text]").keypress(function (e) {

        if (e.keyCode == 13) {
            // enter     
            e.preventDefault();

            var el = $(this).parent().parent(),
                    st = $(this).val(),
                    url = $("a:first", el).attr("href"),
                    base = $("head base").attr("href");

            if (st != "") {
                window.location = base + url + "?st=" + st;
            }
        }

    });

    $("div.search-box-small a").click(function (e) {

            e.preventDefault();

            var el = $(this).parent().parent(),
                    st = $(this).parent().find("input").val(),
                    url = $("a:first", el).attr("href"),
                    base = $("head base").attr("href");

            if (st != "") {
                window.location = base + url + "?st=" + st;
            }
    

    });

});

$.fn.shp_Buy = function () {

    var timer = null;

    var timeFull = $("#shopBsk-Remaining").text();

    var totalSecs = parseInt(timeFull.substring(timeFull.indexOf(":") + 1)) + (parseInt(timeFull.substring(0, timeFull.indexOf(":"))) * 60);
    countdown();

    function countdown() {

        $(".trP:last td").css("border-bottom", "none");

        totalSecs--;

        if (totalSecs > 0) {
            var secs = totalSecs % 60;
            var mins = parseInt(totalSecs / 60);
            if (secs < 10) {
                $("#shopBsk-Remaining").text(mins + ":0" + secs);
            }
            else {
                $("#shopBsk-Remaining").text(mins + ":" + secs);
            }
            $(".checkout").show();
            timer = setTimeout(function () { countdown() }, 1000);
        }
        else {
            $(".bskPrice").html("<span>expired</span>");
            $("#tdTotal").html("<span>expired</span>");
            $("#shopBsk-Remaining").text("time up");
            $(".checkout").hide();
        }
    };

    return this.each(function () {

        $(this).click(function (e) {

            e.preventDefault();
            var el = $(this),
                id = el.attr("id"),
                qnt = el.parent().parent().find(".qnt select:first"),
                q = 1;

            if (qnt.val() != undefined) {
                q = qnt.val();
            }

            updateBasket(id, q);

        });

        function updateBasket(id, q) {

            $.post("__dta/bsk.ashx", { id: id, q: q }, function (txt) {
                if (txt == "true") {
                    // delete
                    $("#tr" + id.substring(3)).remove();
                    if ($(".trP").length == 0) {
                        $("#shopBsk-Remaining").parent().hide();
                        $(".trEmp").show();
                        $(".trBtns").hide();
                        $(".trTotal").hide();
                        clearTimeout(timer);
                    }
                    else {
                        var t = 0;
                        $.each($(".shpBsk .bskPrice"), function () {
                            if ($(this).text() != "expired") {
                                t += parseFloat($(this).text());
                            }
                        });
                        if (t > 0) {
                            $("#tdTotal").text(roundNumber(t, 2));
                        }
                    }
                }
                else if (txt.indexOf("false") > -1) {
                    alert("There has been a problem, please try again later.");
                }

                else {
                    // potentially lots of rows are returned
                    var trs = $(txt);
                    clearTimeout(timer);
                    $.each($("tr", trs), function () {
                        // add row
                        var tr = $(this);
                        $("a", tr).bind("click", function (e) {
                            e.preventDefault();
                            var innerel = $(this),
                            innerid = innerel.attr("id"),
                            innerqnt = innerel.parent().parent().find(".qnt select:first"),
                            innerq = 1;

                            if (innerqnt.val() != undefined) {
                                innerq = innerqnt.val();
                            }

                            updateBasket(innerid, innerq);
                        });
                        $(".trEmp").hide();
                        $(".trBtns").show();
                        if ($("#" + tr.attr("id")).length > 0) {
                            $("#" + tr.attr("id")).replaceWith(tr);
                            tr.show();
                        }
                        else {
                            tr.insertBefore(".trEmp").show();
                        }
                    });

                    if ($(".trP").length > 0) {

                        $(".trP:last td").css("border-bottom", "none");

                        var t = 0;
                        $.each($(".shpBsk .bskPrice"), function () {
                            if ($(this).text() != "expired") {
                                t += parseFloat($(this).text());
                            }
                        });

                        if (t > 0) {
                            $("#tdTotal").text(roundNumber(t, 2));
                        }
                        $("#shopBsk-Remaining").parent().show();
                        $(".trTotal").show();
                        totalSecs = 120;
                        countdown();


                    }
                }
            });
        }

        function roundNumber(num, dec) {
            var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
            return result.toFixed(2);
        }


    });



}
