﻿/// <reference path="includes/js/jquery.min.js" />

String.prototype.namespace = function(separator) {
    var ns = this.split(separator || '.'), p = window, i;
    for (i = 0; i < ns.length; i++) {
        p = p[ns[i]] = p[ns[i]] || {};
    }
};

'campsol.zachwamp'.namespace();

campsol.zachwamp.mainarea = function(options) {
    if (!options)
        throw "'options' parameter is required. (object)";

    if (!options.locationId)
        throw "'options.locationId' is required. (i.e.: mainarea)";

    if (!options.serviceBaseUrl)
        throw "'options.serviceBaseUrl' is required. (i.e.: http://server/folder/)";

    this.options.serviceBaseUrl = options.serviceBaseUrl;
    this.options.locationId = options.locationId;
    this.options.loadingId = options.loadingId ? options.loadingId : this.options.loadingId;
		this.options.baseImagePath = options.baseImagePath ? options.baseImagePath : this.options.baseImagePath;
    this.options.buttonSelectedClass = options.buttonSelectedClass ? options.buttonSelectedClass : this.options.buttonSelectedClass;
    this.options.buttonHoverClass = options.buttonHoverClass ? options.buttonHoverClass : this.options.buttonHoverClass;
    this.options.contentAnimationTime = options.contentAnimationTime ? options.contentAnimationTime : this.options.contentAnimationTime;
    this.options.buttonAnimationTime = options.buttonAnimationTime ? options.buttonAnimationTime : this.options.buttonAnimationTime;
    this.options.onerror = options.onerror ? options.onerror : this.options.onerror;
		this.options.onloadcomplete = options.onloadcomplete ? options.onloadcomplete : this.options.onloadcomplete;
		
}

campsol.zachwamp.mainarea.prototype = {
    options: {
        width: 980,
        height: 348,
        serviceBaseUrl: null,
        baseStyle: "mainarea",
        baseImagePath: "",
        locationId: null,
        loadingId: null,
        onerror: null,
        onloadcomplete: null,
        initialDelay: 200,
        contentAnimationTime: 1000,
        slideWidth: 720,
        buttonAnimationTime: 500,
        buttonTextNormalWidth: 230,
        buttonTextExpandedWidth: 250,
        rightSideStyle: "rightSideStyle",
        buttonLeftSideStyleOff: "buttonLeftSideStyleOff",
        buttonLeftSideStyleOn: "buttonLeftSideStyleOn",
        buttonRightSideStyle: "buttonRightSideStyle",
        buttonSeparatorStyle: "buttonSeparatorStyle",
        buttonSelectedClass: "buttonSelected",
        buttonHoverClass: "buttonHover"
    },
    controlData: [],
    currentIndex: -1,
    lastIndex: -1,
    isAnimating: false,
    isInitialized: false,

    imageList: [],

    initialize: function() {
        var me = this;

        // This control cannot be initialized more than once
        if (this.isInitialized) {
            alert('This control has already been initialized.');
            return;
        }

        if (this.options.loadingId != null) {
            $("#" + this.options.loadingId).css("z-index", "2000");
        }

        // Getting Data
        $.ajax({
            type: "POST",
            url: this.options.serviceBaseUrl + "mainarea.asmx/GetMainAreaData",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg, status) {
                if (status = "success") {
                    me.initialize_callback(msg.d);
                }
            },
            error: function(request, status, error) {
                if (me.options.loadingId != null) {
                    $("#" + me.options.loadingId).hide();
                }

                var msg = "";

                try {
                    var response = eval("(" + request.responseText + ")");
                    msg = "The data could not be loaded due to: " + response.Message;
                }
                catch (e) {
                    msg = "The data could not be loaded, please try again later." + request.responseText;
                }

                if (jQuery.isFunction(me.options.onerror))
                    me.options.onerror(msg);
                else
                    alert(msg);
            }
        });
    },

    initialize_callback: function(dataList) {

        var me = this;

        if (this.isInitialized) {
            alert('This control has already been initialized.');
            return;
        }

        // Building "frame"
        var location = $('#' + this.options.locationId);
        location.append(this.getFrameCode());

        // If there are not options... then finish
        if (dataList.length == 0)
            return;

        var slideFrame = $("#" + this.options.locationId + "_slideframe");
        var buttonFrame = $("#" + this.options.locationId + "_boxes");


        // For each option build its contents
        for (var i = 0; i < dataList.length; i++) {
            var content = $(this.getContentCode(this.options.locationId + "_slide" + i, dataList[i].content));
            var button = $(this.getButtonCode(this.options.locationId + "_slideBox" + i, dataList[i].buttonText));

            content.hide();
            content.css("z-index", i);
            // TODO: Activate this line.
            //content.css("background-image", "url(" + this.options.baseImagePath + dataList[i].backgroundImage + ")");

            // Button properties and method
            button[0].index = i;

            button.click(function() {
                me.clickButton(this.index);
            });

            button.mouseenter(function() {
                me.moveEnterButton(this.index);
            });

            button.mouseleave(function() {
                me.moveLeaveButton(this.index);
            });

            // New "control data"
            var node = { data: dataList[i],
                slideId: content.id,
                controlId: button.id,
                slideControl: content,
                buttonControl: button
            };

            this.controlData.push(node);

            // Adding new controls to DOM
            slideFrame.append(content);
            if (i > 0)
                buttonFrame.append(this.getButtonSeparatorCode());

            buttonFrame.append(button);
        }

        // Adjusting BOXES location
        buttonFrame.css("top", (slideFrame.height() - buttonFrame.height()) / 2 + 'px');
        buttonFrame.css("width", this.controlData[0].buttonControl.width() - this.options.buttonTextNormalWidth + this.options.buttonTextExpandedWidth + 10 + "px");

        this.isInitialized = true;

        if (this.options.onloadcomplete != null)
            this.options.onloadcomplete(this);

        if (this.options.loadingId != null) {
            $("#" + this.options.loadingId).hide();
        }

    },

    start: function() {
        var me = this;

        // If the data has not been retrieved yet and/or DOM has not been created, schedule the "start method"
        if (!this.isInitialized)
            setTimeout(function() {
                me.start();
            }, 200);
        else
            setTimeout(function() {
                me.moveEnterButton(0);
                me.clickButton(0);
            }, this.options.initialDelay);
    },

    getContentCode: function(id, content) {
        return '<div id="' + id + '" class="content" style="' +
                                                'left: ' + this.options.slideWidth + 'px; ' +
                                                'height: ' + this.options.height + 'px; ' +
                                                'width: ' + this.options.slideWidth + 'px;' +
                                                'top: 0px ' +
                        '" >' +
                    content +
               '</div>';
    },

    getButtonCode: function(id, text) {
        return '<div id="' + id + '" class="button">' +
                    '<div class="' + this.options.buttonRightSideStyle + '">' +
                        text + '</div>' +
                    '<div class="' + this.options.buttonLeftSideStyleOff + '">' +
                    '</div>' +
               '</div>';
    },

    getButtonSeparatorCode: function() {
        return '<div class="' + this.options.buttonSeparatorStyle + '">&nbsp;</div>';
    },

    getFrameCode: function() {
        return '<div class="mainarea" style="width:' + this.options.width + 'px; ' +
                                   'height:' + this.options.height + 'px; ' +
                                   '">' +
                    '<div class="' + this.options.rightSideStyle + '">' +
                    '</div>' +
                    '<div id="' + this.options.locationId + '_slideframe" class="slideframe" style="' +
                                                'width: ' + this.options.slideWidth + 'px; ' +
                                                'height: ' + this.options.height + 'px; ' +
                                                '">' +
                    '</div>' +
                    '<div id="' + this.options.locationId + '_boxes" class="boxframe" style="' +
                                           'right: 0px; top:0px; ' +
                                          '">' +
                    '</div>' +
                '</div>';

    },

    clickButton: function(index) {
        var me = this;

        // No more than 1 animation
        if (this.isAnimating)
            return;

        // Do something only if the current index is not the clicked button
        //        if (this.currentIndex == index)
        //            return;

        // If the user clicks on the "active" tab... then it loads the new link (if specified)
        if (this.currentIndex == index) {
            var data = this.controlData[index].data;
            if (data.buttonLink.trim() != "") {
                if (data.buttonLinkInNewWindow)
                    window.open(data.buttonLink);
                else
                    window.location=data.buttonLink;
            }
            return;
        }

        this.isAnimating = true;
        this.lastIndex = this.currentIndex;
        this.currentIndex = index;

        // If there was another button selected, deselect it!
        if (this.lastIndex >= 0) {
            $(this.controlData[this.lastIndex].buttonControl.children()[0]).removeClass(this.options.buttonSelectedClass);
            // Changing Button Image to OFF state
            $(this.controlData[this.lastIndex].buttonControl.children()[1]).removeClass(this.options.buttonLeftSideStyleOn);
            $(this.controlData[this.lastIndex].buttonControl.children()[1]).addClass(this.options.buttonLeftSideStyleOff);
            // Animating the button
            this.moveLeaveButton(this.lastIndex);

            // Hiding current content
            this.controlData[this.lastIndex].slideControl.hide();
        }

        // Making sure the hover class is not active
        $(this.controlData[this.currentIndex].buttonControl.children()[0]).removeClass(this.options.buttonHoverClass);
        // Assigning the selected class
        $(this.controlData[this.currentIndex].buttonControl.children()[0]).addClass(this.options.buttonSelectedClass);

        // Marking sure the current index is visible
        this.controlData[this.currentIndex].slideControl.show();
        // Increasing layer index
        this.controlData[this.currentIndex].slideControl.css("z-index", "11");

        // Changing Button Image to ON state
        $(this.controlData[this.currentIndex].buttonControl.children()[1]).removeClass(this.options.buttonLeftSideStyleOff);
        $(this.controlData[this.currentIndex].buttonControl.children()[1]).addClass(this.options.buttonLeftSideStyleOn);

        // Animating content
        this.controlData[this.currentIndex].slideControl.animate({ left: "0px" }, this.options.contentAnimationTime, 'swing', function() {
            // Reseting the last selected content
            if (me.lastIndex >= 0) {
                //me.controlData[me.lastIndex].slideControl.hide();
                me.controlData[me.lastIndex].slideControl.css("left", me.options.slideWidth + "px");
            }

            me.controlData[me.currentIndex].slideControl.css("z-index", "10");
            me.isAnimating = false;
        });
    },
    moveEnterButton: function(index) {
        if (index != this.currentIndex) {
            var item = $(this.controlData[index].buttonControl.children()[0]);

            item.stop();

            item.addClass(this.options.buttonHoverClass);
            item.animate({ width: this.options.buttonTextExpandedWidth + "px" }, this.options.buttonAnimationTime);
        }
    },
    moveLeaveButton: function(index) {
        if (index != this.currentIndex) {
            var item = $(this.controlData[index].buttonControl.children()[0]);

            item.stop();

            item.removeClass(this.options.buttonHoverClass);
            item.animate({ width: this.options.buttonTextNormalWidth + "px" }, this.options.buttonAnimationTime);
        }
    }
}