/**
 * farshid:
 * add the navigation function to window object in firefox
 * we are calling this native IE function: window.navigate in
 * many places in our code.
 * TODO: replace all calls to navigate function with:
 * window.location.href or we can use a proxy funcion like
 * "rayGoto" presented here to make further improvements
 * easier.
 */
try {
   navigate;
} catch(e) {
    navigate = function(url){window.location.href = url;};
};
/**
 * farshid:
 * TODO: add all functions of this type to a jQuery plugin
 * for code encapsulation
 */
function rayGoto(url) {
    try {
        window.top.location.href = url;
    } catch (e) {
        window.location.href = url;
    }
}

function rayPopup(url, options) {

}

/**
 * From jQuery docs:
 * Many JavaScript libraries use $ as a function or variable name, just as jQuery does.
 * In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $.
 * If we need to use another JavaScript library alongside jQuery, we can return control of $ back to 
 * the other library with a call to $.noConflict():
 */
jQuery.noConflict();

(function(jQuery) {
jQuery.widget("ui.combobox", {
_create: function() {
var self = this;
var select = this.element.hide();
var input = jQuery("<input>")
.insertAfter(select)
.autocomplete({
source: function(request, response) {
var matcher = new RegExp(request.term, "i");
response(select.children("option").map(function() {
var text = jQuery(this).text();
if (!request.term || matcher.test(text))
return {
id: jQuery(this).val(),
label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
value: text
};
}));
},
delay: 0,
select: function(e, ui) {
if (!ui.item) {
// remove invalid value, as it didn't match anything
jQuery(this).val("");
return false;
}
jQuery(this).focus();
select.val(ui.item.id);
self._trigger("selected", null, {
item: select.find("[value='" + ui.item.id + "']")
});
							
},
minLength: 0
})
.addClass("ui-widget ui-widget-content ui-corner-left");
jQuery("<button>&nbsp;</button>")
.insertAfter(input)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
}).removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.position({
my: "left center",
at: "right center",
of: input,
offset: "-1 0"
}).css("top", "")
.click(function() {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
}
});

})(jQuery);
		
/**
* Fall into DOM ready:
*/
jQuery(document).ready(function() {
    //jQuery("select").combobox();
    /**
    * farshid:
    * TODO: replace DD_roundies with jQuery.corner plugin as it seems to be 
    * more reliable.
    */
    //DD_roundies.addRule('#tooltip','5px');
    DD_roundies.addRule('.paging_elem', '5px');
    DD_roundies.addRule('.round5px', '5px');
    DD_roundies.addRule('#message_preview', '0 0 8px 8px');
    DD_roundies.addRule('#message_preview_body', '5px');

    /**
    * farshid:
    * I do not remmember why I add this! :)
    * think for some design related resons
    * TODO: may be I remove this at all.
    */
    /*
    jQuery('div#menu > ul > li > a').addClass('levelonea');
    jQuery('div#menu > ul > li').find('ul > li:first').addClass('fli');
    jQuery('div#menu > ul > li').find('ul > li:last').addClass('lli');
    */

    /**
    * farshid:
    * added this to te winndow resize, as in some pages after page resize
    * things went wrong.
    * @see: fix_page_title_pos function
    */
    jQuery(window).bind('resize', fix_page_title_pos);
    fix_page_title_pos();

    /**
    * farshid:
    * fixOverflow was used to work around the ie problem in rendering
    * pages with both vertical and horizental scrolle, the problem is this:
    * the scrill width/height in IE will be counted in the scrilled element 
    * width/height.
    */
    jQuery('#contentmain').fixOverflow();

    /**
    * farshid:
    * adding FormNavigate. this will notify user, leaving a page with a dirty form
    * we do not need this on login page so the 'not' filter was added.
    */
    /**
    * I have reomeved this for now, should be added later, but now we will call this 
    * on a per page demand.
    jQuery("form").not('[action="Login.aspx"]').each(function(i,item){
    jQuery(item).FormNavigate("ترک کردن این صفحه باعث از بین رفتن تغییرات شما خواهد شد");
    });
    */

    /**
    * farshid:
    * start right content from 0 pos where there are no right icons:
    */
    if (jQuery('#righticons').length == 0) {
        jQuery('#right_content_top').css('top', 0);
    }

    /**
    * farshid:
    * here we can bind/set keyboard shortcuts.
    * in this form:
    * jQuery(document).bind('keydown', 'short cut key', 
    * function (evt){ do stuff here; return false if we want the key, do not take it's defualt action; });
    */
    jQuery(document).bind('keydown', 'Ctrl+x', function(evt) { jQuery('#right_handle').click(); evt.stopPropagation(); return false; });

    /**
    * setting handlers for right pan, click the 'right_handle' div to
    * collaps/show right area, some animation is added, I do not know 
    * if this is good... or what?
    */
    jQuery('#right_handle').toggle(
	        function() {
	            /*
	            jQuery('#right_content').hide();
	            jQuery('#right').css('width','7px');
	            jQuery('#content').css('right','7px');
	            jQuery('#right_handle').css('right','0').addClass('right-handle-inner-closed');
	            */
	            //jQuery('#content').css('right','7px');
	            jQuery('#content').animate({ right: 7 }, 300);
	            jQuery('#right_handle').animate({ right: 0 }, 300, function() {
	                jQuery(this).addClass('right-handle-inner-closed');
	            });
	            jQuery('#right').animate({ width: 7 }, 300);
	        },
	        function() {
	            //jQuery('#right_content').show();
	            //jQuery('#right').css('width','230px');
	            //jQuery('#content').css('right','230px');
	            //jQuery('#right_handle').css('right','223px').removeClass('right-handle-inner-closed');
	            jQuery('#content').animate({ right: 230 }, 300);
	            jQuery('#right_handle').animate({ right: 223 }, 300, function() {
	                jQuery(this).removeClass('right-handle-inner-closed');
	            });
	            jQuery('#right').animate({ width: 230 }, 300);
	        });
    /**
    * adding tooltip functionality to top icons
    */
    /*
    jQuery('.top-icon > a[title]').tooltip({ tip: '#tooltip',
    position: 'bottom center'
    });
    */
    //jQuery('.top-icon > a[title]').simpletip({ fixed: true, content: jQuery(this).attr('title') });
    ////jQuery('.top-icon > a[title]').each(function(index,item) {
    ////    jQuery(item).parent().simpletip({ fixed: true, position:'top', content: jQuery(item).attr('title') });
    ////});
    //$(document).ready(function() {
    simple_tooltip(".top-icon > a[title], .right-icon > a[title]", "tooltip");
    //simple_tooltip(".right-icon > a[title]", "tooltip");
    //jQuery('.top-icon > a[title]').each(function(index, item) {
    //    simple_tooltip(item, 'tip_'+index);
    //});
    //});
    /**
    * handle modals if any
    * TODO: replace this with jQuery UI dialog.
    */
    if (jQuery('#modal') && jQuery('#modal')['length'] > 0) {
        alert('a');
        isEmpty = (jQuery('div.modal-content:empty')['length'] > 0);
        if (!isEmpty) {
            jQuery('#modal').overlay({ expose: {
                color: '#000',
                loadspeed: 10,
                opacity: .7
            },
                closeOnClick: false,
                api: true,
                effect: 'default',
                top: '5%'
            }).load();
        };
    };

    /**
    * on some pages (currently only: the letter view page) we have items in
    * the right pan, holding extra information, here we are setting handlers
    * for those functionality
    */
    right_items = jQuery('.appcontainer-nomenu-rightpan .handle-item');
    if (right_items && right_items['length'] > 0) {
        jQuery('.handle-item-hidden').css('opacity', .95).click(function(e) {
            e.stopPropagation();
        });
        right_items.click(function(e) {
            id = '#' + jQuery(this).attr('rel');
            if (jQuery(id).css('display') == 'none') {
                jQuery('.handle-item-hidden').hide();
                jQuery('.handle-item').css('width', '221px');
                jQuery(id).show();
                if (document.getElementById('DynamicWebTwain1') != null)
                    document.getElementById('DynamicWebTwain1').height = '265';
                jQuery(this).css('width', '222px');
            } else {
                jQuery(id).hide();
                if (document.getElementById('DynamicWebTwain1') != null)
                    document.getElementById('DynamicWebTwain1').height = '1200';
                jQuery(this).css('width', '221px');
            }
            e.stopPropagation();
            return false;
        });
        jQuery('body').click(function(e) {
            jQuery('.handle-item-hidden').hide();
            if (document.getElementById('DynamicWebTwain1') != null)
                document.getElementById('DynamicWebTwain1').height = '1200';
            jQuery('.handle-item').css('width', '221px');
        });
    };

    /**
    * login watermark handing
    */
    login_username = jQuery('input.username');
    login_password = jQuery('input.password');
    if ((login_username && login_username['length'] > 0) && (login_password && login_password['length'] > 0)) {
        //alert(login_username.val());
        (login_username.val() != '') ? removeWaterMark(login_username) : '';
        (login_password.val() != '') ? removeWaterMark(login_password) : '';
        login_username.focus(function(e) {
            removeWaterMark(login_username);
        });
        login_password.focus(function(e) {
            removeWaterMark(login_password);
        });
        login_username.blur(function(e) {
            (login_username.val() != '') ? removeWaterMark(login_username) : addWaterMark(login_username, 'username');
        });
        login_password.blur(function(e) {
            (login_password.val() != '') ? removeWaterMark(login_password) : addWaterMark(login_password, 'password');
        });
    };
    /**
    * login help btn
    */
    /*
    $("#login_help_content").dialog({
    autoOpen: false,
    modal: true,
    height: 500,
    width: 800,
    resizabel: true
    });
    */
    jQuery('#login_help_btn').click(function() {
        jQuery("#login_help_content").html('<iframe id="login_help_content_iframe" width="100%" height="100%" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" />').dialog({
            modal: true,
            height: 500,
            width: 800,
            title: 'راهنمای تنظیم مرورگر'
        });
        jQuery("#login_help_content_iframe").attr("src", "./Help/help.aspx");
    });
    simple_tooltip("#login_help_btn", "tooltip");

    /**
    * farshid
    * init the menus, I am putting this in a try/catch, cuase in some pages
    * we do not have any menu containers (remmember we have different master pages)
    * so in some cases this script generates errors.
    * TODO: choce another strategy for this so that e can remove the try/catch
    */
    try {
        jQuery('#menu').html(Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetMenuItems().value).find('a').fadeTo(0, .96);
        jQuery('#menu').raymenu();
        currentIndexRes = Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetSelectedNodeIndex();
        jQuery('#user_name').text(Rayvarz.OfficeAutomation.Web.TopLeftBar.SetData().value.UserName);
        jQuery('#dateShow').text(Rayvarz.OfficeAutomation.Web.TopLeftBar.SetData().value.DateShow);
    } catch (e) {
    }
    reloadTreeMenu();
    /**
    * farshid
    * set up ray_autocomplete functionality on elements with 'autocomp' class
    * TODO: replace this with an extended version of jQuery UI ray_autocomplete
    * widget, currently this approach is not generic enugh to be used every where
    */
    jQuery.each(jQuery('.autocomp'), function(i, el) {
        jQuery(el).ray_autocomplete({ onSelect: ray_autocomplete_selected, deferRequestBy: 400 });
    });
    jQuery.each(jQuery('.autocomp-showAll'), function(i, el) {
        jQuery(el).click(function() {
            var autoObj = jQuery(".autocomp[rel='" + el.rel + "']").get(0).AutoCompObject;
            autoObj.el.focus();
            autoObj.getSuggestions("");
        })
    }
    );

    /*try {
        var startNode = jQuery(".tree-item-selected");
        var pageTitle = //String.fromCharCode(8237) + 
            startNode.text();
        startNode = startNode.parent().parent();
        while (startNode.attr("class").toLowerCase() != "right_tree") {
            startNode = startNode.parent();
            pageTitle = startNode.children('a').text() + " > " + pageTitle;
            startNode = startNode.parent();
        }
        jQuery(document).attr("title", pageTitle);
    }
    catch (e) {
    }*/
    /**
    * farshid
    * Set display to none if there is an element with visibility st to hidden
    */
    /*
    Alireza: 
    
    Caused some problems. the existing scripts change 'visibility' to 'visible' but 
    the control's 'display' remains 'none' and the item is still invisible
    
    
    */
    /*
    var hiddens = jQuery('*').filter(function() {
    return (jQuery(this).css('visibility') == 'hidden');
    });
    hiddens.css('display', 'none');*/
});


/**
* farshid:
* Work around for title problem in pages with long page titles
* as customers demand, we should show all the title, no mater 
* how big it is. the problem was: as the page title is floated
* it would not push next childrens of page down, so some conflicts
* would occur. this is the work around:
*/
function fix_page_title_pos(){
    var pag_title = jQuery('.page-title', '#topicons');
    pag_title.width(jQuery('#topicons').width() - jQuery('#topiconswrap').outerWidth(true) - 15);
    if (pag_title.outerHeight() > jQuery('#topicons').height()) {
        jQuery('#contentmain').css('margin-top', (pag_title.outerHeight() - jQuery('#topicons').height()) + 'px');
    };
}

/**
 * farshid:
 * function to build page tree presented in the right pan
 */
function buildTree(elem){
    jQuery('#right_content_top ul:first li:first').addClass('first-tree-li');
    elem = elem ? elem : jQuery('#right_content_top ul:first');
    elem.find('li:last').addClass('last-tree-li');
    elem.find('li').each(function(index,item){
        var jItem = jQuery(item);
        var uls = jItem.find('ul');
        if(uls['length'] > 0){
            jQuery(uls).hide();
            treeIcon = jItem.find('div.tree-icon:first');
            treeIcon.addClass('tree-icon-p');
            treeIcon.click(function(){
                innerUl = jQuery(this).parent().find('ul:first');
                NodeIndex = jQuery(this).attr('rel');
                if(innerUl['length'] > 0){
                    if(innerUl.css('display') == 'none'){
                        if(innerUl.find('li')['length'] == 0){
                             var res = Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetChildNodesData(NodeIndex);
                             if(res.value == null){jQuery(this).removeClass('tree-icon-m').removeClass('tree-icon-p'); return;}
                             out = '';
                             jQuery.each(res.value,function(itemIntdex,item){
                             var hasImage = true;
                             out += '<li><div class="tree-icon" rel="' + item.NodeIndex + '"></div><div class="tree-image' + (hasImage ? '' : ' tree-image-empty') + '"><img src="' + item.ImageUrl + '" /></div><a href="' + item.Href + '">' + item.Title + '</a>';
                                if(item.HasChildNodes){
                                    out += '<ul></ul>';
                                }
                                out += '</li>';
                                innerUl.append(out);
                                out = '';
                             });
                             buildTree(innerUl);
                        }
                     innerUl.show('fast');
                     jQuery(this).removeClass('tree-icon-p').addClass('tree-icon-m');
                    }else{
                     innerUl.hide('fast');
                     jQuery(this).removeClass('tree-icon-m').addClass('tree-icon-p');
                    }
                }
            });
        }
        });
}

/**
 * gets the right tree roots and load the proper item.
 * @param force Boolean: removes generated elements and forces
 * to reload items from aserver.
 */
function getTreeMenuRoots(force){
    var res = Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetMainNodesData();
    jQuery.each(res.value,function(itemIntdex,item){
        handleItem = '<div class="handle-item"><a href="#" rel="'+item.NodeIndex+'">'+item.Title+'</a></div>';
        jQuery('#right_content_handles').append(handleItem);
    });
    jQuery('#right_content_handles').css('height',32*res.value.length);
    jQuery('#right_content_top').css('bottom',32*res.value.length);
    
	var right_content_handles = jQuery('#right_content_handles > .handle-item');
	if(right_content_handles && right_content_handles['length'] > 0){
	    right_content_handles.click(function(e) {
	        jQuery('.handle-item').removeClass('handle-item-selected');
	        jQuery(this).addClass('handle-item-selected');
	        itemIndex = jQuery(this).find('a:first').attr('rel');
	        var ulID = '#right_tree_' + itemIndex;
	        var menuID = '#menu_' + itemIndex;
	        if (force) {
	            jQuery(ulID).remove();
	        }
	        if (jQuery(ulID).size() == 0) {
	            var res = Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetChildNodesData(itemIndex);
	            if (res.error == null) {
	                out = '<ul id="right_tree_' + itemIndex + '" class="right_tree">';
	                jQuery.each(res.value, function(itemIntdex, item) {
	                    var hasImage = !(item.ImageUrl == "" || item.ImageUrl == null);
	                    out += '<li><div class="tree-icon" rel="' + item.NodeIndex + '"></div><div class="tree-image' + (hasImage ? '' : ' tree-image-empty') + '"><img src="' + item.ImageUrl + '" /></div><a href="' + item.Href + '">' + item.Title + '</a>';
	                    if (item.HasChildNodes) {
	                        out += '<ul></ul>';
	                    }
	                    out += '</li>';
	                });
	                out += '</ul>';
	                jQuery('#right_content_top ul.right_tree').css('display', 'none');
	                jQuery('#right_content_top').prepend(out);
	                buildTree();
	            }
	        } else {
	            jQuery('#right_content_top ul.right_tree').css('display', 'none');
	            jQuery(ulID).css('display', 'block');
	            //buildTree();
	        }
	        
	        var mainIndex = currentIndexRes.value.split('.')[0];
	        disableContentMainhandler( (mainIndex != itemIndex) , mainIndex );
	        
	        /**
	         * cache GetMenuItems calls
	         * this was removed due to some serverside problems,
	         * we should call this service on every user click to
	         * set some sort of user contexts on the server.
	         */
	        /*
	        jQuery('#menu > ul').hide();
	        if(jQuery(menuID).size()>0) {
	           jQuery(menuID).show();
	        } else {
	            var newMenuUL = jQuery(Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetMenuItems().value);
	            newMenuUL.attr('id','menu_' + itemIndex);
                //jQuery('#menu').append(Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetMenuItems().value);
                jQuery('#menu').append(newMenuUL);
            }
            */
            jQuery('#menu').html(Rayvarz.OfficeAutomation.Web.Main.MessageTree.GetMenuItems().value).find('a').fadeTo(0,.96);
            jQuery('#menu').raymenu();
            if (itemIndex != "1") {
                jQuery(".top-icon.sitter").css("display", "none");
                jQuery(".top-icon.search-letter").css("display", "none");
                jQuery(".top-icon.search-letter-forwards").css("display", "none");
            }
            else {
                jQuery(".top-icon.sitter").css("display", "");
                jQuery(".top-icon.search-letter").css("display", "");
                jQuery(".top-icon.search-letter-forwards").css("display", "");
            }
            
	        /*
	        if(currentIndexRes.value){
	        //alert(currentIndexRes.value);
	        var pathToShow = currentIndexRes.value.split('.');
	        var curentRel = Array();
	        for(var i=0; i<pathToShow.length; i++){
	        if(curentRel.length > 1){
	        curentRel.push(pathToShow[i]);
	        jQuery('#right_content_handles .handle-item').find('a[rel='+curentRel.join('.')+']').parent().click();
	        jQuery('ul.right_tree').find('.tree-icon[rel='+curentRel.join('.')+']').click();
                        
	        jQuery('ul.right_tree a').removeClass('tree-item-selected');
	        jQuery('ul.right_tree').find('.tree-icon[rel='+curentRel.join('.')+']').parent().find('> a').addClass('tree-item-selected');
	        }
	        }
	        }
	        */
	        return false;
	    });
	}
}

function reloadTreeMenu() {
    try {
        getTreeMenuRoots(true);
        buildTree();
        if(currentIndexRes.value){
            //alert(currentIndexRes.value);
            var pathToShow = currentIndexRes.value.split('.');
            var curentRel = Array();
            for(var i=0; i<pathToShow.length; i++){
                curentRel.push(pathToShow[i]);
                jQuery('#right_content_handles .handle-item').find('a[rel='+curentRel.join('.')+']').parent().click();
                jQuery('ul.right_tree').find('.tree-icon[rel='+curentRel.join('.')+']').click();
                
                jQuery('ul.right_tree a').removeClass('tree-item-selected');
                jQuery('ul.right_tree').find('.tree-icon[rel='+curentRel.join('.')+']').parent().find('> a').addClass('tree-item-selected');
            }
        }else{
            jQuery('#right_content_handles .handle-item:first').click();
        }
    }catch(e){
        // Take no action... it seems this page has no menu call backs to function
        // This is in case we get an error on page saying:
        // Microsoft JScript runtime error: 'Rayvarz.OfficeAutomation.Web.Main.MessageTree' is null or not an object
        // Which means there is no MessageTree included on the page, on the other hand we are not a page providing a
        // tree menu.
    }
}
/**
 * farshid:
 * login related, waterMarks add/remove functions
 */
function removeWaterMark(el){
	el.css('background', '#FFFFFF');
};
function addWaterMark(el,wmt){
	switch(wmt){
		case 'username':
			el.css('background', 'url(App_Themes/Concrete/images/layout.jpg) 0 -283px no-repeat');
			break;
		case 'password':
			el.css('background', 'url(App_Themes/Concrete/images/layout.jpg) -151px -283px no-repeat');
			break;
	};
};
/**
 * add on overlay to 'contentmain' div so that user can not click cartable
 * links, where not allowed, due to server side conext variable, used to
 * determine current user data. this data is removed in server when we call
 * menu services to manipulate page top menu
 */
function disableContentMainhandler(enable , mainIndex) {
    jQuery('#contentmainOverlay').remove();
    if(enable) {
        //jQuery('#contentmain').after(jQuery('<div id="contentmainOverlay"><a class="activate-link" href="#">برای فعال شدن اینجا کلیک کنید.</a></div>').fadeTo(0,.8));
        jQuery('#contentmain').after(jQuery('<div id="contentmainOverlay"></div>').fadeTo(0,.8));
        /*
        jQuery('#contentmainOverlay a.activate-link').click(function(e){
            //alert(mainIndex);
            var finderSelector = '#right_content_handles a[rel='+mainIndex+']';
            jQuery(finderSelector).parent().click();
            //alert(jQuery(finderSelector).size());
        });
        */
        //right_content_handles
    }
}

/**
 * RayMenu jQuery plugin to encapsulate menu related function
 * mostly added for the anomations and show/hiding menu items
 */
(function(jQuery) {
  function RayMenu(el, options) {
    this.el = jQuery(el);
    this.initialize();
  }
  jQuery.fn.raymenu = function(options) {
    return new RayMenu(this.get(0), options);
  };
  RayMenu.prototype = {
    killerFn: null,
    initialize: function(){
        jQuery('ul > li ul',this.el).parent().mouseenter(function(e){
            jQuery(this).siblings().removeClass('hover').find('ul').stop(true, true).fadeOut('fast');
            jQuery(this).addClass('hover').find('> ul').stop(true, true).fadeIn('normal');
        }).mouseleave(function(){
            jQuery(this).removeClass('hover').find('> ul').stop(true, true).fadeOut('fast');
        }).focusin(function(){
            jQuery(this).mouseenter();
        });
    }
  };
}(jQuery));

// usage
//jQuery('pre').fixOverflow().doOtherPlugin();
(function(jQuery) {
    jQuery.fn.fixOverflow = function() {
        if (jQuery.browser.msie) {
            return this.each(function() {
                if (((this.scrollWidth - this.offsetWidth) < 17) && ((this.scrollWidth - this.offsetWidth) > -11)) {
                    jQuery(this).css({ 'padding-left': (this.scrollWidth - this.offsetWidth)+'px', 'overflow-x': 'hidden' });
                }
            });
        } else {
            return this;
        }
    };
})(jQuery);
/**
* farshid:
* fixOverflow was used to work around the ie problem in rendering
* pages with both vertical and horizental scrolle, the problem is this:
* the scrill width/height in IE will be counted in the scrilled element 
* width/height.
*/
//if (jQuery('#contentmain').length > 0)
//    jQuery('#contentmain').fixOverflow();

/**
 * jQuery.FormNavigate.js
 * jQuery Form onChange Navigate Confirmation plugin
 * Browser Compatibility : IE 6.0, 7.0, 8.0; Firefox 2.0+;  Safari 3+; Opera 9+; Chrome 1+;
 *
 * Copyright (c) 2009 Law Ding Yong
 * 
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * See the file license.txt for copying permission.
 */
 
 /**
  * Documentation :
  * ==================
  *
  * How to Use:
  * jQuery("YourForm").FormNavigate("YourMessage");
  *  -- "YourForm" as Your Form ID jQuery("#form") or any method to grab your form
  *  -- "YourMessage" as Your onBeforeUnload Prompt Message Here
  *
  * This plugin handles onchange of input type of text, textarea, password, radio, checkbox and file to toggle on and off of window.onbeforeunload event.
  * Users are able to configure the custom onBeforeUnload message.
  */
var global_formNavigate = true;		// Js Global Variable for onChange Flag
(function(jQuery){
    jQuery.fn.FormNavigate = function(message) {
        window.onbeforeunload = confirmExit;  
        function confirmExit() {  
            if (global_formNavigate == true) {  event.cancelBubble = true;  }  else  { return message;  }
        }
        jQuery(this+ ":input[type=text], :input[type='textarea'], :input[type='password'], :input[type='radio'], :input[type='checkbox'], :input[type='file']").change(function(){
            global_formNavigate = false;
        });
        if(jQuery(this+ ":input[type=submit]").size() > 0) {
        jQuery(this+ ":input[type=submit]").click(function(){
            global_formNavigate = true;
        });
        }
        jQuery('.aspLinkButton').click(function(){
            global_formNavigate = true;
        });
        
        
    }
})(jQuery);




(function(jQuery) {
    jQuery.fn.__bind__ = jQuery.fn.bind; jQuery.fn.__unbind__ = jQuery.fn.unbind; jQuery.fn.__find__ = jQuery.fn.find; var hotkeys = { version: '0.7.9', override: /keypress|keydown|keyup/g, triggersMap: {}, specialKeys: { 27: 'esc', 9: 'tab', 32: 'space', 13: 'return', 8: 'backspace', 145: 'scroll', 20: 'capslock', 144: 'numlock', 19: 'pause', 45: 'insert', 36: 'home', 46: 'del', 35: 'end', 33: 'pageup', 34: 'pagedown', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 109: '-', 112: 'f1', 113: 'f2', 114: 'f3', 115: 'f4', 116: 'f5', 117: 'f6', 118: 'f7', 119: 'f8', 120: 'f9', 121: 'f10', 122: 'f11', 123: 'f12', 191: '/' }, shiftNums: { "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ":", "'": "\"", ",": "<", ".": ">", "/": "?", "\\": "|" }, newTrigger: function(type, combi, callback) { var result = {}; result[type] = {}; result[type][combi] = { cb: callback, disableInInput: false }; return result; } }; hotkeys.specialKeys = jQuery.extend(hotkeys.specialKeys, { 96: '0', 97: '1', 98: '2', 99: '3', 100: '4', 101: '5', 102: '6', 103: '7', 104: '8', 105: '9', 106: '*', 107: '+', 109: '-', 110: '.', 111: '/' }); jQuery.fn.find = function(selector) { this.query = selector; return jQuery.fn.__find__.apply(this, arguments); }; jQuery.fn.unbind = function(type, combi, fn) {
        if (jQuery.isFunction(combi)) { fn = combi; combi = null; }
        if (combi && typeof combi === 'string') { var selectorId = ((this.prevObject && this.prevObject.query) || (this[0].id && this[0].id) || this[0]).toString(); var hkTypes = type.split(' '); for (var x = 0; x < hkTypes.length; x++) { delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi]; } }
        return this.__unbind__(type, fn);
    }; jQuery.fn.bind = function(type, data, fn) {
        var handle = type.match(hotkeys.override); if (jQuery.isFunction(data) || !handle) { return this.__bind__(type, data, fn); }
        else {
            var result = null, pass2jq = jQuery.trim(type.replace(hotkeys.override, '')); if (pass2jq) { result = this.__bind__(pass2jq, data, fn); }
            if (typeof data === "string") { data = { 'combi': data }; }
            if (data.combi) {
                for (var x = 0; x < handle.length; x++) {
                    var eventType = handle[x]; var combi = data.combi.toLowerCase(), trigger = hotkeys.newTrigger(eventType, combi, fn), selectorId = ((this.prevObject && this.prevObject.query) || (this[0].id && this[0].id) || this[0]).toString(); trigger[eventType][combi].disableInInput = data.disableInInput; if (!hotkeys.triggersMap[selectorId]) { hotkeys.triggersMap[selectorId] = trigger; }
                    else if (!hotkeys.triggersMap[selectorId][eventType]) { hotkeys.triggersMap[selectorId][eventType] = trigger[eventType]; }
                    var mapPoint = hotkeys.triggersMap[selectorId][eventType][combi]; if (!mapPoint) { hotkeys.triggersMap[selectorId][eventType][combi] = [trigger[eventType][combi]]; }
                    else if (mapPoint.constructor !== Array) { hotkeys.triggersMap[selectorId][eventType][combi] = [mapPoint]; }
                    else { hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length] = trigger[eventType][combi]; }
                    this.each(function() {
                        var jqElem = jQuery(this); if (jqElem.attr('hkId') && jqElem.attr('hkId') !== selectorId) { selectorId = jqElem.attr('hkId') + ";" + selectorId; }
                        jqElem.attr('hkId', selectorId);
                    }); result = this.__bind__(handle.join(' '), data, hotkeys.handler)
                }
            }
            return result;
        }
    }; hotkeys.findElement = function(elem) {
        if (!jQuery(elem).attr('hkId')) { if (jQuery.browser.opera || jQuery.browser.safari) { while (!jQuery(elem).attr('hkId') && elem.parentNode) { elem = elem.parentNode; } } }
        return elem;
    }; hotkeys.handler = function(event) {
        var target = hotkeys.findElement(event.currentTarget), jTarget = jQuery(target), ids = jTarget.attr('hkId'); if (ids) {
            ids = ids.split(';'); var code = event.which, type = event.type, special = hotkeys.specialKeys[code], character = !special && String.fromCharCode(code).toLowerCase(), shift = event.shiftKey, ctrl = event.ctrlKey, alt = event.altKey || event.originalEvent.altKey, mapPoint = null; for (var x = 0; x < ids.length; x++) { if (hotkeys.triggersMap[ids[x]][type]) { mapPoint = hotkeys.triggersMap[ids[x]][type]; break; } }
            if (mapPoint) {
                var trigger; if (!shift && !ctrl && !alt) { trigger = mapPoint[special] || (character && mapPoint[character]); }
                else { var modif = ''; if (alt) modif += 'alt+'; if (ctrl) modif += 'ctrl+'; if (shift) modif += 'shift+'; trigger = mapPoint[modif + special]; if (!trigger) { if (character) { trigger = mapPoint[modif + character] || mapPoint[modif + hotkeys.shiftNums[character]] || (modif === 'shift+' && mapPoint[hotkeys.shiftNums[character]]); } } }
                if (trigger) {
                    var result = false; for (var x = 0; x < trigger.length; x++) {
                        if (trigger[x].disableInInput) { var elem = jQuery(event.target); if (jTarget.is("input") || jTarget.is("textarea") || jTarget.is("select") || elem.is("input") || elem.is("textarea") || elem.is("select")) { return true; } }
                        result = result || trigger[x].cb.apply(this, [event]);
                    }
                    return result;
                }
            }
        }
    }; window.hotkeys = hotkeys; return jQuery;
})(jQuery);





/**
 * farshid:
 * work around the garbage collection mentioned by alireza
 * I don't know if we should do this or not needs more testing
 * CollectGarbage is an undocumented function for IE, to make
 * IE collect garbage. it seems we need to delete variables
 * and set al unwanted properties to null to free them for
 * garbage collection, this is OKay for FF but IE needs the tweek
 */
// CollectGarbage();
if(!jQuery.support.leadingWhitespace) {
  setTimeout(CollectGarbage, 1000);
}