﻿/// <reference path="jquery-1.4.4.js" />
/// <reference path="json2.js" />
/// <reference path="jquery.metadata.js" />
/// <reference path="jquery.metadata-2.1.js" />
/// <reference path="jquery-jtemplates.js" />
/// <reference path="jquery.blockUI-2.31.js" />
/// <reference path="jquery.tools.min.js" />
function jsonDataFilter(data) {
    var msg = JSON.parse(data);
    if (msg.hasOwnProperty('d'))
        return JSON.stringify(msg.d);
    else
        return data;
}

$.ajaxWM = function(params) {
    /// <summary>This method is used to make ajax calls to page webmethods.</summary>
    params.type = params.type || 'POST';
    params.contentType = params.contentType || 'application/json; charset=utf-8';
    params.dataFilter = params.dataFilter || jsonDataFilter;
    params.data = params.data || '{}';
    $.ajax(params);
}
$.fn.serializeObject = function(initial) {
    /// <summary>Serialise the form data as a json object</summary>
    var o = initial || {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

// Src: http://dev.jquery.com/ticket/4197
// Fix for .live() bug with right click on Firefox,
// because right click it's not a click!
jQuery.fn.__live__ = jQuery.fn.live;
jQuery.fn.live = function(type, fn) {
    if (type != 'click') {
        return this.__live__(type, fn);
    } else {
        var anti_right_click_callback = fn;
        var anti_right_click_proxy = function(e) {
            if (e && e.button && e.button != 0) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            } else {
                return anti_right_click_callback.call(this, e);
            }
        };
        return this.__live__(type, anti_right_click_proxy);
    }
};

// Object converter, thanks to http://snook.ca/archives/javascript/testing_for_a_v
function oc(a) {
    var o = {};
    for (var i = 0; i < a.length; i++) {
        o[a[i]] = '';
    }
    return o;
}

$(function() {
    // Using autocomplete from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
    if ($().autocomplete) {
        $('#sinchSearchBox').autocomplete('/Search/Predict', {
            delay: 50,
            max: 8,
            minChars: 2,
            scroll: false,
            selectFirst: false,
            formatItem: function(d) { return '<a href="'+d[0]+'">'+d[1]+'</a>'; },
            formatResult: function(d) { return d[1]; },
            containerDiv: $('.searchPredictor'),
            listUl: $('.searchPredictor ul'),
            ignoreClicks: true
        });
    }
});

function StripeMe() {
    $(".stripeMe").each(function () {
        $("tbody tr:odd", this).addClass("alt");
    });

    $(".stripeMe tbody tr").mouseover(function () { $(this).addClass("trHover"); }).mouseout(function () { $(this).removeClass("trHover"); });
}

// setup stripe me initially
$(StripeMe);

$(document).ready(function () {
    // for each row
    $(".prodSummaryList").each(function () {
        // assign mouse enter event
        $(this).bind("mouseenter", function () { $(this).addClass('hovered'); });
        $(this).bind("mouseleave", function () { $(this).removeClass('hovered'); });
    })

    getAllCustomerPrices();
});

function getAllCustomerPrices() {
    if (typeof (sinchProductIDs) != 'undefined' && sinchProductIDs.length && $("#hfBasketCustomerUserID").length && $("#hfBasketCustomerUserID").val() != '') {
        $.ajax({
            url: '/MySinch/Customers/CustomerPrices',
            data: { customerUserID: $("#hfBasketCustomerUserID").val(), products: sinchProductIDs },
            type: 'POST',
            traditional: true,
            success: function (data) {
                if (!data.Success)
                    return;

                for (i in data.Results) {
                    var item = data.Results[i];
                    var $span = $('#spnCustomerPrice' + item.SinchProductID);
                    if (item.Price > 0) {
                        $span.html('&#163;' + item.Price.formatMoney()).parent().show();
                    } else {
                        $span.parent().hide();
                    }
                }
            }
        });
    }
    else {
        $(".customerPrice").hide();
        return;
    }
}

function getLivePrice(accountID, distriSku, stockControl, priceControl) {
    var ajaxLoader = new Image();
    ajaxLoader.src = '/images/ajax-loader-realtime.gif';
    $('#' + priceControl).html(ajaxLoader);
    $.post(
        '/Handlers/LivePrice.ashx',
        { accountID: accountID, code: distriSku, formatPrice: 1 },
        function (pas) {
            $('#' + stockControl).html("<span>" + pas.Stock + "</span>");
            $('#' + priceControl).html("<span>" + pas.Price + "</span>");
        },
        'json');
}

function getAllLivePrices(priceData) {
    var accounts = priceData.split("|");

    for (var i = 0; i < accounts.length; i++) {
        var account = accounts[i].split(",");
        getLivePrice(account[0], account[1], account[2], account[3]);
    }
}

$(function () {
    var hideDelay = 500;
    var currentID;
    var hideTimer = null;
    var ajax = null;
    var hideFunction = function () {
        if (hideTimer)
            clearTimeout(hideTimer);
        hideTimer = setTimeout(function () {
            currentPosition = { left: '0px', top: '0px' };
            container.css('display', 'none');
        }, hideDelay);
    };

    var currentPosition = { left: '0px', top: '0px' };

    // One instance that's reused to show info for the current person
    var container = $('<div class="balloonContainer"><div class="balloon"><div id="balloonContent"></div><img class="balloonTail" src="/Images/balloonTail.png" alt="" /></div></div>');

    $('body').append(container);

    $('.blnTrigger').live('mouseover', function () {
        if (!$(this).data('hoverIntentAttached')) {
            $(this).data('hoverIntentAttached', true);
            $(this).hoverIntent
            (
            // hoverIntent mouseOver
                function () {
                    if (hideTimer)
                        clearTimeout(hideTimer);

                    var pos = $(this).offset();
                    var width = $(this).width();
                    var reposition = { left: (pos.left + width - 27) + 'px', top: pos.top - 5 + 'px' };

                    // If the same popup is already shown, then don't requery
                    if (currentPosition.left == reposition.left &&
                        currentPosition.top == reposition.top)
                        return;

                    container.css({
                        left: reposition.left,
                        top: reposition.top
                    });

                    currentPosition = reposition;

                    $('#balloonContent').html('<img src="/Images/ajax_loader_small.gif" alt="Loading" />');

                    if (ajax) {
                        ajax.abort();
                        ajax = null;
                    }

                    ajax = $.ajax({
                        type: 'POST',
                        url: $(this).data('blnhref'),
                        data: $(this).data('blndata'),
                        success: function (data) {
                            $('#balloonContent').html(data);
                        }
                    });

                    container.css('display', 'block');
                },
            // hoverIntent mouseOut
                hideFunction
            );
            // Fire mouseover so hoverIntent can start doing its magic
            $(this).trigger('mouseover');
        }
    });

    // Allow mouse over of details without hiding details
    $('#balloonContent').mouseover(function () {
        if (hideTimer)
            clearTimeout(hideTimer);
    });

    // Hide after mouseout
    $('#balloonContent').mouseout(hideFunction);
});

var storeConst = {
    $sinchLoader: '<img src="/Images/sinch-loader.gif" alt="Loading" />',
    $smallLoader: '<img src="/Images/smallLoader.gif" alt="Loading" />',
    $smallLoaderLeft: '<img src="/Images/smallLoader.gif" alt="Loading" class="left" />',
    $smallLoaderRight: '<img src="/Images/smallLoader.gif" alt="Loading" class="right" />'
};

function blockOptions(message) {
    return {
        css: {
            border: 'none',
            backgroundColor: '#fff',
            width: 'auto'
        },
        overlayCSS: {
            backgroundColor: '#ddd'
        },
        message: message || storeConst.$sinchLoader
    };
}

$.fn.charCounter = function (maxChars, maxCharsWarning) {
    this.jqEasyCounter({
        'maxChars': maxChars,
        'maxCharsWarning': maxCharsWarning,
        'msgFontSize': '10px',
        'msgFontColor': '#000',
        'msgFontFamily': 'Verdana',
        'msgTextAlign': 'right',
        'msgWarningColor': '#F00',
        'msgAppendMethod': 'insertAfter'
    });
};

Number.prototype.formatMoney = function (c, d, t) {
    if (this == null) return null;
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

function formatMoney(val) { if (val != null) return val.formatMoney(); return null; }

function loadLivePrices(productID) {
    $.ajax({
        url: '/MySinch/LivePrices/Lookup',
        type: 'POST',
        data: { productID: productID },
        success: function (data) {
            if (data.Success == true)
                viewModel["livePrice" + productID](data.Payload);
            else
                alert(data.Message);
        },
        error: function () {
            alert('Error looking up prices!');
        }
    });
}
