﻿/// <reference path="jquery-1.3.2.min.js" />
/// <reference path="global.js" />
/* 
	AJAX Functionality for Item 
	
	(C) 2009 Orange Tentacle. Click Databases
*/

$j(document).ready(function() {
    var ref = new PageObject();
    // ref.debug = 1;
    ref.init();
});


function PageObject(){}

// Container object for anything interesting.
PageObject.prototype = {

    _conflicts: 0, // Array of conflicts - part of configurator
    _count: 0, // Gallery count.
    _totalCount: 0, // Total Gallery images.

    /* Any initalization happens here. */
    init: function() {
        var ref = this;

        if (window.location.hash == '') {
            window.location.hash = '#overview';
        }

        ref.highlightTab(ref);
        ref.loadPage(ref);
        $j('.tabs li a').bind("click", { vs: ref }, ref.loadTab);
    },

    /* Highlights the selected tab. */
    highlightTab: function(ref) {
        $j('.tabs li').each(function() {
            if (window.location.hash == $j('a', this).attr('href')) {
                if ($j(this).hasClass('configure')) {
                    $j(this).removeClass('configure').addClass('configure-selected');
                } else {
                    $j(this).addClass('selected');
                }
            } else {
                if ($j(this).hasClass('configure-selected')) {
                    $j(this).removeClass('configure-selected').addClass('configure');
                } else {
                    $j(this).removeClass('selected');
                }
            }
        });
    },

    loadTab: function(ev) {
        var ref = ev.data.vs;
        var tab = $j(this);

        window.location.hash = tab.attr('href');
        ref.highlightTab(ref);
        ref.loadPage(ref);
    },

    loadPage: function(ref) {
        var ref = this;

        switch (location.hash) {
            case '#specifications':
                ref.loadSpec(ref);
                break;
            case '#video':
                ref.loadVideo(ref);
                break;
            case '#gallery':
                ref.loadGallery(ref);
                break;
            case '#downloads':
                ref.loadDownloads(ref);
                break;
            case '#configure':
                ref.loadConfigure(ref);
                break;
            default:
                ref.loadOverview(ref);
                break;
        }
    },

    loadOverview: function(ref) {
        $j.get("/AJAX/ItemOverview.aspx?id=" + $j('.itemId').text(), function(data, textStatus) { ref.postAjaxLoad(ref, data, textStatus); }, 'text');
    },

    loadSpec: function(ref) {
        $j.get("/AJAX/ItemSpecification.aspx?id=" + $j('.itemId').text(), function(data, textStatus) { ref.postAjaxLoad(ref, data, textStatus); });
    },

    loadVideo: function(ref) {
        $j.get("/AJAX/ItemVideo.aspx?id=" + $j('.itemId').text(), function(data, textStatus) { ref.bindVideo(ref, data, textStatus); });
    },

    loadGallery: function(ref) {
        $j.get("/AJAX/ItemGallery.aspx?id=" + $j('.itemId').text(), function(data, textStatus) { ref.bindGallery(ref, data, textStatus); });
    },

    loadDownloads: function(ref) {
        $j.get("/AJAX/ItemDownloads.aspx?id=" + $j('.itemId').text(), function(data, textStatus) { ref.postAjaxLoad(ref, data, textStatus); });
    },

    loadConfigure: function(ref) {
        $j.get("/AJAX/ItemConfig.aspx?id=" + $j('.itemId').text(), function(data, textStatus) { ref.bindConfigurator(ref, data, textStatus); });
    },

    bindVideo: function(ref, data, textStatus) {
        var newData = $j(data);
        $j('#flashContent', newData).bind("load", function() {
            swfobject.registerObject("flashContent", "9.0.115", "/_prodVideos/expressInstall.swf");
        });
        $j('.ajaxContent').children().remove().end().append(newData);
        $j('.ajaxContent').show();

        DDFix();
    },

    bindGallery: function(ref, data, textStatus) {
        $j('.ajaxContent').html(data);
        $j('.ajaxContent').show();
        Cufon.refresh();

        ref._count = 0;
        ref._totalCount = $j('#GalleryImages li').length;

        $j('.prev').bind("click", function() { ref.changePage(ref, ref._count - 1); return false; });
        $j('.next').bind("click", function() { ref.changePage(ref, ref._count + 1); return false; });

        DDFix();
    },

    changePage: function(ref, newIndex) {

        // If our requested page is outside of bounds, return.
        if (newIndex < 0 || newIndex > ref._totalCount - 1) {
            return;
        }

        // Determine if first/last page has been reached.
        if (newIndex == 0) {
            $j("div.prev").addClass('prev-disabled');
        } else {
            $j("div.prev").removeClass('prev-disabled');
        }

        if (newIndex == ref._totalCount - 1) {
            $j("div.next").addClass('next-disabled');
        } else {
            $j("div.next").removeClass('next-disabled');
        }

        var newImage = $j('#GalleryImages li:eq(' + newIndex + ') a');
        ref.setImage(ref, newImage);

        // Finally - set the current page.
        ref._count = newIndex;
        $j('.count').text(newIndex + 1);

    },

    /* Sets the image to appear. */
    setImage: function(ref, image) {
        var bigImage = $j(".mainImg");
        bigImage.fadeOut('slow', function() {
            bigImage.bind("load", ref.fadeNewIn);
            bigImage.attr('src', image.attr('href'));
            bigImage.attr('title', image.attr('title'));
        });
    },

    fadeNewIn: function() {
        var bigImage = $j(".mainImg");
        bigImage.fadeIn('slow');
    },

    postAjaxLoad: function(ref, data, textStatus) {
        $j('.ajaxContent').html(data);
        $j('.ajaxContent').show();
        Cufon.refresh();
        DDFix();
    },

    bindConfigurator: function(ref, data, textStatus) {
        $j('.ajaxContent').html(data);
        $j('.ajaxContent').show();

        // Fix the name attribute on the group input radio.
        $j('ul.base li input').each(function() {
            $j(this).attr('name', 'base');
        });

        var itemId = $j('.itemId').text();
        var url = "/Services/GetConflicts.ashx?ItemId=" + itemId;
        $j.getJSON(url, null, function(data, textStatus) { ref._conflicts = data });

        $j('select.position').bind("change", function() { ref.updateConflicts(ref, $j(this)); ref.refreshTotals(ref); ref.updateInfo(ref, $j(this)); });
        $j('ul.base input').bind("change", function() { ref.refreshTotals(ref); });
        $j('ul.configuration li a').bind("click", function() { ref.newDefaults(ref, $j(this)); return false; });
        $j('a.info').bind("click", function() { ref.switchInfo(ref, $j(this)); return false; });
        $j('a.download').bind("click", function() { ref.generatePdf(ref); return false; });
        $j('a.contact').bind("click", function() { ref.showContact(ref); return false; });

        ref.refreshTotals(ref);
        DDFix();
    },

    /* Applies the relevant update conflicts method, depending upon browser. */
    updateConflicts: function(ref, target) {
        if (jQuery.browser.msie && parseInt(jQuery.browser.version.substr(0, 1)) < 8) {
            ref.updateConflictsNonCompliant(ref, target);
        } else {
            ref.updateConflictsCompliant(ref, target);
        }
    },

    /* Updates and removes conflicted items - adding new ones as appropiate. */
    updateConflictsCompliant: function(ref, target) {

        $j("select.position option:disabled").each(function() {
            $j(this).text($j(this).attr('title'));
            $j(this).removeAttr('disabled');
        });

        $j("select.position").each(function() {
            var select = $j(this);
            var key = select.val();
            if (ref._conflicts[key] != null) {
                for (var select in ref._conflicts[key]) {
                    var clash = ref._conflicts[key][select];
                    
                    var source = $j("select.position option[value='" + key + "']");
                    var conflict = $j("select.position option[value='" + clash + "']");

                    conflict.text(conflict.attr('title') + ' (Not available with ' + source.attr('title') + ')');
                    conflict.attr('disabled', 'disabled');
                }
            }
        });

    },

    /* Updates and removes conflicted items - adding new ones as appropiate.  IE6 version */
    updateConflictsNonCompliant: function(ref, target) {

        /* Remove optgroups and replace with opts. */
        $j("select.position optgroup").each(function() {
            var optgroup = $j(this);
            var option = $j('<option />').attr('value', optgroup.attr('value'))
                .attr('title', optgroup.attr('title'))
                .text(optgroup.attr('title'))
                .insertAfter(optgroup);
            optgroup.remove();
        });

        /* Replace all clashed elements with closed optgroups */
        $j("select.position").each(function() {
            var select = $j(this);
            var key = select.val();
            if (ref._conflicts[key] != null) {
                for (var select in ref._conflicts[key]) {
                    var clash = ref._conflicts[key][select];
                    var option = $j("select.position option[value='" + clash + "']");
                    var conflict = $j("select.position option[value='" + key + "']");
                    
                    var optiongroup = $j('<optgroup />').attr('value', option.attr('value'))
                        .attr('title', option.attr('title'))
                        .attr('label', option.attr('title') + ' (Not available with ' + conflict.attr('title') + ')')
                        .insertAfter(option);
                    option.remove();
                }
            }
        });

    },

    /* Switches the visible/hidden state for a given component.
    Also updates the data if switching to a visible state. */
    switchInfo: function(ref, target) {
        var targetBlock = $j('.infoBlock', target.parent());

        if (target.hasClass('info-expanded')) {
            target.removeClass('info-expanded').addClass('info');
            targetBlock.slideUp("slow", function() { target.text('info'); });
        } else {
            ref.showInfo(ref, target);
        }
    },

    /* Update the info for a currently expanded target. */
    updateInfo: function(ref, target) {
        var infoButton = $j('.info-expanded', target.parent());
        if (infoButton.length > 0) {
            ref.showInfo(ref, infoButton);
        }
    },

    /* Shows the information for a selected component */
    showInfo: function(ref, target) {
        var targetBlock = $j('.infoBlock', target.parent());

        var item = $j('select', target.parent()).val();
        var url = "/Services/GetInfo.ashx?itemId=" + item;

        /* Get the info block, set the data and then display
        the block. */
        $j.getJSON(url, null, function(data, textStatus) {
            if (data.Description != "") {
                target.removeClass('info').addClass('info-expanded');

                if (data.ImageUrl != "") {
                    $j('.infoImage', targetBlock).show();
                    $j('.infoImage', targetBlock).attr('src', data.ImageUrl);
                } else {
                    $j('.infoImage', targetBlock).hide();
                }

                $j('.infoContent', targetBlock).html(data.Description);

                targetBlock.slideDown('slow', function() { target.text('close'); });
            } else {
                target.removeClass('info-expanded').addClass('info');
                targetBlock.slideUp('slow', function() { target.text('info'); });
            }

        });
    },

    /* Generates the PDF for the user to download and print. */
    generatePdf: function(ref) {
        var itemId = $j('.itemId').text();
        var baseId = $j('input[name="base"]:checked').val();

        var url = "/Services/GetPDF.ashx?" +
                "&ItemId=" + itemId +
                "&BaseId=" + baseId;

        $j('.position').each(function() {
            var position = $j(this).attr('id');
            var posValue = $j(this).val();
            url = url + "&" + position + "=" + posValue;
        });

        window.open(url);
    },

    /* Show the contact us thickbox. */
    showContact: function(ref) {
        var itemId = $j('.itemId').text();
        var baseId = $j('input[name="base"]:checked').val();

        var url = "/ContactForm.aspx?destination=SalesEmail&KeepThis=true&attach=true" +
                    "&ItemId=" + itemId +
                    "&BaseId=" + baseId;

        $j('.position').each(function() {
            var position = $j(this).attr('id');
            var posValue = $j(this).val();
            url = url + "&" + position + "=" + posValue;
        });

        url = url + '&TB_iframe=true&height=450&width=415&modal=true';

        tb_show('Title', url, null, function() { });
    },

    /* Calls for a refresh of new totals  */
    refreshTotals: function(ref) {
        var itemId = $j('.itemId').text();
        var baseId = $j('input[name="base"]:checked').val();

        var url = "/Services/GetPriceImage.ashx?" +
            "&ItemId=" + itemId +
            "&BaseId=" + baseId;

        $j('.position').each(function() {
            var position = $j(this).attr('id');
            var posValue = $j(this).val();
            url = url + "&" + position + "=" + posValue;
        });

        $j.getJSON(url, null, function(data, textStatus) { ref.setRefreshTotals(data, textStatus, ref); });
    },

    /* Sets the new totals from the returned values. */
    setRefreshTotals: function(data, textStatus, ref) {
        $j('#ImageContainer img').attr('src', data.ImageUrl);
        $j('#Summary span.config').text('£' + data.Configuration.toFixed(2));
        $j('#Summary span.shipping').text('£' + data.Shipping.toFixed(2));
        $j('#Summary span.vat').text('£' + data.VAT.toFixed(2));
        $j('#Summary span.total').text('£' + data.Total.toFixed(2));
    },

    /* loads a new set of configuration defaults depending on the option
    clicked. */
    newDefaults: function(ref, target) {
        $j('.button-preset-selected').removeClass('button-preset-selected').addClass('button-preset');
        target.removeClass('button-preset').addClass('button-preset-selected');
        var configId = target.attr('class').split(' ')[0].split('-')[1];

        /* Close all outstanding tabs. */
        $j('.info-expanded').each(function() {
            var target = $j(this);
            var targetBlock = $j('.infoBlock', target.parent());

            target.removeClass('info-expanded').addClass('info');
            targetBlock.slideUp('slow', function() { target.text('info'); });
        });

        $j.getJSON('/Services/GetConfig.ashx?configId=' + configId, null,
            function(data, textStatus) { ref.setNewDefaults(data, textStatus, ref); });
    },

    /* Sets the new defaults from the returned values. */
    setNewDefaults: function(data, textStatus, ref) {

        /* Set the base */
        $j("ul.base li input").attr('checked');
        $j("ul.base li input[value='" + data.BaseId + "']").attr('checked', 'checked');

        /* Set the new drop down defaults... */
        for (var option in data.Options) {
            var target = $j("option[value='" + data.Options[option] + "']");
            target.parent().val(data.Options[option]);
        }

        /* Refresh the totals. */
        ref.refreshTotals(ref);
    }
}

/* Returns a parameter from the url. */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
} 