$(document).ready(function() {

    SuperFishMenuSetup();
    SetClassHelpers();
    SearchSetup();
    TabSetup();
    ZoomSetup();
    SubscribeDialog();
    QuestionDialog();
});

function SuperFishMenuSetup() {

    $('ul.sf-menu').superfish({
        pathClass: 'current',
        autoArrows: false,
        onInit: function() {

            $(this).find('ul.mega-menu li:has(ol)').each(function() { // for each li
                // Set the toal width of the mega menu li element based on the column size * number of columns
                // $this = mega-menu li element

                var singleColumnWidth = parseFloat($(this).children(':first').css('width')) + 1; // Column width + 1px for column border separator
                var numberOfColumns = $(this).children('ol').size();
                var megaMenuWidth = (singleColumnWidth * numberOfColumns) + 'px';
                $(this).css({ 'width': megaMenuWidth });
                // Set parent ul width for shadow image to display correctly
                $(this).parent().css({ 'width': megaMenuWidth });

                // Set the left position of the mega menu ul element. If right corner is outside of
                // website then set mega menu left to negative value to move mega menu inside website.
                parentMenuPositionLeft = parseFloat($(this).parent().parent().position().left);
                parentMenuWidth = parseFloat($(this).parent().parent().parent().css('width'));
                megaMenuPositionRight = parseFloat(megaMenuWidth) + parentMenuPositionLeft;
                if (megaMenuPositionRight > parentMenuWidth) {
                    megaMenuLeftAdjusted = (parentMenuWidth - megaMenuPositionRight) + 'px';
                    $(this).parent().css({ 'left': megaMenuLeftAdjusted });
                }
                //$('#jdebug').append(megaMenuLeftAdjusted + ' ');
            });
        }
    });

}

function SetClassHelpers() {

    /* Standard buttons */
    $('input[id$=ctrlLogin_LoginButton]').addClass('LoginButton');
    $('input[id$=UserNameContainerID_btnRequestNewPassword]').addClass('RequestNewPasswordButton');
    $('input[id$=PageContent_btnRequestEstimates]').addClass('GetEstimatesButton');
    $('input[id$=PageContent_btnSignInAndCheckout]').addClass('SignInAndCheckoutButton');
    $('input[id$=PageContent_RegisterAndCheckoutButton]').addClass('RegisterAndCheckoutButton');
    $('input[id$=PageContent_btnCheckOut]').addClass('ContinueCheckoutFinalButton');
    $('input[id$=PageContent_btnRecalcShipping]').addClass('GetShippingOptionsButton');

    /* Standard search control */
    $('input[id$=ctrlSearch_SearchButton]').addClass('Button');
    $('input[id$=ctrlSearch_SearchText]').addClass('Text');
}

// Set default search text. Select text on control focus.
function SearchSetup() {

    $search = $('input[id$=ctrlSearch_SearchText]');
    $search.val('Keyword');
    $search.focus(function() {
        this.select();
    });
}

function TabSetup() {

    var $tabs = $('#tabs');

    // Show tabs.
    $tabs.tabs();

    // Set event for rating summary link
    $('#ProductRatingsSummary').click(function() {
        $tabs.tabs('select', 1);
    });

    // Set events for product navigation links (jump to tabs).
    $('#PageWrapper.Product #DescriptionLink').click(function() {
        $tabs.tabs('select', 0);
        //SetProductMenuLink($(this));
    });
    $('#PageWrapper.Product #ReviewsLink').click(function() {
        $tabs.tabs('select', 1);
        //SetProductMenuLink($(this));
    });
    $('#PageWrapper.Product #SpecificationLink').click(function() {
        $tabs.tabs('select', 2);
        //SetProductMenuLink($(this));
    });
}

function ZoomSetup() {

    var isLargeImage = $('#PageWrapper.Product .MainImage img[src$=showlarger.gif]').length;
    if (isLargeImage) {
        // Add anchor wrapper required by jqzoom to product medium image.
        $img = $('#PageWrapper.Product img[id^=ProductPic]').wrap(function() {
            src = $(this).attr('src').replace('medium', 'large');
            return '<a href="' + src + '" class="ProductZoom" title="Zoom">' + $(this).text() + '</a>';
        });
        // Initialize jqzoom.
        $('.ProductZoom').jqzoom({
            zoomWidth: 360,
            zoomHeight: 340,
            yOffset: -13
        });
    }
}

function SetProductMenuLink($element) {

    // Clear all links
    $('#PageWrapper.Product #DescriptionLink').removeClass('Selected');
    $('#PageWrapper.Product #ReviewsLink').removeClass('Selected');
    $('#PageWrapper.Product #SummaryLink').removeClass('Selected');

    // Set link
    $element.addClass('Selected');
}

function SubscribeDialog() {

    // Save the dialog initial content (we must put it back when we close the dialog).
    // If we don't, when user clicks to join a second time (on same page) they'll see content from the previous click.
    var dialogContent = $('.SubscribeDialog .Content').html();
    
    // Initialize dialog.
    $('.SubscribeDialog').dialog({
        autoOpen: false,
        modal: true,
        width: 475,
        dialogClass: 'Subscribe',
        draggable: true,
        resizable: false,
        zindex: 999,
        buttons: { 'Close': function() { $(this).dialog('close'); } },
        close: function(event, ui) { $('.SubscribeDialog .Content').html(dialogContent); }
    });

    // Display dialog on button click.
    $('#Subscribe .Button').click(function() {

        var email = $('input[id$=ucSubscribe_txtEmail]').val();

        var params = new Array(1);
        for (i = 0; i < params.length; i++) params[i] = new Array(2);

        params[0][0] = 'email';
        params[0][1] = email;

        $.ajax({
            type: 'POST',
            url: 'AJAX.asmx/ConstantContactSubscribe',
            // dataType: 'text', // Use text to view full xml returned by web service call.
            dataType: 'xml',
            // data: 'key1=value1&key2=value2',
            // Variable names are case sensitive.
            // Encode strings as required.
            data: CreateJQueryAJAXParams(params),
            success: function(data) {
                // data = XMLDocument object i.e. http://www.w3schools.com/Dom/dom_document.asp
                // alert(data) // Return raw result data.
                // alert(data.getElementsByTagName('string')[0].childNodes[0].nodeValue);  // Return a single value where WebService call returns string value.
                var title = data.getElementsByTagName('title')[0].childNodes[0].nodeValue;
                var content = data.getElementsByTagName('content')[0].childNodes[0].nodeValue;
                // Display subscription result in dialog.
                $('.SubscribeDialog .Image').remove();
                $('.SubscribeDialog .Title').html(title);
                $('.SubscribeDialog .Text').html(content);

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            }
        });

        $('.SubscribeDialog').dialog('open');
    });
}

function QuestionDialog() {

    // Initialize dialog.
    $('#QuestionDialog').dialog({
        autoOpen: false,
        modal: true,
        width: 475,
        dialogClass: 'Question',
        draggable: true,
        resizable: false,
        zindex: 999,
        buttons: { 'Cancel': function() { $(this).dialog('close'); }, 'Send': function() { QuestionDialogSend($(this)); } }
    });

    // Display dialog on button click.
    $('#btnQuestion').click(function() {
        $('#QuestionDialog').dialog('open');
    });
}

function QuestionDialogSend($dialog) {

    var productID = $dialog.find('#hidProductID').val();
    var productName = $dialog.find('#hidProductName').val();
    var email = $dialog.find('#txtEmail').val();
    var question = $dialog.find('#txtQuestion').val();

    var params = new Array(4);
    for (i = 0; i < params.length; i++) params[i] = new Array(2);

    params[0][0] = 'productID';
    params[0][1] = productID;
    params[1][0] = 'productName';
    params[1][1] = escape(productName);
    params[2][0] = 'customerEmail';
    params[2][1] = escape(email);
    params[3][0] = 'question';
    params[3][1] = escape(question);

    $.ajax({
        type: 'POST',
        url: 'AJAX.asmx/AskAQuestionSend',
        // dataType: 'text'
        dataType: 'xml',
        // data: 'key1=value1&key2=value2',
        // Variable names are case sensative.
        // Encode strings as required.
        data: CreateJQueryAJAXParams(params),
        success: function(data) {
            var htmlReturn = data.getElementsByTagName('string')[0].childNodes[0].nodeValue;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.responseText);
        }
    });

    $dialog.dialog('close');
}

// key1=value1&key2=value2
function CreateJQueryAJAXParams(a) {

    var params = '';

    for (i = 0; i < a.length; i++) {
        if (i != 0) {
            params += '&';
        }
        params += a[i][0] + '=' + a[i][1];
    }
    return params;
}

