var utilities = {
    dismissAll: function ()
    {
        $('.close').trigger('click');
        $('#dismissAll').remove();
    }
}

var Favorites = {
    container: '#favorites',
    tab: '#tab',
    frameContainer: '#frame_container',
    updateContainer: 'updatePanel',

    init: function(){
        var self = this;
        self.launch();
        self.openFavorite();
        self.addFavorite();
        self.deleteFavorite();
    },

    launch: function(){
        var self = this;
        $.ajax({
            type: "POST",
            url: "/services/UserInfo.asmx/GetFavorites",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
                self.populateFavorites(result);
            }
        });

        $('#fav a').click(function(){
            $(self.container).dialog({
                width: 250,
                bgiframe: true,
                autoOpen: false,
                modal: true,
                title: 'Favorite Programs'
            })
            $(self.container).dialog('open');
            return false;
        })
    },


    populateFavorites: function(result){
        var self = this;
        if(result.length != 0){
            var list = '<ul>';
            $.each(result, function(){
                //list += '<li><a href="'+ this.URL +'" rel="' + this.Id +'">' + this.ProgramCode + '</a></li>';
                list += self.createFavorite(this.URL, this.Id, this.ProgramCode, this.Title);
            })
            list += '</ul>';
            $(self.container).append(list);
        }
        self.checkStatus();
    },

    
    refreshFavorites: function(elem){
        var self = this;
        if($('ul', self.container).length == 0){
            $(self.container).append('<ul>' + elem + '</ul>');
        }
        else{
            $('ul', self.container).append(elem);
        }
        self.checkStatus();
        $('#header').before('<div id="'+ self.updateContainer +'">A new link has been added into your favorites widget.</div>');
        $('#' + self.updateContainer).slideDown('fast', function(){
            setTimeout(function(){
                $('#' + self.updateContainer).slideUp().remove();
            }, 5000)
        })
    },

    openFavorite: function(){
        var self = this;
        $(self.container).click(function(event){
            if($(event.target).attr('nodeName').toLowerCase() == 'a'){
                var target = $(event.target);
                createTabs($(target).attr('title'), $(target).attr('href'), $(target).text());
                $(self.container).dialog('close');
                return false;
            }
        })
    },

    createFavorite: function(url, id, programCode, title){
        if(title == null){
            title = programCode;
        }
        return '<li><a href="'+ url +'" rel="' + id +'" title="' + programCode + '">' + title + '</a> <img src="http://cdn.matrixwebs.net/distribusuite/themes/default/images/icons/delete.gif" alt="" /></li>';
    },


    addFavorite: function(){
        var self = this;
        $('#addFav a').click(function(){
            var item = {};
            item.ProgramCode = $('.current a', self.tab).text();
            item.Title = $('.current a', self.tab).attr('title');
            item.URL = $('iframe:visible', self.frameContainer).attr('src');
            item.AccessKey = '';

            var bool = self.checkExistence(item.ProgramCode);
            if(bool){
                $.ajax({
                    type: "POST",
                    url: "/services/UserInfo.asmx/SaveFavorite",
                    data: "{'item':" + JSON.stringify(item) + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(result) {
                        if(result != 0){
                            var elem = self.createFavorite(item.URL, result, item.ProgramCode, item.Title);
                            self.refreshFavorites(elem);
                        }
                    }
                });
            }
            else{
                $('#header').before('<div id="'+ self.updateContainer +'">That link already exists in your favorites widget.</div>');
                $('#' + self.updateContainer).slideDown('fast', function(){
                    setTimeout(function(){
                        $('#' + self.updateContainer).slideUp().remove();
                    }, 5000)
                })
            }
            return false;
        })
    },

    deleteFavorite: function(id){
        var self = this;
        $(self.container).click(function(event){
            if($(event.target).attr('nodeName').toLowerCase() == 'img'){
                var target = $(event.target);
                var id = $(target).prev('a').attr('rel');
                
                $.ajax({
                    type: "POST",
                    url: "/services/UserInfo.asmx/DeleteFavorite",
                    data: "{'key':" + id + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(result) {
                        if(result){
                            $(target).parent('li').remove();
                            self.checkStatus();
                        }
                    }
                });
                return false;
            }
        })
    },

    checkExistence: function(programCode){
        var self = this;
        var bool = true;
        $('ul li a', self.container).each(function(){
            if($(this).attr('title').toUpperCase() == programCode.toUpperCase()){
                bool = false && bool;
            }
            else{
                bool = true && bool;
            }
        })
        return bool;
    },

    checkStatus: function(){
        var self = this;
        if($('li', self.container).length == 0){
            $('ul', self.container).hide();
            $('p', self.container).show();
        }
        else{
            $('ul', self.container).show();
            $('p', self.container).hide();
        }
    }
}


var Programs = {
    target: '#runCommand',
    button: '.execute',
    titles: [],
    urls: [],
    names: [],
    updateContainer: 'updatePanel',
    
    init: function(){
        var self = this;
        $.ajax({
            type: "POST",
            url: "/services/company.asmx/GetRunPrograms",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result){
                for(var i=0; i<result.length; i++){
                    if(result[i].Code){
                        self.titles.push(result[i].Code.toUpperCase());
                        self.urls.push(result[i].URL);
                        self.names.push(result[i].Name);
                    }
                }
                $(self.target).autocomplete(self.titles, {
                    width: 170,
                    maxItemsToShow: 4,
                    highlight: false,
                    multiple: true,
                    multipleSeparator: " ",
                    scroll: true,
                    scrollHeight: 150
                });
                self.launch();
                self.events();
            },
            error: function(xhr, status, error){
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message)
            }
        });
    },

    launch: function(){
        var self = this;
        $('#autoComplete a').click(function(){
            $('#autocompleting').dialog({
                width: 450,
                bgiframe: true,
                autoOpen: false,
                modal: true,
                title: 'Run a Program'
            })
            $('#autocompleting').dialog('open');
            return false;
        })
    },

    run: function(command){
        var self = this;
        if(command.length != 0){
            var index = $.inArray(command.toUpperCase(), self.titles);
            createTabs(command, self.urls[index], self.names[index]);
            $('.ui-dialog-titlebar-close').trigger('click');
            $(self.target).attr('value', '');
        }
    },

    events: function(){
        var self = this;
        var command;
        
        $(self.target).keydown(function(event){
            if(event.keyCode == 13){
                command = $.trim($(self.target).attr('value'));
                if(self.checkExistence(command) == -1){
                    $('#autocompleting').prepend('<ul class="information"><li>The shortcut you entered is not valid.  Please try again.</li></ul>');
                }
                else{
                    command = $.trim($(self.target).attr('value'));
                    self.run(command)
                }
            }
        })
        $(self.button).click(function(event){
            var command = $.trim($(self.target).attr('value'));
            self.run(command);
            return false;
        })
    },

    checkExistence: function(command){
        var self = this;
        var bool = $.inArray(command, self.titles);
        return bool;
        
    }
}



addLoadEvent(activateTabs);
//addLoadEvent(highlightTable);
//addLoadEvent(launchFavorites);
addLoadEvent(focusFields);
addLoadEvent(setDisabledStyle);
addLoadEvent(setDefaultInputFocus);
addLoadEvent(distributeTasks);
addLoadEvent(hidePortlet);
var currClass = "";
var globalInput = "";

function addLoadEvent(func){
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function(){
            oldonload();
            func();
        }
    }
}

function popup(url){
    GB_showFullScreen("Preview", url)
}

function removeLoaders(){
    //var loader = window.parent.getClasses("loader", "img");
    //Changed from window.parent to 2Xwindow.parent as it javascript threw error in sales analysis report
    var loader = window.parent.window.parent.getClasses("loader", "img");    
    for (var i = 0; i < loader.length; i++) {
        loader[i].parentNode.removeChild(loader[i]);
    }
}

function distributeTasks(){
    var help = getClasses("help", "a");
    for (var i = 0; i < help.length; i++) {
        help[i].onclick = function(){
            var helpWin = window.parent.window.open(this.href);
            helpWin.focus();
            return false;
        }
    }
}

function openMe(url, skip, callback){
    if(callback){
        GB_show("Preview", url, 530, 900, callback)
    }
    else{
        GB_show("Preview", url, 530, 900)
    }
}

function backToOldPosition(){
    window.parent.scrollTo(0,oldScroll);
}

function reloadPage(){
    window.location = "/orders/maintenance/incomplete/completed.aspx";
}

function activateTabs(){
    $("#section_tab a, .inner a, .multipleInner a").click(function(){
        var parent = $(this).parents('ul').attr('id');
        var clicked = $(this).attr('id');
        if(clicked == "viewall"){
            var sections = ["section_general", "section_documents", "section_statusupdates", "section_closeorder", "section_printSettings"];
            for (var j = 0; j <sections.length; j++) {
                var div = $(sections[j]);
                if (div.length > 0) {
                    $(div).addClass('shown');
                }
            }
            resizeIframe();
        }
        else{
            if(parent == "section_tab"){
                var shown_array = $('.shown','#content');
                var hidden_array = $('.hidden','#content');
                var inner_shown_array = $('.shown', '#inner');
            }
            else{
                var shown_array = $('.shown','#inner');
                var hidden_array = $('.hidden','#inner');
            }
            var section_array = new Array();
            $.each(shown_array, function(i, val){
                section_array.push(val);
            })
            $.each(hidden_array, function(i, val){
                section_array.push(val);
            })
            for (var k = 0; k <section_array.length; k++) {
                if (section_array[k].id.split("_")[1] != clicked) {
                    $(section_array[k]).attr('class','hidden');
                }
                else {
                    $(section_array[k]).attr('class','shown');
                    resizeIframe();
                }
            }//end of hiding
            if(parent == "section_tab"){
                if(inner_shown_array.length > 0){
                    $.each(inner_shown_array, function(i, val){
                        $(this).attr('class', 'shown');
                    })
                }
            }
        }
        setTabHighlight(clicked, parent);
        return false;
    })
}


function clearFocus(original){
    for (var i = 0; i < original.length; i++) {
        var classes = original[i].className.split(" ");
        var classname = "";
        for (var j = 0; j < classes.length; j++) {
            if (classes[j] != "focus") {
                classname = classes[j] + classname;
            }
        }
    }
}

function setTabHighlight(tab, parent){
    if((parent == "inactive_section_tab") || (parent == "inner_tab")){
        if($('.inner').length == 0){
            var section_tab = $('.multipleInner a');
        }
        else{
            var section_tab = $('.inner a');
        }
        
    }
    else{
        var section_tab = $('#section_tab a');
    }
    for (var i = 0; i < section_tab.length; i++) {
        if ($(section_tab[i]).attr('id') == tab) {
            $(section_tab[i]).attr('class', 'on');
        }
        else {
            $(section_tab[i]).attr('class', '');
        }
    }
}

function setActiveTab(tab){
    var section_tab = getId("section_tab");
    var section_tabs = getTag("a", section_tab);
    var shown = getClasses('shown','div');
    for(var i=0; i<shown.length; i++){
        shown[i].className = "hidden";
    }
    document.getElementById('section_' + tab).className = "shown";
	
    for (var i = 0; i < section_tabs.length; i++) {
        if (section_tabs[i].id == tab) {
            section_tabs[i].className = "on";
			
			
        }
        else {
            section_tabs[i].className = null;
        }
    }
}

function setQuery(q){
    var query = parent.document.getElementById("ctl00_RelatedPRograms_ItemQuery");
    if (query) {
        query.value = q;
    }
}

function highlightTable(){
    var tables = getClasses("display", "table");
    for (var i = 0; i < tables.length; i++) {
        var tbodies = getTag("tbody", tables[i]);
        for (var j = 0; j < tbodies.length; j++) {
            var rows = getTag("tr", tbodies[j]);
            for (var k = 0; k < rows.length; k++) {
                rows[k].onmouseover = function(){
                    if ((this.className == "alt") || (this.className == "")) {
                        this.className = "focus";
                    }
                }
                rows[k].onmouseout = function(){
                    if ((this.className == "focus") || (this.className == "alt") || (this.className == "")) {
                        this.className = null;
                    }
                }
            }
        }
    }
}

function setNewTab(id){
    var section_tab = document.getElementById("inactive_section_tab");
    if (section_tab) {
        var section_tab = section_tab.getElementsByTagName("a");
        for (var i = 0; i < section_tab.length; i++) {
            if (section_tab[i].id == id) {
                section_tab[i].className = "on";
            }
            else {
                section_tab[i].className = null;
            }
        }
    }
}

/*
function launchFavorites(){
    var favorites = getId("favorites");
    if (favorites) {
        var links = getTag("a", favorites);
        for (var i = 0; i < links.length; i++) {
            links[i].onclick = function(){
                if (this.className != "add") {
                    var title = this.getAttribute("title");
                    var programcode = this.getAttribute("programcode");
                    window.parent.createTabs(this.title, this.href, this.title);
                }
                return false;
            }
        }
    }
}
 */

function setDefaultInputFocus(){
    var focuses = $(".focus");
    if (focuses.length > 0) {
        var mainfocus = focuses[0];
        if ((mainfocus.getAttribute("readonly") == true) || (mainfocus.getAttribute("readonly") == "readonly") || (mainfocus.getAttribute("disabled") == true) || (mainfocus.getAttribute("disabled") == "disabled")) {
            $(mainfocus).removeClass("focus");
        }
        else {
            try{
                mainfocus.focus();
            }
            catch(err){
            
            }
        }
    }
}

function setDisabledStyle(){
    $("input, select, textarea").each(function(i){
    
        if (($(this).attr('disabled') == true) || ($(this).attr('readonly') == true)) {
            $(this).addClass('disabled');
        }
    })
}


function setButtonFocus(e, buttonId){
    var keynum
    if (window.event) {
        keynum = e.keyCode;
    }
    else if (e.which) {
        keynum = e.which;
    }
    
    if (keynum == 13) {
        var button = document.getElementById(buttonId);
        button.focus();
    }
}

function focusFields(){
    $("input, textarea, select").bind("focus", function(){
        $(this).addClass("focus");
    });
    
    $("input, textarea, select").bind("blur", function(){
        $(this).removeClass("focus");
    });
    
    if ($.browser.msie) {
        $("select").bind("focusin", function(){
            $(this).addClass("focus");
        });
        
        $("select").bind("focusout", function(){
            $(this).removeClass("focus");
        });
    }
}

function closeGB_Window(){
    /*var iframe = window.parent.window.parent.document.getElementsByTagName("iframe");
    if (iframe) {
        iframe = iframe[0];
    }
    var selects = window.parent.window.parent.document.getElementsByTagName("select");
    for (var i = 0; i < selects.length; i++) {
        selects[i].style.visibility = "visible";
    }
    
    var overlay = window.parent.window.parent.document.getElementById("GB_overlay");
    var windowgb = window.parent.window.parent.document.getElementById("GB_window");
    if (iframe) {
        iframe.parentNode.removeChild(iframe);
    }
    if (overlay) {
        overlay.parentNode.removeChild(overlay);
    }
    if (windowgb) {
        windowgb.parentNode.removeChild(windowgb);
    }*/


    window.parent.window.parent.GB_hide();
}

function cancelGB_Window(){
    window.parent.window.parent.location.reload();
}

function expandIt(id){
    var div = document.getElementById(id);
    var classes = getClasses(id, "tbody");
    for (var i = 0; i < classes.length; i++) {
        if (classes[i].style.display == "none") {
            classes[i].style.display = ""
        }
        else {
            classes[i].style.display = "none"
        }
    }
}

function setDefaultButton(){
//somewhere in the old code, we're still calling this function, so got to put this empty one.  Maybe the backend programmers can actually remove it so we won't have to keep this.
}

function showPopup(){
    var selects = getTag("select");
    for (var i = 0; i < selects.length; i++) {
        selects[i].style.visibility = "hidden";
    }
    var quickedit = document.getElementById("quickedit");
    var quickeditselects = getTag("select", quickedit);

    for (var i = 0; i < quickeditselects.length; i++) {
        quickeditselects[i].style.visibility = "visible";
    }
    var width = $('#quickedit').width();
    var height = $('#quickedit').height();
    var window_width = $('body').width();
    //var window_height = $(window, top.document).height();
    var window_height = window.parent.document.documentElement.clientHeight -180

    //$('body').append('<div id="overlay">&nbsp;</div>');
    $('#overlay').height($('body', top.document).get(0).scrollHeight + 'px');
    $('#overlay').css('width', window_width);
    $('#overlay', 'body').css('display', 'block');
    
    var scrollAmt = parseInt($('html', top.document).scrollTop());
    var topAmt = parseInt(((window_height - height) / 2)) + scrollAmt;
    var leftAmt = (window_width - width) / 2;
    $('#quickedit').css('left', leftAmt);
    $('#quickedit').css('top', topAmt);
    $('#quickedit').css('display', 'block');
    return false;
}


function hidePopup(){
    var quickedit = document.getElementById("quickedit");
    quickedit.style.display = "none";
    var overlay = document.getElementById("overlay");
    overlay.style.display = "none";
    var selects = getTag("select");
    
    for (var i = 0; i < selects.length; i++) {
        selects[i].style.visibility = "visible";
    }
    return false;
}

//I didn't use this function. It throws error for some reason.
function Querystring(qs){
    this.params = new Object()
    this.get = Querystring_get
    
    if (qs == null)
        qs = location.search.substring(1, location.search.length)
    
    if (qs.length == 0)
        return qs = qs.replace(/\+/g, ' ')
    var argss = qs.split('&')
    
    for (var i = 0; i < argss.length; i++) {
        var value;
        var pair = argss[i].split('=')
        var name = unescape(pair[0])
        
        if (pair.length == 2)
            value = unescape(pair[1])
        else
            value = name
        
        this.params[name] = value
        
    }
}
function Querystring_get(key, default_){
    if (default_ == null)
        default_ = null;
    
    var value = this.params[key]
    if (value == null)
        value = default_;
    return value
}
//so using the following function
function getQueryStringByName(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;}


function formatCurrency(amount){
    var i = parseFloat(amount);
    if (isNaN(i)) {
        i = 0.00;
    }
    var minus = '';
    if (i < 0) {
        minus = '-';
    }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) {
        s += '.00';
    }
    if (s.indexOf('.') == (s.length - 2)) {
        s += '0';
    }
    s = minus + s;
    return s;
}

function formatNumber(number){
    var formattedNumber;
    if (number < 10){
        formattedNumber = "00" + number;
    } else if (number < 100) {
        formattedNumber = "0" + number;
    } else {
        formattedNumber = number;
    }
    return formattedNumber;
}

function defaultKeypress(div, elem){
    $(div).keydown(function(event){
        if(event.keyCode == 13 ){
            $(elem, this).click();
            return false;
        }
    });
}

function stripNonNumeric(str){
    str += '';
    var rgx = /^\d|\.|-$/;
    var out = '';
    for(var i = 0; i < str.length; i++){
        if(rgx.test(str.charAt(i))){
            if(!((str.charAt(i) == '.' && out.indexOf( '.' ) != -1) ||
                (str.charAt(i) == '-' && out.length != 0))){
                out += str.charAt(i);
            }
        }
    }
    return out;
}

function hidePortlet(){
    $('#handle').click(function(){
        if($('#navigation').css('display') == 'none'){
            portletShow();
        }
        else{
            portletHide();
        }
        return false;
    })
}

function togglePortlet(){
    var status = getCookie('collapsed');
    if(status == null || status == 'block'){
        portletShow();
    }
    else{
        portletHide();
    }
}

function hideHandle(){
    if($('#navigation').css('display') == 'none'){
        $('#navigation').css('display', 'block');
        $('#content').css('margin-right', '200px');
        $(this).removeClass('collapsed');
        $(this).attr('title', 'Collapse the side bar');
    }
    else{
        $('#content').css('margin-right', '2px');
        $('#navigation').css('display', 'none');
        $(this).addClass('collapsed');
        $(this).attr('title', 'Expand the side bar');
    }
    $('#handle').hide();
}



function portletShow(){
    $('#navigation').css('display', 'block');
    $('#content').css('margin-right', '200px');
    $(this).removeClass('collapsed');
    $(this).attr('title', 'Collapse the side bar');
    setCookie('collapsed', 'block');
}

function portletHide(){
    $('#content').css('margin-right', '2px');
    $('#navigation').css('display', 'none');
    $(this).addClass('collapsed');
    $(this).attr('title', 'Expand the side bar');
    setCookie('collapsed', 'none');
}



Array.prototype.removeItems = function(itemsToRemove) {
    if (!/Array/.test(itemsToRemove.constructor)) {
        itemsToRemove = [ itemsToRemove ];
    }
    var j;
    for (var i = 0; i < itemsToRemove.length; i++) {
        j = 0;
        while (j < this.length) {
            if (this[j] == itemsToRemove[i]) {

                this.splice(j, 1);
            } else {
                j++;
            }
        }
    }
}

function clearPanels(){
    $('.information li').remove();
    $('.error li').remove();
    $('.information').addClass('hidden');
    $('.error').addClass('hidden');
    $('.focus').removeClass('focus');
}

function showPanel(type, message){
    clearPanels();
    $('.' + type).append('<li>' + message + '</li>');
    $('.' + type).removeClass('hidden');
    $('.' + type).get(0).scrollIntoView(true);
    resizeIframe();
}

function toggleWorkingOverlay(show) {
    if (show) {
        $('#workingOverlay').show();
    } else {
        $('#workingOverlay').hide();
    }    
}