/*----------------------------------------------------------------------------
 * JSlint, settings for the javascript code verifier jslint.com
 *
 * Run from the commandline using rhino, or:
 * 1. go to jslint.com
 * 2. click clear all options at the bottom (we define the options below)
 * 3. paste in the code
 *
 *----------------------------------------------------------------------------*/
/*jslint
 adsafe: false, // if ADsafe.org rules widget pattern should be enforced.
 bitwise: true, // if bitwise operators should not be allowed
 browser: true, // if the standard browser globals should be predefined
 cap: false, // if upper case HTML should be allowed
 newcap: false, // if Initial Caps must be used with constructor functions
 css: false, // if CSS workarounds should be tolerated
 debug: false, // if debugger statements should be allowed
 eqeqeq: true, // if === should be required
 evil: false, // if eval should be allowed
 forin: false, // if unfiltered for in statements should be allowed
 fragment: true, // if HTML fragments should be allowed
 laxbreak: true, // if statement breaks should not be checked
 nomen: false, // if names should be checked for initial underbars
 on: false, // if HTML event handlers should be allowed
 onevar: false, // if only one var statement per function should be allowed
 passfail: false, // if the scan should stop on first error
 plusplus: true, // if ++ and -- should not be allowed
 regexp: true, // if . should not be allowed in RegExp literals
 rhino: false, // if the Rhino environment globals should be predefined
 safe: false, // if the safe subset rules are enforced. These rules are used by ADsafe.
 sidebar: false, // if the Windows Sidebar Gadgets globals should be predefined
 strict: false, // if the ES3.1 "use strict"; pragma is required.
 sub: false, // if subscript notation may be used for expressions better expressed in dot notation
 undef: true, // if undefined global variables are errors
 white: false, // if strict whitespace rules apply
 widget: false // if the Yahoo Widgets globals should be predefined
 */

// JSQuery globals
/*global  $, unFocus, escape, unescape, window, ValidatorFactory, url, console, alert */

// RFQ globals
/*global  accountType, contextPath */

/**
 * Platform for RFQ All RFQ specific classes is found here
 *
 * @namespace
 * @requires jQuery
 */
var RFQ = {

    /**
     * Constants
     * @class
     */
    Constants: {
        SupplierCreateProfileContainer: 'create-tracking-profile',
        SupplierCreateProfileOk: 'create-tracking-profile-ok',
        SupplierTrackinProfileReminder: 'create-tracking-profile-reminder',
        SupplierLogoutLink: 'logoutLink'
    },

    CookieHandler: {
        /**
        * Method for creating cookie
        * @param {String} name The name of the cookie to be saved
        * @param {String} value Value of cookie to be saved
        * @param {Int} days The number of days the cookie should be saved
        **/
        createCookie: function(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        /**
        * Method for reading a cookie's value
        * @param {String} name The name of the cookie to be retrived
        * @returns {String} The value of the cookie
        **/
        readCookie: function(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i += 1) {
                var c = ca[i];
                while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
                if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); }
            }
            return null;
        },
        /**
        * Deletes cookie
        * @param {String} name The name of the cookie to be deleted
        **/
        eraseCookie: function(name) {
            this.createCookie(name, "", -1);
        },

        isCookiesEnabled: function() {
            var checkCookie = 'someCookieForCheckIfCookiesEnabled';
            RFQ.CookieHandler.createCookie(checkCookie, "1", 1);
            if (RFQ.CookieHandler.readCookie(checkCookie)) {
                RFQ.CookieHandler.eraseCookie(checkCookie);
                return true;
            } else {
                return false;
            }
        }
    },

    TopPanel :{
        loginLink : 'loginLink',
        noCookiesAlert : 'nocookies',
        init : function () {
            var loginLink = $("#" + RFQ.TopPanel.loginLink);
            if (loginLink && !RFQ.CookieHandler.isCookiesEnabled()) {
                var dlg = RFQ.Dialogs.initAlertDialog(this.noCookiesAlert);
                loginLink.click(function() {
                    RFQ.Dialogs.showDialog(dlg);
                    return false;
                });
            }
        }
    },

    Dialogs: {
        okCancelDialogPrefix : '#ok-cancel-dlg-',
        okDialogPrefix : '#ok-dlg-',

        okBtnPrefix : 'ok-btn-',
        okBtnSearchPrefix : '#ok-btn-',
        cancelBtn : "#cancel-btn-",



        hideDialog : function(/* jQuery */ dlg) {
            if(!RFQ.ElementEffects.isMsie) {
                dlg.fadeOut();
            } else {
                dlg.hide();
            }
        },

        showDialog : function(/* jQuery */ dlg) {
            if(!RFQ.ElementEffects.isMsie) {
                dlg.fadeIn();
            } else {
                dlg.show();
            }
        },

        /* Adds standard dialogs elements and styles */
        initInfoDialog : function(/* jQuery */ dlg) {

            dlg.addClass("standard-dialog");

            if(dlg.find('.top').length == 0) {
                dlg.prepend("<div class='top'></div>");
            }

            if(dlg.find('.top a.close').length == 0) {
                dlg.find('.top').append("<a class='close' href='#'></a>");
            }

            if(dlg.find('.bot').length == 0) {
                dlg.append("<div class='bot'></div>");
            }

            return dlg;
        },

        showInfoDialog : function(/* jQuery */ dlg) {

            this.initInfoDialog(dlg);
            this.showDialog(dlg);
        },

        initAlertDialog : function(name) {
            var dlg = $(this.okDialogPrefix + name);

            dlg.find(this.okBtnSearchPrefix + name).click(function() {
				RFQ.Dialogs.hideDialog(dlg);
			});

            RFQ.ElementEffects.initDialog(dlg);
            return dlg;
        },


        initOkCancelDialog : function(name, trigger, onOk) {

            var dlg = $(this.okCancelDialogPrefix + name);
            var okBtn = dlg.find(this.okBtnSearchPrefix + name);
            var cancelBtn = dlg.find(this.cancelBtn + name);

            okBtn.click(onOk);
            cancelBtn.click(function (){
                RFQ.Dialogs.hideDialog(dlg);
                return false;
            });

            trigger.click(function() {
                RFQ.Dialogs.showDialog(dlg);
                return false;
            });

            RFQ.ElementEffects.initDialog(dlg);
        }
    },

    /**
     * Class for handling all element effects, like folding/unfolding, highlighting element etc.
     * @class
     */
    ElementEffects: {
        isMsie: false,

        /**
         * Init function
         */
        init: function() {
            if ($.browser.msie && $.browser.version.substr(0,1)<8) {
                this.isMsie = true;
            }
            // Initialize all info messages to show after page is loaded
            $('.show-info-msg').each(function() {
                RFQ.Dialogs.showInfoDialog($(this));
            });
            // Initialize all dialogs
            $('.standard-dialog, div.inline-overlay-box').each(function() {
                RFQ.ElementEffects.initDialog($(this));
            });
        },

        /**
         * Toggle dialog
         * @param {jQuery} targetDialog jQuery wrapper to toggle
         */
        toggleDialog: function(targetDialog) {

            $('.standard-dialog, .inline-overlay-box').hide();

            if(targetDialog.is(':hidden')) {
                RFQ.Dialogs.showDialog(targetDialog);
            } else {
                RFQ.Dialogs.hideDialog(targetDialog);
            }

            return false;
        },

        /**
         * Dialog initialization.
         * Defines a close button handler.
         * @param {jQuery} targetDialog jQuery wrapper to initialize
         */
        initDialog: function(targetDialog) {

            targetDialog.find('.top a, p.close a, a.close').click(function() {
                if(!this.isMsie) {
                    $(this).parents('.standard-dialog:eq(0), .inline-overlay-box:eq(0)').fadeOut();
                } else {
                    $(this).parents('.standard-dialog:eq(0), .inline-overlay-box:eq(0)').hide();
                }
                return false;
            });
        }
    },

    /**
     * Handler for supplier login support.
     * @class
     **/
    SupplierLoginSupport: {

        init: function() {
            this.initReminder();
            $('#' + RFQ.Constants.SupplierCreateProfileOk).click(RFQ.SupplierLoginSupport.initOkButton);
            $('#' + RFQ.Constants.SupplierLogoutLink).click(RFQ.SupplierLoginSupport.logoutClick);
        },

        initReminder: function() {
            if (accountType == 'EMPTY_PROFILE_SUPPLIER') {
                var targetDialog = $('#' + RFQ.Constants.SupplierCreateProfileContainer);
                if (targetDialog) {
                    var cookie = RFQ.CookieHandler.readCookie(RFQ.Constants.SupplierTrackinProfileReminder);
                    if (!cookie) {
                        RFQ.ElementEffects.toggleDialog(targetDialog);
                        RFQ.CookieHandler.createCookie(RFQ.Constants.SupplierTrackinProfileReminder, 'true', 1);
                    }
                }
            }
        },

        initOkButton: function() {
            var targetDialog = $('#' + RFQ.Constants.SupplierCreateProfileContainer);
            targetDialog.fadeOut();
        },

        logoutClick: function() {
            RFQ.CookieHandler.eraseCookie(RFQ.Constants.SupplierTrackinProfileReminder);
        }
    },

    /**
     * Handler for consumer request
     * @class
     **/
    ConsumerRequest: {

        categoryId: "categoryId",
        subCategoryId: "subCategoryId",
        areaId: "areaId",
        subAreaId: "subAreaId",
        deactiveId: "deactiveLink",
        backButton: "backButton",
        confirmDlgId: "deactivate",
        openAnswerId: "openAnswerForm",

        init: function() {
            this.initSubCategoryDrop();
            this.initSubAreaDrop();

            //$('#' + this.backButton).click(RFQ.ConsumerRequest.backOnClick);
            RFQ.Dialogs.initOkCancelDialog(RFQ.ConsumerRequest.confirmDlgId,
                    $('#' + this.deactiveId),
                    RFQ.ConsumerRequest.deactiveOnClick);
            $('#' + this.openAnswerId).click(RFQ.ConsumerRequest.openAnswerOnClick);
        },

        /**
         * check max answered when click by openAnswerForm link
         */
        openAnswerOnClick: function() {
            var href = $('#' + RFQ.ConsumerRequest.openAnswerId).attr("href").toString();
            $.ajax({
                url: href,
                async: false,
                success: function(resp) {
                    // if answer-form no then jqeury.html(redirect)
                    if ($(resp).find('#answer-form').length == 0) {
                        $('#main-content').html($(resp).find('#main-content')[0]);
                    }
                }
            });
        },

        /**
         * Active or Deactive consumer request
         */
        deactiveOnClick: function() {
            var href = $('#' + RFQ.ConsumerRequest.deactiveId).attr("href").toString();

            $('#main-content').load(href + ' #main-content', callback);
            function callback() {
                RFQ.Dialogs.initOkCancelDialog(RFQ.ConsumerRequest.confirmDlgId,
                                               $('#' + RFQ.ConsumerRequest.deactiveId),
                                               RFQ.ConsumerRequest.deactiveOnClick);
            }
            return false;
        },

        /**
         * Back
         */
        backOnClick: function() {
            if (history.length > 1) {
                history.back();
            } else {
                document.location = contextPath + "/";
            }
            return false;
        },

        /**
         * Set listener for category combo-box
         */
        initSubCategoryDrop: function() {
            var selectId = '#create-user-account ' + '#' + RFQ.ConsumerRequest.categoryId;
            $(selectId).change(function() {
                var subSelectId = '#create-user-account ' + '#' + RFQ.ConsumerRequest.subCategoryId;
                var selectedValue = $(selectId).val();
                var url = contextPath + '/references/subCategoryOption?categoryId=' + selectedValue;

                if (selectedValue == '') {
                    $(subSelectId).attr('disabled', 'disabled');
                    $(subSelectId + " option:first-child").attr("selected", "selected");
                } else {
                    $(subSelectId).removeAttr('disabled');
                    var extraOption = $(subSelectId + " option:first-child").text(); // Get text for extra option
                    $(subSelectId).html('<option value="">' + extraOption + '</option>');
                    $.get(url , function(data) {
                                        $(subSelectId).append(data);
                                });
                }
                return false;
            });
        },

        /**
         * Set listener for area combo-box
         */
        initSubAreaDrop: function() {
            var selectId = '#create-user-account ' + '#' + RFQ.ConsumerRequest.areaId;
            $(selectId).change(function() {
                var subSelectId = '#create-user-account ' + '#' + RFQ.ConsumerRequest.subAreaId;
                var selectedValue = $(selectId).val();
                var url = contextPath + '/references/subAreaOptionList';

                if (selectedValue == '') {
                    $(subSelectId).attr('disabled', 'disabled');
                    $(subSelectId + " option:first-child").attr("selected", "selected");
                } else {
                    $(subSelectId).removeAttr('disabled');
                    var extraOption = $(subSelectId + " option:first-child").text(); // Get text for extra option
                    $(subSelectId).html('<option value="">' + extraOption + '</option>');
                    $.post(url , {areaId : selectedValue}, function(data) {
                                        $(subSelectId).append(data);
                                });
                }
                return false;
            });
        }
    },

    /**
     * Handler for search request functionality
     * @class
     **/
    SearchRequests: {

        categoryId: "categoryIdFilter",
        subCategoryId: "subCategoryIdFilter",
        areaId: "areaIdFilter",
        subAreaId: "subAreaIdFilter",

        init: function() {
            this.initSubCategoryDrop();
            this.initSubAreaDrop();
        },

        /**
         * Set listener for category combo-box
         */
        initSubCategoryDrop: function() {
            var selectId = '#search-filter #' + RFQ.SearchRequests.categoryId;

            RFQ.SearchRequests.loadSubCategories(selectId);

            $(selectId).change(function() {
                RFQ.SearchRequests.loadSubCategories(selectId);
            });
        },

        /**
         * Load sub categories
         */
        loadSubCategories: function(selectId) {
            var subSelectId = '#search-filter #' + RFQ.SearchRequests.subCategoryId;
            var extraOption = $(subSelectId + " option:first-child").text(); // Get text for extra option
            if ($(selectId).val() !== undefined) {
                var url = contextPath + '/references/subCategoryOption?categoryId=' + $(selectId).val();
                $(subSelectId).html('<option value="">' + extraOption + '</option>');
                $.get(url , function(data) {
                                $(subSelectId).append(data);
                            });
            }
            return false;
        },

        /**
         * Set listener for area combo-box
         */
        initSubAreaDrop: function() {
            var selectId = '#search-filter #' + RFQ.SearchRequests.areaId;
            RFQ.SearchRequests.loadSubAreas(selectId);

            $(selectId).change(function() {
                RFQ.SearchRequests.loadSubAreas(selectId);
            });
        },

        /**
         * Load sub areas
         */
        loadSubAreas: function(selectId) {
            var subSelectId = '#search-filter #' + RFQ.SearchRequests.subAreaId;
            var extraOption = $(subSelectId + " option:first-child").text(); // Get text for extra option
            var url = contextPath + '/references/subAreaOptionList';
            $(subSelectId).html('<option value="">' + extraOption + '</option>');
            $.post(url , {areaId : $(selectId).val()}, function(data) {
                             $(subSelectId).append(data);
                         });
            return false;
        }
    },

    /**
     * Handler for no supplier logout functionality
     * @class
     **/
    NoSupplierLogout: {

        init: function() {
            // Loads the logout page => logging out user
            if($("#noSupplierLogout").length && $("#noSupplierLogoutChecker").length == 0) {
                var url = contextPath + '/j_spring_security_logout';
                $("#noSupplierLogout").load(url);
            }
        }
    },

    /**
     * Handler for consumer request
     * @class
     **/
    Util: {

        /**
         * Modify URL with custom param
         */
        getModifyURL: function(param, value) {
            var url = document.location.toString();

            if (url.indexOf(param) > -1) {
                var startPos = url.indexOf(param);
                var endPos;

                var endPice = url.substring(startPos, url.length);
                if ((endPos = endPice.indexOf("&")) == -1) {
                    url = url.substring(0, startPos) + param + '=' + value;
                } else {
                    url = url.substring(0, startPos) +
                          url.substring(startPos + endPos + 1, url.length) + '&' +
                          param + '=' + value;
                }
            } else {
                url += '&' + param + '=' + value;
            }
            return url;
        }
    },

    /**
     * Handler for admin
     * @class
     **/
    Admin: {

        loginLink : 'adminLoginLink',
        noCookiesAlert : 'nocookies',

        init: function() {
            if($('form#downloadRequestForm a.datepicker').length) {
                $('form#downloadRequestForm input[class="text date-pick"]').datepicker({minDate: null});
            }
	    var loginLink = $("#" + RFQ.Admin.loginLink);
            if (loginLink && !RFQ.CookieHandler.isCookiesEnabled()) {
                var dlg = RFQ.Dialogs.initAlertDialog(this.noCookiesAlert);
                loginLink.click(function() {
                    RFQ.Dialogs.showDialog(dlg);
                    return false;
                });
            }
        }
    },
    General: function(){

        var isMsie = $.browser.msie;

        $('a.in-new-window').live("click", function(e){
            e.preventDefault();
            window.open($(e.target).attr('href'));
        });

        $('a.back-link').live("click", function(e){
            e.preventDefault();
            history.back();
        });

        $('.expand-box').live("click", function(){

            var targetElement = $('#' + $(this).metadata().targetElement);

            if($(targetElement).is(":hidden")) {
                $(targetElement).slideDown();
            } else {
                $(targetElement).slideUp();
            }
            
            return false;
        });
        
        $('.open-dialog').toggle(function()
        {
            var targetDialog = $(this).metadata().targetDialog;

            $('.standard-dialog, .inline-overlay-box').hide();

            RFQ.ElementEffects.initDialog($(targetDialog));

            if(!isMsie) {
                $('#' + targetDialog).fadeIn();
            } else {
                $('#' + targetDialog).show();
            }
            
         }, function() {

            var targetDialog = $(this).metadata().targetDialog;
            if(!isMsie) {
                $('#' + targetDialog).fadeOut();
            } else {
                $('#' + targetDialog).hide();
            }
            
        });

        /**
         * element can used to open/close specified DOM element (dialog), having this class.
         * E.g. <sometag class="show-dialog {targetDialog: 'some-dialog-id'}" />
         * By clicking this link dialog will became shown/hidden depending of its current state.
         */
        $('.show-dialog').click(function() {

            var targetDialog = $('#' + $(this).metadata().targetDialog);

            RFQ.ElementEffects.initDialog($(targetDialog));

            //hide all other boxes when clicked
            $('.standard-dialog, .inline-overlay-box').hide();

            if(!isMsie) {
                $(targetDialog).fadeIn();
            } else {
                $(targetDialog).show();
            }
            
            return false;
        });

        if($("a.datepicker.").length > 0) {
            $('#startDate').attr('readonly', true).end().datepicker();

            $("#ui-datepicker-div").hide();
            
            $(".ui-widget-content").css("border","1px solid #aaa");

            $('form a.datepicker').click(function(e)
            {
                $('#startDate').focus();
                e.preventDefault();
            });
        }

        if($("#recent-requests").length > 0) {
            $("#recent-requests").find("li > p").expander({
                slicePoint: 200,
                expandText: '',
                userCollapseText: ''
            });
        }

        
        $('table.answers a.expand-td').click(function()
        {
            var targetElement = $('#' + $(this).metadata().targetElement);
            if($(targetElement).is(":hidden")) {
              if(isMsie) {
                  $(targetElement).css('display', 'block');
              } else {
                  $(targetElement).css('display', 'table-cell');
              }
            } else {
              $(targetElement).hide();
            }

            $(this).toggleClass('btn-contract');

            return false;
        });

        if($('form#downloadRequestForm a.datepicker').length > 0) {
            $('form#downloadRequestForm a#endPicker').click(function(e)
            {
                $('#endDate').focus();
                e.preventDefault();
            });
        }

        $("table#big-recent-requests tbody tr.tr-link").click(function(e)
        {
            e.preventDefault();
            window.location.href = $(this).metadata().url;
        });

        //dd menu
        $("#top-menu ul.nav > li ").hover(function(){
            $(this).find("ul.sub").slideDown('fast');

        }, function() {
            $(this).find("ul.sub").slideUp('fast');
        });

        //delay function for messages (tracking profile)
        $.fn.pause = function(duration) {
            $(this).animate({ dummy: 1 }, duration);
            return this;
        };

        if($(".tracking-status-ok").length) {
            $(".tracking-status-ok").fadeIn().pause(1500).fadeOut(500);
        }
    },
    StartPage: function() {
        //Start page category selector
        if($("#category_select").length) {
            var wrapper = $("#category_select"),
                catWrapper = wrapper.find("> div:not('.no-crop')"),
                catLists = catWrapper.find("ul"),
                rowHeight = catLists.find("li:first-child").height(),
                showHeight = Math.abs(rowHeight*5),
                animSpeed = 500,
                animateHeight = function(wrapper) {

                    var list = wrapper.find("ul"),
                        amount = list.find("li").length;


                    if (wrapper.hasClass("cropped")) {

                        wrapper.stop().animate({
                            //backgroundColor: '#efefef',
                            height: list.height()
                        }, animSpeed, function() {
                            wrapper
                                .removeClass("cropped")
                                .addClass("expanded")
                                .siblings("a.showAll")
                                .addClass("expanded")
                                .find(".show").hide()
                                .siblings(".hide").show();
                        });

                    } else {
                        wrapper.stop().animate({
                            //backgroundColor: '#fff',
                            height: showHeight
                        }, animSpeed, function() {
                            wrapper
                                .addClass("cropped")
                                .removeClass("expanded")
                                .siblings("a.showAll")
                                .removeClass("expanded")
                                .find(".hide").hide()
                                .siblings(".show").show();
                        });
                    }
                };

            $.each(catLists, function(){
                if ($(this).find("li").length > 5) {
                    $(this).parents(".listWrapper").css({
                        'height': showHeight
                    }).addClass("cropped").siblings("a.showAll").fadeIn(500);
                }
            });

            //bind live event to "show all"-click
            wrapper.find(".showAll").bind("click", function(e) {
                e.preventDefault();
                var listWrapper = $(this).siblings(".listWrapper");
                animateHeight(listWrapper);
            });
        }
    },
    /**
     * Method for initializing RFQ java-script
     * @class
     */
    Init: function() {
        var bodyId = document.getElementsByTagName("body")[0].id;

        switch (bodyId) {
            case "startpage":
                RFQ.StartPage();
                break;
        }

        RFQ.ElementEffects.init();
        RFQ.General();
        RFQ.SupplierLoginSupport.init();
        RFQ.ConsumerRequest.init();
        RFQ.SearchRequests.init();
        RFQ.TopPanel.init();
        RFQ.NoSupplierLogout.init();
        RFQ.Admin.init();

        // init logging
        $.log = function(message) {
            if(window.console) {
                console.debug(message);
            } else {
                alert(message);
            }
        };
    }
};

//add listener to dom tree
$(document).ready(RFQ.Init);
