﻿var buytabs_array = [];
var buy_currenttab = 0;

function initBuyTabs() {
    buytabs_array = [$("#buy-main"), $("#buy-course")];
    $("h2", buytabs_array[0]).click(function() { tabClick(0); return false; });
    $("h2", buytabs_array[1]).click(function() { tabClick(1); return false; });
}

function tabClick(n) {
    if (buy_currenttab != n) {
        buytabs_array[buy_currenttab].removeClass("selected");
        buytabs_array[n].addClass("selected");
        buy_currenttab = n;
    }

    if (n != 1) {
        document.getElementById("State_Abbreviation").selectedIndex = 0;
        document.getElementById("SiteId").options.length = 0;
        document.getElementById("SiteId").options[0] = new Option("Select your school");
    }
}

var ISBNFeedback = Class.extend({
    init: function(targetid) {
        this.displaylist = false;
        this.target = $("#" + targetid);
        this.textarea = $("textarea", this.target);
        this.cache = new Array();
        this.validisbn_array = new Array();

        // wrap the desc content in an extra div
        $(".desc", this.target).wrapInner('<div class="non-ajax-content"></div>');

        // add a container to hold our ajax results, hidden by default
        var html = '<div class="ajax-results" style="display:none">';
        html += '	<h3>You\'ve entered (<span class="result-count">0</span>) valid ISBNs.</h3>';
        html += '	<ul></ul>';
        html += '</div>';

        $(".desc", this.target).append(html);
        this.ul = $(".ajax-results ul", this.target);
        this.resultcount = $(".ajax-results .result-count", this.target);

        // add events to watch for changes of the textarea
        var self = this;
        this.textarea.bind("keyup", { self: this }, function(event) {
            var self = event.data.self;
            self.checkInputContents();
            return false;
        });
        // manually trigger the keyup event in case the textarea already has a value
        this.textarea.keyup();

    },

    checkInputContents: function() {
        this.findISBNs(this.textarea.val());
    },

    findISBNs: function(str) {
        // this function picks one or many ISBN-formatted numbers from a string and
        // determines if they are valid ISBNs.  Supports ISBN-10 and ISBN-13.

        var pattern = /\d{13}|\d{9}[0-9Xx]{1}/g;  	// revised and simplified, supports ISBN-10 and ISBN-13
        // NOTE: this pattern assumes that ALL separators have been removed
        // by the stripSeparators method
        var result;

        // strip out any hyphens or spaces
        var str = this.stripSeparators(str);

        result = str.match(pattern);
        if (result) {
            this.validisbn_array.length = 0;
            for (var i = 0; i < result.length; i++) {
                result[i] = this.validateISBN(result[i]); // returns isbn if valid, 0 if not
                if (result[i] != 0) {
                    this.validisbn_array.push(result[i]);
                }
            }
            this.renderList(this.validisbn_array);
            if (this.validisbn_array.length > 0) {
                this.updateResultsDisplay(true);
            }
        } else {
            this.updateResultsDisplay(false);
        }
    },

    validateISBN: function(isbn) {

        if (isbn.length == 10) {
            return this.validateISBN10(isbn);
        } else if (isbn.length == 13) {
            return this.validateISBN13(isbn);
        } else {
            return 0;
        }
    },

    validateISBN10: function(isbn) {

        var checksum = 0;
        for (var i = 0; i < 9; i++) {
            checksum += isbn.charAt(i) * (i + 1);
        }
        checksum = checksum % 11;
        checksum = (checksum == 10) ? "X" : checksum;

        if (isbn.charAt(9) == checksum) {
            return isbn;
        } else {
            return 0;
        }
    },

    validateISBN13: function(isbn) {

        var checksum = 0;
        for (var i = 0; i < 12; i++) {
            var digit = isbn.charAt(i);
            digit *= (i % 2 == 0) ? 1 : 3;
            checksum += digit;
        }

        checksum = 10 - (checksum % 10);

        checksum = (checksum == 10) ? 0 : checksum;

        if (isbn.charAt(12) == checksum) {
            return isbn;
        } else {
            return 0;
        }

    },

    stripSeparators: function(isbn) {
        // strips hyphens and spaces from isbn -- makes it easier to use for things like IDs
        return isbn.replace(/[- ]/g, "");
    },

    renderList: function(array) {
        var html = "";
        var request_array = [];
        for (var i = 0; i < array.length; i++) {
            var bookinfo = "";
            // check the cache for existing info, hit the server if necessary
            if (this.cache["ISBN" + array[i]] != undefined) {
                bookinfo = this.formatBookInfo(this.cache["ISBN" + array[i]]);
            } else {
                // create a placeholder
                bookinfo = array[i] + " : Loading...";
                // request the info from the server, it will be added after load
                request_array.push(array[i]);
            }
            html += "<li class='isbn" + array[i] + "'>" + bookinfo + "</li>\n";
        }

        this.ul.html(html);

        for (var i = 0; i < request_array.length; i++) {
            this.requestBookInfo(request_array[i]);
        }

        $(".result-count", this.target).html(array.length);
    },

    formatBookInfo: function(book) {
        // simple function for formatting a book object as an HTML string for display
        var section = this.target[0].id;

        var searchController = (section == "buy-main") ? "SearchKeyword" : "SearchSellback";

        return '<a style="text-decoration:none;" href="/Search/' + searchController + '/' + book.isbn + '"><span class="title">' + book.title + '</span>, <span class="author">' + book.author + '</span> <span class="isbn">ISBN&nbsp;' + book.isbn + '</span></a>';
    },

    requestBookInfo: function(isbn) {
        var url = "/Search/IsbnFeedback";
        var self = this;

        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            data: { isbn: isbn },
            success: function(json) {
                self.processBookInfo(json);
            }
        });
    },

    processBookInfo: function(data) {
        // store results in the cache
        this.cache["ISBN" + this.stripSeparators(data.isbn)] = data;
        $(".isbn" + this.stripSeparators(data.isbn), this.ul).html(this.formatBookInfo(data));
    },

    updateResultsDisplay: function(boolShow) {
        if (boolShow) {
            // the results should be displayed
            if (this.displaylist == false) {
                // toggle the results display
                this.displaylist = true;
                var self = this;
                $(".non-ajax-content", this.target).fadeOut("fast", function() {
                    $(".ajax-results", self.target).fadeIn("fast");
                });
            }
        } else {
            // there are 0 results, do not show the results list
            if (this.displaylist == true) {
                // toggle the results display
                this.displaylist = false;
                var self = this;
                $(".ajax-results", this.target).fadeOut("fast", function() {
                    $(".non-ajax-content", self.target).fadeIn("fast");
                });
            }
        }
    }

});

var topSellerRotator = {};

function topSellerRotatorInit(selector) {
    topSellerRotator.items = $(selector);
    topSellerRotator.interval = 5; // in secs
    topSellerRotator.currentIndex = 0;
    $(topSellerRotator.items).hide();

    if (topSellerRotator.items[0] != null)
        $(topSellerRotator.items[0]).show();
    
    // start the interval
    if (topSellerRotator.items.length > 1) {
        topSellerRotator.intervalID = setInterval(topSellerRotatorAdvance, topSellerRotator.interval * 1000);
    }
}

function topSellerRotatorAdvance() {
    $(topSellerRotator.items[topSellerRotator.currentIndex]).fadeOut("normal", topSellerRotatorShowNext);
}

function topSellerRotatorShowNext() {
    if (topSellerRotator.currentIndex < topSellerRotator.items.length - 1) {
        topSellerRotator.currentIndex++;
    } else {
        topSellerRotator.currentIndex = 0;
    }
    $(topSellerRotator.items[topSellerRotator.currentIndex]).fadeIn();
}

$(document).ready(function() {
    initBuyTabs();
    sell_isbn = new ISBNFeedback("sell-isbn");
    buy_isbn = new ISBNFeedback("buy-main");
    topSellerRotatorInit("#buy-topsellers ol > li");
    $('.help').cluetip({ arrows: true });
});