var LoadReady = {
    makeScrollableTable: function(){
        var toSubtract1 = $('#header').outerHeight(true) + $('#nav').outerHeight(true) + $('#nav2').outerHeight(true) + $('#extended').outerHeight(true) + $('#footer').outerHeight(true);
        var toSubtract2 = parseInt($('#main').css('padding-top')) + parseInt($('#main').css('padding-bottom'));
        var toSubtract3 = parseInt($('#col3_content').css('padding-top')) + parseInt($('#col3_content').css('padding-bottom'));
        var toSubtract4 = parseInt($('#main .page').css('padding-top')) + parseInt($('#main .page').css('padding-bottom'));
        var mainPanelHt = $(window).height() - toSubtract1 - toSubtract2 - toSubtract3 - toSubtract4 - 20;
        $('.contentScroller').css({'height' : mainPanelHt + 'px', overflow: 'auto', 'overflow-x': 'hidden'});
        $('#col1').css({'height' : mainPanelHt + 'px', overflow: 'auto', 'overflow-x': 'hidden'});
    },

    showHideRightPanels: function(){
        var toggleBtn = $('div.toggle').click(function(){
            var parent = $(this).closest('.linkPortalWrapper');
            var container = $('.mediaFilesDisplayWrap, .linkPortalDataWrapper', parent);

            $(this).css('background', 'transparent');
            $(this)
            .removeClass('plus, minus')
            .addClass(
                (!container.is(':hidden')) ? 'plus' :
                'minus');

            $('.mediaFilesDisplayWrap, .linkPortalDataWrapper', parent).toggle('fast');
        });

        //*** for initial hide. if the section is hidden by default
        $('div.header[expanded=0]').each(function(){
            var parent = $(this).closest('.linkPortalWrapper');
            $('.mediaFilesDisplayWrap, .linkPortalDataWrapper', parent).hide();
        });

        $('div.header[expanded=0] div.toggle')
        .removeClass('plus, minus').addClass('plus');
    },

    setupLinks: function () {
        $(function() {
            $('a.editLink').livequery('click', function (e) {

                var chooseLinkValidateJsMethod = $(this).attr('chooseLinkValidateJsMethod');
                var result = true;
                if (chooseLinkValidateJsMethod) {
                    chooseLinkValidateJsMethod = eval(chooseLinkValidateJsMethod);
                    var recId = $(this).attr('recId');
                    var exp = {
                        'recId': recId
                    };
                    result = chooseLinkValidateJsMethod.call(this, exp);

                }
                if (result) {
                    Links.showEditLinkDialog.call(this, e);
                }
            });

            $('a.newPortalRecord, a.editPortalRecord').live('click', function (e){
                var editLinkItemValidateJsMethod = $(this).attr('editLinkItemValidateJsMethod');
                var result = true;
                if (editLinkItemValidateJsMethod) {
                    editLinkItemValidateJsMethod = eval(editLinkItemValidateJsMethod);
                    var recId = $(this).attr('recId');
                    var exp = {
                        'recId': recId
                    };
                    result = editLinkItemValidateJsMethod.call(this, exp);

                }
                if (result) {
                    Links.showNewEditPortalForm.call(this, e);
                }
            });

            $('a.newGridRecord').live('click', function (e){
                Links.addNewGridRecord.call(this, e);
            });

            $('a.viewPortalRecord').live('click', Links.showDetailPortalForm);

            $('a.deletePortalRecord').live('click', function(e) {
                Links.deletePortalRecord.call(this, e);
            });

            $('a.editLinkSingle').live('click', function (e) {
                e.preventDefault();
                Util.openDialogForLink.call(this, 'Edit Link',  600, $(window).height()-100, 1);
            });


            $('#linkModalOuter a.addToLinked').live('click', function(e) {
                e.preventDefault();
                Links.addToLinked.call(this);
            });

            $('#linkModalOuter a#addAll').live('click', function(e) {
                e.preventDefault();
                Links.addAll.call(this);
            });

            $('#linkModalOuter a#addRemoveAll').live('click', function(e) {
                e.preventDefault();
                Links.addRemoveAll.call(this);
            });

            $('#linkModalOuter a.removeFromLinked').live('click', function(e) {
                e.preventDefault();
                Links.removeFromLinked.call(this);
            });

            $('#linkModalOuter a.btnSort, #linkModalOuter .pagelinks a').live('click', function(e) {
                e.preventDefault();
                Links.loadDataFromUrl.call(this);
            });

            $('#linkModalOuter a.btnSort, #linkModalOuter .pagelinks a').live('click', function(e) {
                e.preventDefault();
                Links.loadDataFromUrl.call(this);
            });

            $('input.setSingleValue').live('click', function(){
                Links.setSingleValue.call(this);
            });

            $('#linkModalOuter form#searchNotLinked').livequery(function(){
                Links.searchNotLinked.call(this);
            });

            $('#linkModalOuter form#searchLinked').livequery(function(){
                Links.searchLinked.call(this);
            });

            $(".portalSearch select").livequery('change', function() {
                var linkName = $(this).closest('.linkPortalWrapper').attr('id');
                var linkNameActual = $(this).closest('.linkPortalWrapper').attr('lnkRoomActual');
                Links.reloadPortalRecords(linkName, linkNameActual)
            });

            $('.linkPortalDataWrapper .grid input,'  +
              '.linkPortalDataWrapper .grid select,' +
              '.linkPortalDataWrapper .grid textarea').live('change', function(e) {
                e.preventDefault();
                Links.updateGridData.call(this);
            });
        });
    }
}

/******/
$(function() {

    var masterPathAlias = $('#masterPathAlias').val();
    var masterRootPathAlias = $('#masterRootPathAlias').val();

    $("#ui-datepicker-div")
    .livequery(function() {
        $("#ui-datepicker-div").addClass("ui-datepicker-zindex");
    });

    $(".hlist li:last-child")
    .livequery(function() {
        $(this).addClass('last');
    });

    $(".hlist li:first-child")
    .livequery(function() {
        $(this).addClass('first');
    });

    $(".vlist li:last-child")
    .livequery(function() {
        $(this).addClass('last');
    });

    $(".vlist li:first-child")
    .livequery(function() {
        $(this).addClass('first');
    });

    $(".linkPortalWrapper tr td:first, .linkPortalWrapper tr th:first")
    .livequery(function() {
        //$(this).css('border-left', 0);
    });

    $("form#searchTop select").livequery('change', function() {
        $('#searchTop').submit();
    });

    $("form#searchTop").submit(function(e) {
        Util.clearPrepopulatedTextbox($(this));
        return true;
    });

    var dateObj = new Date();
    var currentYear = dateObj.getFullYear() + 1;
    $(".fld_date").livequery(function(){
        yearStart = $(this).attr('yearStart');
        yearEnd  = $(this).attr('yearEnd');
        
        if (!yearStart){
            yearStart = currentYear - 10;
        }
        
        if (!yearEnd){
            yearEnd = currentYear;
        }

        $(this).datepicker({
            showOn: 'button',
            buttonImage: masterRootPathAlias + 'common/images/icons/calendar_icon.gif',
            dateFormat: 'yy-mm-dd',
            buttonImageOnly: true,
            changeYear: true,
            yearRange: yearStart + ':' + yearEnd
        })
        .focus(function(){
            var allowEdit = $(this).attr('allowEdit');
            if (!allowEdit && allowEdit != 1){
                $(this).blur();
            } else {
                 this.select();
            }
        });

        $('#ui-datepicker-div').draggable();
    });

    $(".fld_time").livequery(function(){
        $(this).timepicker({
        	timeFormat: 'hh:mm:ss'
        })
    });

    $("#actBtn_cancelNew").livequery('click', function(e) {
        e.preventDefault();
        Actions.cancelNew()
    });

    $("#actBtn_addNew").livequery('click', function(e) {
        e.preventDefault();
        Actions.addNew();
    });

    $("#actBtn_save").livequery('click', function(e) {
        e.preventDefault();
        Actions.save();
    });

    $("#actBtn_cancel").livequery('click', function(e) {
        e.preventDefault();
        Actions.cancelEdit();
    });

    $("input#actBtn_edit").livequery('click', function(e) {
        e.preventDefault();
        Actions.edit.call(this);
    });

    $("#actBtn_changePassword").livequery('click', function(e) {
        e.preventDefault();
        Actions.changePassword.call(this);
    });

    $(".yform").livequery('click', function() {
        Util.expose($(this).parent());
    });

    $("form#frmKeyword").livequery('click', function() {
        Util.expose($(this));
    });

    if ($('.yform.detail').length > 0){
        $('fieldset').each(function(){
            var lastDiv = $('div:last', $(this));

            if (lastDiv.hasClass('type-check')){
                lastParent = lastDiv.closest('.form-row-wrapper');
            } else {
                lastParent = lastDiv.parent();
            }

            lastParent.css('border-bottom', '1px solid #ddd');
        });
    }

    $('.yform.detail .openLink').hide();
    $('.yform .actBtnsInNewForm').show();

    //Auto grow for text area
    if( $.fn.elastic) {
        $("textarea").livequery(function(){
            $(this).elastic();
        });
    }

    $("a.editFromList").livequery('click', function (e){
        var title = $(this).attr('dialogTitle');

        e.preventDefault();
        var expObj = {
            validate: true,
            callbackOnSuccess: function(){
                document.location = document.location;
            }
        }
        Util.openFormInDialog.call(this, 'portalForm', title, 400, 300, expObj);
    });

    $('.cp_ckeditor').livequery(function(){
        includeStylesheet = $(this).attr('includeStylesheet');
        stylesheetPath = $(this).attr('stylesheetPath');
        var jssPath = $('#jssPath').val();

        var fldId = $(this).attr('id');

        var instance = CKEDITOR.instances[fldId];
        if(instance){
            CKEDITOR.remove(instance);
        }

        if ($('#cpScope').val() == 'www'){
            toolbar = Util.getCKEditorToolBarsLite();
        } else {
            toolbar = Util.getCKEditorToolBarsFull();
        }

        $(this).ckeditor(function() {
        },
        {
            toolbar : toolbar,
            bodyClass: 'cpCkEdiorBody',
            filebrowserBrowseUrl : jssPath + 'ckfinder/ckfinder.html',
            filebrowserImageBrowseUrl: jssPath + 'ckfinder/ckfinder.html?Type=Images',
            filebrowserFlashBrowseUrl: jssPath + 'ckfinder/ckfinder.html?Type=Flash',
            filebrowserUploadUrl: jssPath + 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
            filebrowserImageUploadUrl: jssPath + 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
            filebrowserFlashUploadUrl: jssPath + 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
        })

        var editor = $(this).ckeditorGet();
        if (includeStylesheet){
            editor.config.contentsCss = stylesheetPath;
        }

        //editor.config.baseHref = 'http://www.example.com/path/';

    });

    if($.browser.msie && $.browser.version=="6.0"){
        Util.showIE6RejectMessage();
    }
});

/***
 * Pacth for dialog-fix ckeditor problem [ by ticket #4727 ]
 * 	http://dev.jqueryui.com/ticket/4727
 */

$(function() {
    $.extend($.ui.dialog.overlay, { create: function(dialog){
    	if (this.instances.length === 0) {
    		// prevent use of anchors and inputs
    		// we use a setTimeout in case the overlay is created from an
    		// event that we're going to be cancelling (see #2804)
    		setTimeout(function() {
    			// handle $(el).dialog().dialog('close') (see #4065)
    			if ($.ui.dialog.overlay.instances.length) {
    				$(document).bind($.ui.dialog.overlay.events, function(event) {
    					var parentDialog = $(event.target).parents('.ui-dialog');
    					if (parentDialog.length > 0) {
    						var parentDialogZIndex = parentDialog.css('zIndex') || 0;
    						return parentDialogZIndex > $.ui.dialog.overlay.maxZ;
    					}

    					var aboveOverlay = false;
    					$(event.target).parents().each(function() {
    						var currentZ = $(this).css('zIndex') || 0;
    						if (currentZ > $.ui.dialog.overlay.maxZ) {
    							aboveOverlay = true;
    							return;
    						}
    					});

    					return aboveOverlay;
    				});
    			}
    		}, 1);

    		// allow closing by pressing the escape key
    		$(document).bind('keydown.dialog-overlay', function(event) {
    			(dialog.options.closeOnEscape && event.keyCode
    					&& event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
    		});

    		// handle window resize
    		$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
    	}

    	var $el = $('<div></div>').appendTo(document.body)
    		.addClass('ui-widget-overlay').css({
    		width: this.width(),
    		height: this.height()
    	});

    	(dialog.options.stackfix && $.fn.stackfix && $el.stackfix());

    	this.instances.push($el);
    	return $el;
    }});

    $('a.jqui-dialog').live('click', function(e) {
        e.preventDefault();
        var title = $(this).attr('title');
        var width = $(this).attr('dlg-w');
        var height = $(this).attr('dlg-h');
        Util.openDialogForLink.call(this, title, width, height);
    });

    $('a.jqui-dialog-form').live('click', function(e) {
        e.preventDefault();
        var title = $(this).attr('title');
        var formName = $(this).attr('formId');
        if (!formName) {
            formName = $(this).attr('formid');
        }
        var w = $(this).attr('w');
        var h = $(this).attr('h');
        Util.openFormInDialog.call(this, formName, title, w, h);
    });

    if ($('form.cpJqForm').length > 0){
        $('form.cpJqForm').livequery(function() {
            var formId = $(this).attr('id');
            Util.setUpAjaxFormGeneral(formId);
    	});
    }

    if ($('form.cpUploadifyForm').length > 0){
        $('form.cpUploadifyForm').livequery(function() {
            var formId = $(this).attr('id');
            Util.setUpFormWithUploadify(formId);
    	});
    }

    $('form[autoSubmitOnChange=1] select').change(function(){
        Util.showProgressInd();
        $(this).closest('form').submit();
        Util.hideProgressInd();
    });

    $('a.cpBack').click(function(){
        history.back();
    });

    $('a.cpPrint').click(function(){
        window.print();
    });

    $.extend($.ui.dialog.prototype, {
        'addbutton': function(buttonName, func) {
            var buttons = this.element.dialog('option', 'buttons');
            buttons[buttonName] = func;
            this.element.dialog('option', 'buttons', buttons);
        }
    });

    $.extend($.ui.dialog.prototype, {
        'removebutton': function(buttonName) {
            var buttons = this.element.dialog('option', 'buttons');
            delete buttons[buttonName];
            this.element.dialog('option', 'buttons', buttons);
        }
    });

    $('div.cpwLoading').livequery(function(){
        $('div.cpwLoading > div').show();
        $('div.cpwLoading').removeClass('cpwLoading');
    });

    Util.prepopulatedTextbox();

});

/* @projectDescription jQuery Serialize Anything - Serialize anything (and not just forms!)
 * @author Bramus! (Bram Van Damme)
 * @version 1.0
 * @website: http://www.bram.us/
 * @license : BSD
*/
(function($) {
$.fn.serializeAnything = function() {
    var toReturn = [];
    var els   = $(this).find(':input').get();
    $.each(els, function() {
        if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
            var val = $(this).val();
            toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
        }
    });
    return toReturn.join("&").replace(/%20/g, "+");
}
})(jQuery);

