/*global jQuery*/

(function (window) {
    "use strict";
    var $ = window.jQuery,
		model,
		view,
		isIE = jQuery.browser.msie && parseInt(jQuery.browser.version, 10) <= 8,
        document = window.document;

    view = {
        init: function () {
            $(window).load(function () {
                if ($('.featured').length) {
                    $('.featured a').css('display', 'inline');
                    //                    $('#featured').orbit({
                    //                        'bullets': true,
                    //                        'timer': true,
                    //                        'animation': 'horizontal-slide'
                    //                    });
                    $('.featured').each(function () {
                        $(this).orbit({
                            'bullets': true,
                            'timer': true,
                            'animation': 'horizontal-slide'
                        });
                    });
                }
            });
        },

        misc: {
            init: function init() {
                view.misc.c33FixForIE();
                view.misc.scriptReady();
                view.misc.showNavInfoWin();
                view.misc.imageChooser();
                view.misc.addSearchEventToButton();
                var elems = {}, me = {}, type = '';

                // wrapBoxInLink
                if ($('#contents ul.wrapInA').length) { me = $('#contents ul.wrapInA'), type = 'ul'; view.misc.wrapBoxInLink(me, type) }; // eg. download & support
                if ($('#contents li.wrapInA').length) { me = $('#contents li.wrapInA'), type = 'li'; view.misc.wrapBoxInLink(me, type) };

                // equalHeights Sitemap
                if ($('#sitemap').length) { elems = $('#sitemap > ul > li'); view.misc.equalHeights(elems); }

                // equalHeights Product list on Products
                setTimeout(function () {
                    if ($('#eqHeightJS ul.largeList').length) { elems = $('#eqHeightJS ul.largeList > li'); view.misc.equalHeights(elems); }
                }, 500);

                // equalHeights AreaStartpage two boxes next to imageslider
                if ($('#areaIndex div.eqHeight').length) { elems = $('#areaIndex div.eqHeight > ul'); view.misc.equalHeights(elems); }

                // equalHeights AreaStartpage 'threeboxes'
                if ($('#threeBoxes').length) { elems = $('#threeBoxes div.eqHeight'); view.misc.equalHeights(elems); }
            },

            /* Attach the search event to the right button, without this is only reloads the page when pressing enter at the search page */
            addSearchEventToButton: function addSearchEventToButton() {
                $('#search fieldset input').focus(function () {
                    $('body').keypress(function (e) {
                        if (e.keyCode == '13') {
                            e.preventDefault();
                            $('#search fieldset button').trigger('click');
                        }
                    });
                });
                $('.searchArea input').focus(function () {
                    $('body').keypress(function (e) {
                        if (e.keyCode == '13') {
                            e.preventDefault();
                            $('.searchArea button').trigger('click');
                        }
                    });
                });
            },

            /* Wrap the whole box with the one link so everything is clickable */
            wrapBoxInLink: function wrapBoxInLink(elem, type) {
                var toWrap = elem,
                    l = elem.length, le = 0, j = 0, i = 0, theLink = [], href = '', img = [], ea = {}, target = '';

                if (type === 'ul') {
                    for (i = 0; i < l; i += 1) {
                        theLink = $(toWrap[i]).children().children().children('a.theLink');
                        le = theLink.length;

                        if (theLink.length) {
                            for (j = 0; j < le; j += 1) {
                                href = $(theLink[j]).attr('href');
                                target = $(theLink[j]).attr('target');

                                if (target.length) {
                                    $(theLink[j]).parents('div').parents('li').wrap('<a class="newLink" target="_blank" href="' + href + '" />');
                                    $(theLink[j]).children().unwrap();
                                } else {
                                    $(toWrap[i]).children('li').wrap('<a class="newLink" href="' + href + '" />');
                                    theLink.remove();
                                }
                            }
                        }
                    }
                } else if (type === 'li') {
                    for (i = 0; i < l; i += 1) {
                        theLink = $(toWrap[i]).children('a.theLink');
                        href = theLink.attr('href'),
                        target = theLink.attr('target');

                        if (theLink.length && target.length) {
                            $(toWrap[i]).wrapInner('<a class="newLink" target="_blank" href="' + href + '" />');
                        } else if (theLink.length) {
                            $(toWrap[i]).wrapInner('<a class="newLink" href="' + href + '" />');
                        }
                    }
                }
            },

            c33FixForIE: function c33FixForIE() {
                if (isIE) {
                    $('#contents table.tech-spec tr:even td').css('background-color', '#f6f6f7');
                    $('#contents ul.features-list li:odd img').css({ 'float': 'right', 'margin': '0 0 0 20px' });
                }
            },

            /* Run all Javascript before showing the page content */
            scriptReady: function scriptReady() {
                setTimeout(function () {
                    $("body").addClass("ready");
                }, 100);
            },

            /* Show info popup for Main Menu and Footer menu when hovering. Also calculates the position so it is centered above/under the link. */
            showNavInfoWin: function showNavInfoWin() {
                function navHover(link, infowin) {
                    link.mouseover(function () {
                        infowin.hide();
                        var w = $(this).width() / 2, // 256px is the static width of the infowin, / 2 it equals 128px
                            pos = '-' + (128 - w + 'px'); // 128 - half of its parent's, the li's width, is the new left-position
                        $(this).children('div').css({ 'left': pos }).show();
                    });

                    link.mouseout(function () {
                        infowin.hide();
                    });
                }

                var topLink = $('#nav li'),
                    topInfowin = $('#nav li > div'),
                    footerLink = $('#footer nav li'),
                    fotterInfowin = $('#footer nav li > div');

                navHover(topLink, topInfowin);
                navHover(footerLink, fotterInfowin);
            },

            /* Click a thumbnail to see the larger version above. You'll find it in ProductOverview.aspx */
            imageChooser: function imageChooser() {
                $('#thumbs a').click(function (e) {
                    e.preventDefault();
                    var theHref = $(this).attr('href'),
                        bigImg = $('#image-chooser > img');
                    bigImg.attr('src', theHref);
                    $('#thumbs a').removeClass('active');
                    $(this).addClass('active');
                });
            },

            /* Set equal height on boxes; take the heighest value and append to all */
            equalHeights: function equalHeights(elem) {
                var tallest = 0, // Delclare outside loop 
                    thisHeight = 0; // Delclare outside loop

                elem.each(function () {
                    tallest = 0;
                    elem.each(function () {
                        thisHeight = $(this).height();
                        if (thisHeight > tallest) {
                            tallest = thisHeight;
                        }
                    });

                    // If in iFrame(EPiServer), elements doesn't get height right away, so let's try it again.                        
                    if (tallest > 0) {
                        //alert("if");
                        elem.height(tallest).delay(10000);
                        //elem.height(tallest);
                    } else {
                        //alert("else");
                        setTimeout(view.equalHeights, 10000);
                    }
                });
            }
        },

        splashPage: {
            init: function inti() {
                if ($('#splash-content').length) {
                    //                    if (document.evaluate) {
                    //                        var container = document.getElementById("docWrap");
                    //                        var xPathRes = document.evaluate('span[@MLB_idSpanFlag]', container, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                    //                        if (xPathRes.snapshotLength == null || xPathRes.snapshotLength <= 0) {
                    //                            view.splashPage.ifNoJS();
                    //                        }
                    //                        alert(xPathRes.snapshotLength);
                    //                    }
                    view.splashPage.toggleTextInBoxes();
                    view.splashPage.toggleInfoInNav();
                    view.splashPage.mouseOverforNavLi();
                    view.splashPage.ifNoJS();
                }
            },

            /* Wrap the whole inside of the box in the a tag, and toggle hidden text and nav on click */
            toggleTextInBoxes: function toggleTextInBoxes() {


                $('#splash-content div.wrapInA').each(function () {
                    if ($(this).attr('data-href') !== undefined) {
                        $(this).wrapInner('<a class="tehLink" href="' + $(this).attr('data-href') + '" />');
                    } else {
                        $(this).wrapInner('<a class="theLink" href="#" />');
                    }
                });


                function step1(me) {
                    me.children('div.toggle').hide();
                    me.children('div.hidden').show();
                    me.children('div.toggle').unwrap(); // remove the A so the new A-tags will work properly
                }

                function step2(me) {
                    me.parent('div.hidden').hide();
                    me.parent('div.hidden').siblings('div.toggle').show();
                    me.parents('div.wrapInA').wrapInner('<a class="theLink" href="#" />'); // wrap the box again with the A tag
                }

                $('#splash-content a.theLink').live('click', function (e) {
                    e.preventDefault();
                    var me = $(this);
                    step1(me);
                });

                $('#splash-content a.cheekyJS').live('click', function (e) {
                    e.preventDefault();
                    var me = $(this);
                    step2(me);
                });
            },

            /* Toggle the text in bottom nav on mouseover */
            toggleInfoInNav: function toggleInfoInNav() {
                $('#flip-list li').mouseover(function () {
                    $(this).children('a.une').hide();
                    $(this).children('a.deux').show();
                });

                $('#flip-list li').mouseout(function () {
                    $(this).children('a.deux').hide();
                    $(this).children('a.une').show();
                });
            },

            mouseOverforNavLi: function mouseOverforNavLi() {
                $('#flip-list li').mouseover(function () {
                    $(this).addClass('hover');
                });

                $('#flip-list li').mouseout(function () {
                    $(this).removeClass('hover');
                });
            },

            /* If JS is on, hide div.hidden and show div.toggle */
            ifNoJS: function ifNoJS() {
                $('#splash-content div.hidden').hide();
                $('#splash-content div.toggle').show();
            }

        },

        /**
        * Function for loading YouTube video in new layer @ Training page
        */
        video: {
            init: function init() {
                view.video.trigOverlay();
            },

            createHTML4Popup: function createHTML4Popup(url) {
                var html =
                    '<a href="javascript:void(0);" id="close-overlay"><img src="/ui/images/x.png" alt="X" /></a>' +
                    '<div id="movie">' +
                        '<object width="720" height="400">' +
                            '<param name="movie" value="' + url + '"></param>' +
                            '<param name="allowFullScreen" value="true"></param>' +
                            '<param name="allowscriptaccess" value="always"></param>' +
                            '<embed src="' + url + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="720" height="400"></embed>' +
                        '</object>' +
                    '</div>';

                return html;
            },

            createPopup: function createPopup(url) {
                var popupWidth = 750, // width of popup
                    popupHeight = 450, // width of popup
                    scrollTop = $(window).scrollTop(),
				    theLeft = ($(window).width() / 2) - (popupWidth / 2) + 'px', // hor center align on page                    
				    theTop = (popupHeight > ($(window).height() - 20)) ? (10 + scrollTop) + "px" : (($(window).height() / 2) - (popupHeight / 2) + scrollTop) + "px", // vert center align on page
                    html = view.video.createHTML4Popup(url);

                $('body').prepend('<div id="video-popup"></div>');
                $('#video-popup').css({ 'left': theLeft, 'top': theTop }).append(html);
            },

            hideOverlay: function hideOverlay() {
                $('#video-popup').remove();
                $('#p-overlay').remove();
            },

            removeOverlay: function removeOverlay() {
                $('#p-overlay, #close-overlay').click(function () {
                    view.video.hideOverlay();
                });
            },

            printOverlay: function printOverlay(url) {
                $('body').prepend('<div id="p-overlay"></div>');
                $('#p-overlay').css('height', ($(document).height() * 1.05));
                $('#p-overlay').css('opacity', 0).fadeTo('medium', 0.5);

                view.video.createPopup(url);
                view.video.removeOverlay();
            },

            trigOverlay: function trigOverlay() {
                $('#videos a.open-overlay').click(function (e) {
                    e.preventDefault();
                    var url = $(this).siblings('input.embed-url').val();
                    view.video.printOverlay(url);
                });
            }
        }
    };

    /**
    * Handle Ajax request against ClientScriptService
    * @class
    */
    model = {
        /**
        * Handles the response from jQuery ajax object
        * @param {Array} data	JSON data loaded from server.
        * @param {String} queued	ID of current queue, cloud also be bool False it no queue is used.
        */
        handleResponse: function (data, queueId) {
            if (data.d.ResponseStatus !== 200) {
                this.handleError(data.d.ResponseMessage);
                return false;
            }

            if (!queueId && this.queue.tmpCallback) {
                this.queue.tmpCallback(data.d.ResponseData[0].Value);
            } else if (queueId) {
                var i = 0,
                    l = data.d.ResponseData.length,
					x;

                for (x in this.queue[queueId]) {
                    if (this.queue[queueId][x]) {
                        for (i = 0; i < l; i += 1) {
                            if (data.d.ResponseData[i].CommandName.toLowerCase() === x.toLowerCase() && this.queue[queueId][x].callback) {
                                this.queue[queueId][x].callback(data.d.ResponseData[i].Value);
                            }
                        }
                    }
                }

                model.resetQueue(queueId);
            }
        },
        /**
        * Holds queue objects. Each queue should have a unique name and contains properties with correspondant names of the name of webservice to be called.
        * Value of "WebServiceMethod" should always be false
        * @example queue1 : { WebServiceMethod : false }
        * @property
        */
        queue: {
            queue1: {
                GetTwitter: false,
                GetFriends: false
            },

            queue2: {
                AddAccount: false,
                AddSubscriber: false
            }
        },
        /**
        * Add new Queue Item to que based on queueId. If que is full. Trigger the JSON request. ie. 
        * @example model.addToQueue('que1', ['AddStuff', { name: 'stuff' }], view.removeStuff)
        * 
        * @param {String} queueId	ID of current queue, cloud also be bool False it no queue is used.
        * @param {Array} payload	Array containg Webservie name and arguments ie. ['DoStuff',  { name : 'lorem ipsum' }]
        * @param {Function} callback	Callback method, can be false if no callback is requierd 
        */
        addToQueue: function (queueId, payload, callback) {
            var queuePayload,
				i,
				queueObj = { Name: payload[0], Params: [] };

            for (i in payload[1]) {
                if (i in payload[1]) {
                    queueObj.Params.push({ Name: i, Value: payload[1][i] });
                }
            }

            if (!queueId) {
                this.queue.tmpCallback = callback;

                this.addToAjaxQueue({ request: { Commands: [queueObj]} }, false);
                return;
            } else if (this.queue[queueId][payload[0]]) {
                return false;
            }

            if (typeof this.queue[queueId] === 'undefined' || typeof this.queue[queueId][payload[0]] === 'undefined') {
                this.handleError('No queueId with the name ' + queueId + ' or the queItem ' + payload[0] + ' is not in the queue ' + queueId);
            }

            this.queue[queueId][payload[0]] = {};
            this.queue[queueId][payload[0]].payload = queueObj;
            this.queue[queueId][payload[0]].callback = callback;

            if (this.isQueueReady(queueId)) {
                queuePayload = this.getQueuePayload(queueId);
                this.addToAjaxQueue(queuePayload, queueId);
            }
        },
        /**
        * Check if queue is ready to be triggered.
        * @param {String} queueId	ID of current queue.
        * @return {Boolean}	Returns true if queue is ready.
        */
        isQueReady: function (queueId) {
            var isReady = true,
				i;

            for (i in this.queue[queueId]) {
                if (!this.queue[queueId][i]) {
                    isReady = false;
                    break;
                }
            }

            return isReady;
        },
        /**
        * Get current queues payload as and Array.
        * @param {String} queueId	ID of current queue.
        * @return {Array}	Payload array with main webservice methods as first argument.
        */
        getQueuePayload: function (queueId) {
            var payloadArray = [],
				i;

            for (i in this.queue[queueId]) {
                if (this.queue[queueId][i]) {
                    payloadArray.push(this.queue[queueId][i].payload);
                }
            }

            return { request: { Commands: payloadArray} };
        },
        /**
        * Resets the queue of current queueId.
        * @param {String} queueId	ID of current queue.
        */
        resetQueue: function (queueId) {
            var i;
            for (i in this.queue[queueId]) {
                if (this.queue[queueId][i]) {
                    this.queue[queueId][i] = false;
                }
            }
        },
        /**
        * Setup ajax properties for new ajax request.
        * @param {Array} payload	Array to be posted to webservice.
        * @param {String} queueId	ID of current queue.
        */
        addToAjaxQueue: function (payload, queueId) {
            var ajaxOptions = {
                url: '/ScriptServices/ClientDataTransferService.asmx/GetData',
                type: 'post',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(payload),
                callback: queueId,
                success: function (data) {
                    var arg = [data, this.callback];
                    model.handleResponse.apply(model, arg);
                },
                error: model.handleError
            };

            this.doJsonPost(ajaxOptions);
        },
        /**
        * Array to hold currently running ajax requests
        * @property
        */
        ajaxQueue: [],

        /**
        * Triggers jQuery's ajax method and triggers handleResponse method passing loaded data and queId.
        * Uses this.ajaxQueue queue to keep ajax request to be invoked in proper order.
        * @param {Object} ajaxOptions Object containing properties of ajax request.
        */
        doJsonPost: function (ajaxOptions) {
            var ajaxQueueItem,
                ajaxCall = (function (ajaxOptions, obj) { //Return anonymouse function to keep context of ajaxOpotions and obj.
                    return function () {
                        var onSuccess = ajaxOptions.success,
                            ajaxQueue = obj.ajaxQueue;
                        // Override succuess function in ajaxOptions to add logic for handling ajaxQueue
                        ajaxOptions.success = function () {
                            if (onSuccess) {
                                onSuccess.apply(obj, arguments);
                            }

                            ajaxQueue.shift();

                            if (ajaxQueue.length > 0) {
                                ajaxQueueItem = obj.ajaxQueue[0];
                                ajaxQueueItem();
                            }
                        };
                        $.ajax(ajaxOptions);
                    };
                } (ajaxOptions, this));
            //Add new Ajax call to queue
            this.ajaxQueue.push(ajaxCall);
            //If ajax queue is empty or contain only a singel call, invoke it.
            if (this.ajaxQueue.length <= 1) {
                ajaxQueueItem = this.ajaxQueue[0];
                ajaxQueueItem();
            }
        },
        /**
        * Throws error from jQuery ajax method.
        */
        handleError: function (err) {
            throw new Error(err);
        }
    };

    $.extend({ view: view });

    $(document).ready(function () {
        $.runInit($.view);

        /* Check if Mouseless Browsing add-on is enabled. If so, change CSS */
        checkMouselessBrowsing();

        /* Enable global search on 'Enter' */
        if ($.browser.msie) {
            $('.searchArea input').focus(function () {
                $(this).bind('keyup', function (e) {
                    var code = e.keyCode || e.which;
                    if (code == 13) {
                        $('.searchArea button').click();
                    }
                });
            });

            $('.searchArea input').blur(function () {
                $(this).unbind();
            });
        }
        /* End */

    });

} (window));



function checkMouselessBrowsing() {
    var message = "";
    if (document.evaluate) {
        var container = document.getElementById("contents");
        var xPathRes = document.evaluate('//span[@mlb_idspanflag]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        if (xPathRes.snapshotLength != null && xPathRes.snapshotLength > 0) {
            setActiveStyleSheet("globalAlt")
            $('.toggle').hide();
            $('.hidden').show();
        }
        else {
            if ($('.new-design').length > 0) {
                setActiveStyleSheet("globalNewDesign")
            }
            else {
                setActiveStyleSheet("global")
            }
        }
    }
    else {
        if ($('.new-design').length > 0) {
            setActiveStyleSheet("globalNewDesign")
        }
        else {
            setActiveStyleSheet("global")
        }
    }
}

function setActiveStyleSheet(title) {
    var i, a, main;
    for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
            a.disabled = true;
            if (a.getAttribute("title") == title) a.disabled = false;
        }
    }
}
