var mySpecialsWebServiceUrl = "http://" + location.host + "/usercontrols/MySpecialsUserControls/WebServices/MySpecialsWebService.asmx";



$(document).ready(function() {
    //Collapse the note pad
    var currentUrl = window.location.pathname;
    //    if (currentUrl.indexOf("catalogue") >= 0 || currentUrl.indexOf("utilities") >= 0 || currentUrl.indexOf("terms") >= 0) {
    //        $("#notepadtoggle").css("background-image", "url(/images/myspecials/ui/icon_arrowdown.gif)");
    //        $("#notepadextend").hide();
    //    }
    // Site Tracking
    $('<img src="https://ct.eid.co.nz/JQYNAOGCHWQ,11I1903/sm.gif?eid=' + Math.ceil(10000 * Math.random()) + '" alt="" width="1" height="1" border="0" />').appendTo('body');


    var url = window.location.pathname;
    var cd = url.toLowerCase().indexOf("countdown");
    var changeStoreCount = GetStoreChangeCount(cd >= 0);

    if (url.toLowerCase().indexOf("foodtown") >= 0)
        $("#clickherespecials").attr("href", "/foodtown/specials.aspx");
    else if (url.toLowerCase().indexOf("woolworths") >= 0)
        $("#clickherespecials").attr("href", "/woolworths/specials.aspx");
    else if (url.toLowerCase().indexOf("countdown") >= 0)
        $("#clickherespecials").attr("href", "/countdown/specials.aspx");

    if (queryStr("changestore")) {
        $("#changenote" + changeStoreCount).show();
    }

    if (queryStr("load") == "1") {
        $(".load").show();
        setTimeout(function() { $(".load").hide(); }, 8000);
    }

    if (changeStoreCount == 3) {
        $("a#change-store").hide();
        $("#changetmr").show();
    }

    checkSpecialsOn();

    try {
        $(".department-name").live("click", function() {
            var list = $("tr[dept=" + $(this).attr("dept") + "]")
            list.toggle();
            if (list.is(":visible"))
                $(this).css("background", "#fff url(/images/myspecials/ui/sl_arrow2.png) no-repeat scroll 0 3px");
            else
                $(this).css("background", "#fff url(/images/myspecials/ui/sl_arrow1.png) no-repeat scroll 0 3px");
        });
    } catch (e) { }

    $("#turnonspecials").click(function() {
        if (confirm("Are you sure you want to turn on the mySpecials website to the public?")) {
            $.ajax({
                type: "POST",
                url: mySpecialsWebServiceUrl + "/updatedisplaysetting",
                contentType: "application/x-www-form-urlencoded",
                async: false,
                processData: true,
                dataType: "xml",
                data: {},
                cache: false,
                success: function(xml) {
                    if ($(xml).find("string").text() == "1")
                        $("#turnon").hide();
                },
                error: function(err) {
                    //alert(err.responseText);
                }
            });
        }
    });

    $("body").click(function(e) {
        var clicked = $(e.target);
        if (clicked.is('.help-notes') || clicked.parents().is('.help-notes'))
        { }
        else {
            $(".help-notes").hide();
        }

        if (clicked.is('.clickhelp') || clicked.parents().is('.clickhelp'))
        { }
        else {
            $("#help-changestore").hide();
            $("#help-shoppinglist").hide();
            $("#help-showme").hide();
            $("#help-add").hide();
            $("#help-save").hide();
            $("#help-textarea").hide();
        }
        if (clicked.is('.store-change-event') || clicked.parents().is('.store-change-event'))
        { }
        else {
            $(".store-change-note").hide();
        }
        if (clicked.is(".load") || clicked.parents().is(".load")) { }
        else {
            $(".load").hide();
        }
    });

    $(".txtsmall").click(function() {
        var elements = document.getElementsByTagName("body");
        var body = elements[0];
        body.style.fontSize = '';
        return false;
    });
    $(".txtlarge").click(function() {
        var elements = document.getElementsByTagName("body");
        var body = elements[0];
        body.style.fontSize = '75%';
        return false;
    });
    $(".btn-print").click(function() {
        if (window.print) {
            window.print();
        }
    });
    $(".btn-email").click(function() {
        // Within the body use "%0A" for a new line,
        // use "%0A%0A" for a new line preceded by a blank line (paragraph),
        var newHref = $(this).attr('href');
        newHref += '&body=I found the following link helpful:%0A%0a' + document.title + ' - ' + document.location.href;
        $(this).attr('href', newHref);
    });



    $(".topnav").click(function() {
        var url = window.location.pathname;
        var current = $(this).attr("goto");
        if (url.toLowerCase().indexOf("foodtown") >= 0)
            window.location.href = current.replace(/foodtown/, "foodtown");
        else if (url.toLowerCase().indexOf("woolworths") >= 0)
            window.location.href = current.replace(/foodtown/, "woolworths");
        else if (url.toLowerCase().indexOf("countdown") >= 0)
            window.location.href = current.replace(/foodtown/, "countdown");
        return false;
    });

    $(".topnav").click(function() {
        var url = window.location.pathname;
        var current = $(this).attr("goto");
        if (url.toLowerCase().indexOf("foodtown") >= 0)
            window.location.href = current.replace(/foodtown/, "foodtown");
        else if (url.toLowerCase().indexOf("woolworths") >= 0)
            window.location.href = current.replace(/foodtown/, "woolworths");
        else if (url.toLowerCase().indexOf("countdown") >= 0)
            window.location.href = current.replace(/foodtown/, "countdown");
        return false;
    });


    $("#searchbox").focus(function() {
        $(this).val("");
    });

    $("#searchbox").keypress(function(e) {
        if (e.which == 13) {
            $(".btngo").trigger("click");
            return false;
        }
    });

    $('.cardname-note').hover(
        function() {
            $(".hoverpanel").show();
        },
        function() {

        }
    );
    $(".hoverpanel").hover(
        function() { },
        function() {
            $(this).hide();
        }
    );
    //Store change
    $("#change-store").click(function() {
        $("#store-display").hide();
        $("#searchLocation").show("slow");
        $("#change-store-panel").css("background", "no-repeat scroll left top");
    });
    $("#searchLocation").change(function() {

        var value = $("#searchLocation option:selected").val();
        $("select.town-store").addClass("store-select");
        $("#region" + value).removeClass("store-select");
        if ($("#searchLocation :selected").val() != "Select your town")
            $("#header .blockstore .cs").css("top", "15px");
        else
            $("#header .blockstore .cs").css("top", "26px");
    });

    $("#ShoppingListEmail").click(function() {
        $.ajax({
            type: "POST",
            url: "http://" + location.host + "/usercontrols/MySpecialsUserControls/WebServices/MySpecialsWebService.asmx/GetSpecialListText",
            contentType: "application/x-www-form-urlencoded",
            async: false,
            processData: true,
            dataType: "xml",
            data: {
        },
        cache: false,
        success: function(data) {
            var newHref = "mailto:?subject=mySpecials shopping list";
            newHref += '&body=' + $(data).find("string").text();
            $("#ShoppingListEmail").attr('href', newHref);
        },
        error: function(err) {
            alert(err.responseText);
        }
    });
});

$("#logout").click(function() {
    $.ajax({
        type: "POST",
        url: mySpecialsWebServiceUrl + "/Logout",
        contentType: "application/x-www-form-urlencoded",
        async: false,
        processData: true,
        dataType: "xml",
        data: {},
        cache: false,
        success: function(xml) {
            window.location.reload(true);
        },
        error: function(err) {
            alert('error');
        }
    });
    return false;
});
/* help */
$(".clickhelp").click(function() {
    $("#help-changestore").toggle();
    $("#help-shoppinglist").toggle();
    $("#help-showme").toggle();
    var videoposition = $(".btnshowme").position();
    $("#help-showme").css("top", videoposition.top - 100);
    $("#help-showme").css("left", videoposition.left - 150);

    $("#help-add").toggle();
    $("#help-save").toggle();
    var saveposition = $("li.save").position();
    $("#help-save").css("top", saveposition.top - 120);

    $("#help-textarea").toggle();
    var textareaposition = $(".boxarea").position();
    $("#help-textarea").css("top", textareaposition.top - 100);
    $("#help-textarea").css("left", textareaposition.left - 150);
});

$('a#notepadtoggle').click(function() {
    if ($("#notepadextend").is(":hidden"))
        $(this).css("background-image", "url(/images/myspecials/ui/icon_arrowup.gif)");
    else
        $(this).css("background-image", "url(/images/myspecials/ui/icon_arrowdown.gif)");
    $('#notepadextend').toggle(200);
    return false;
});

$('li.headlink').hover(
			function() { $('ul', this).css('display', 'block'); },
			function() { $('ul', this).css('display', 'none'); }
    );
$('li.storedrop').hover(
			function() { $('ul', this).css('display', 'block'); },
			function() { $('ul', this).css('display', 'none'); }
    );
});

function GetStoreChangeCount(iscd) {
    var count;
    $.ajax({
        type: "POST",
        url: mySpecialsWebServiceUrl + "/GetStoreChangeCountForToday",
        contentType: "application/x-www-form-urlencoded",
        async: false,
        processData: true,
        dataType: "xml",
        data: {
            isCD: iscd
        },
        cache: false,
        success: function(xml) {
            count = parseInt($(xml).find("int").text());
        },
        error: function(err) {
            //alert(err.responseText);
        }
    });
    return count;
}

function SaveStoreChangeLog(sid, iscd) {
    $.ajax({
        type: "POST",
        url: mySpecialsWebServiceUrl + "/SaveStoreChangeLog",
        contentType: "application/x-www-form-urlencoded",
        async: false,
        processData: true,
        dataType: "xml",
        data: {
                storeId: sid,
                isCD: iscd
              },
        cache: false,
        success: function(xml) {
            
        },
        error: function(err) {
            //alert(err.responseText);
        }
    });
}

function DisplayNote(linkid) {
    //alert("hi");
    var cassid = $("#" + linkid).attr("cassid");
    var result = GetSpecialsListItem2(cassid);
    var pos = $("#" + linkid).position();
    $("#note" + cassid).show();
    $("#note" + cassid).css("left", pos.left - 150);
    $("#note" + cassid).css("top", pos.top + 20);
    
}

function GetSpecialsListItem2(cassItemId) {
    var result;
    $.ajax({
        type: "POST",
        url: mySpecialsWebServiceUrl + "/getspeciallistitem",
        contentType: "application/x-www-form-urlencoded",
        async: false,
        processData: true,
        dataType: "xml",
        data: {
            CassItemId: cassItemId
        },
        cache: false,
        success: function(xml) {
            result = xml;
        },
        error: function(err) {
            //alert(err.responseText);
        }
    });
    return result;
}

function CloseNote(panel) {
    $("#" + panel).hide();
}


function queryStr(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}


function changestore() {
    var $storeSelect = $('#region' + $('#searchLocation option:selected').val() + ' option:selected');
    var sid = $storeSelect.val();
    var b;
    var redirectUrl;
    if ($storeSelect.parent().is(".Foodtown")) {
        b = "FT";
        redirectUrl = "http://" + location.host + "/foodtown.aspx?changestore=y";
    }
    else if ($storeSelect.parent().is(".Countdown")) {
        b = "CD";
        redirectUrl = "http://" + location.host + "/countdown.aspx?changestore=y";
    }
    else if ($storeSelect.parent().is(".Woolworths")) {
        b = "WW";
        redirectUrl = "http://" + location.host + "/woolworths.aspx?changestore=y";
    }
    $.ajax({
        type: "POST",
        url: mySpecialsWebServiceUrl + "/ChangeStore",
        contentType: "application/x-www-form-urlencoded",
        async: false,
        processData: true,
        dataType: "xml",
        data: {
            ChangeStoreId: sid,
            brand: b
        },
        cache: false,
        success: function(xml) {
            var count = GetStoreChangeCount(b == "CD");
            if (count < 3) {
                SaveStoreChangeLog(sid, b == "CD");
                window.location.href = redirectUrl;
            }
            else
                $("#changenote3").show();

        },
        error: function(err) {
            //alert(err.responseText);
        }
    });
}

function checkSpecialsOn() {
    $.ajax({
        type: "POST",
        url: mySpecialsWebServiceUrl + "/checkdisplaysetting",
        contentType: "application/x-www-form-urlencoded",
        async: false,
        processData: true,
        dataType: "xml",
        data: {},
        cache: false,
        success: function(xml) {
            if($(xml).find("boolean").text() == "false")
                $("#turnon").show();

        },
        error: function(err) {
            //alert(err.responseText);
        }
    });
}
