/// <reference path="QCore.js" />
/*** QUI.js **/

/*** 
    - $.scrollTo( target, settings )
    - jQuery.fn.hint


***/

/*** CONTEXT MENU ***/
/*
 * ContextMenu - jQuery plugin for right-click context menus
 *
 * Author: Chris Domigan
 * Contributors: Dan G. Switzer, II
 * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Version: r2
 * Date: 16 July 2007
 *
 * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
 *
 */

(function($) {

  var menu, shadow, trigger, content, hash, currentTarget;
  var defaults = {
    menuStyle: {
      listStyle: 'none',
      padding: '1px',
      margin: '0px',
      backgroundColor: '#fff',
      border: '1px solid #999',
      width: '100px'
    },
    itemStyle: {
      margin: '0px',
      color: '#000',
      display: 'block',
      cursor: 'default',
      padding: '3px',
      border: '1px solid #fff',
      backgroundColor: 'transparent'
    },
    itemHoverStyle: {
      border: '1px solid #0a246a',
      backgroundColor: '#b6bdd2'
    },
    eventPosX: 'pageX',
    eventPosY: 'pageY',
    shadow : true,
    onContextMenu: null,
    onShowMenu: null
 	};

  $.fn.contextMenu = function(id, options) {
    if (!menu) {                                      // Create singleton menu
      menu = $('<div id="jqContextMenu"></div>')
               .hide()
               .css({position:'absolute', zIndex:'500'})
               .appendTo('body')
               .bind('click', function(e) {
                 e.stopPropagation();
               });
    }
    if (!shadow) {
      shadow = $('<div></div>')
                 .css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
                 .appendTo('body')
                 .hide();
    }
    hash = hash || [];
    hash.push({
      id : id,
      menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}),
      itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}),
      itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
      bindings: options.bindings || {},
      shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
      onContextMenu: options.onContextMenu || defaults.onContextMenu,
      onShowMenu: options.onShowMenu || defaults.onShowMenu,
      eventPosX: options.eventPosX || defaults.eventPosX,
      eventPosY: options.eventPosY || defaults.eventPosY
    });

    var index = hash.length - 1;
    $(this).bind('contextmenu', function(e) {
      // Check if onContextMenu() defined
      var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
      if (bShowContext) display(index, this, e, options);
      return false;
    });
    return this;
  };

  function display(index, trigger, e, options) {
    var cur = hash[index];
    QContextMenu = $('#'+cur.id).get(0);
    content = $('#'+cur.id).find('ul:first').clone(true);
    content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
      function() {
        $(this).css(cur.itemHoverStyle);
      },
      function(){
        $(this).css(cur.itemStyle);
      }
    ).find('img').css({verticalAlign:'middle',paddingRight:'2px'});

    // Send the content to the menu
    menu.html(content);

    // if there's an onShowMenu, run it now -- must run after content has been added
		// if you try to alter the content variable before the menu.html(), IE6 has issues
		// updating the content
    if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu, QContextMenu, trigger);

    $.each(cur.bindings, function(id, func) {
      $('#'+id, menu).bind('click', function(e) {
        hide();
        func(trigger, currentTarget);
      });
    });
    QMI._QContextMenuHide = function(){ hide();}; 
    
    menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();
    if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();
    $(document).one('click', hide);
  }

  function hide() {
    menu.hide();
    shadow.hide();
  }

  // Apply defaults
  $.contextMenu = {
    defaults : function(userDefaults) {
      $.each(userDefaults, function(i, val) {
        if (typeof val == 'object' && defaults[i]) {
          $.extend(defaults[i], val);
        }
        else defaults[i] = val;
      });
    }
  };

})(jQuery);

$(function() {
  $('div.contextMenu').hide();
});

function QContextMenu_Init(ev,args){
    $(".QCxtMLinked").each(function(){
        eval("var setting = " + this.value);
        for (var i=0;i<setting.Ctls.length;i++){
            $(setting.Ctls[i]).contextMenu(setting.QCxtM,
                {
                    menuStyle:{width:'250px'},
                    onContextMenu: function(e) { return true; },
                    onShowMenu: function(e, menu, QContextMenu, trigger) {
                        var TriggerUniqueID = $(trigger).attr('name');
                        try {
                            if (typeof(TriggerUniqueID) == 'undefined' || TriggerUniqueID == 'undefined'){
                                TriggerUniqueID = $(trigger).QGetSetting('UniqueID');
                            }
                        }catch(e){
                            AlertObject(e);
                            QEH.log(e.Message);
                        }
                        QMI.ContextMenu(
                        {
                            SourceControl:trigger,
                            SourceControlClientID: $(trigger).attr('id'),
                            SourceControlUniqueID: TriggerUniqueID,                            
                            TargetControl:e.target,
                            TargetControlClientID: $(e.target).attr('id'),
                            TargetControlUniqueID: $(e.target).attr('name'),
                            e:e,
                            OpenMenu:menu,
                            TopMenu:QContextMenu
                        });
                        return menu;
                    }
                });
        }
    });
}

/*** SCROLL TO ***/
(function( $ ){  
	$.scrollTo = function( target, settings ){
		return $('html,body').scrollTo( target, settings );
	};
	
	$.scrollTo.defaults = {
		axis:'y',
		speed:1
	};
	
	$.fn.scrollTo = function( target, settings ){
		settings = $.extend( {}, $.scrollTo.defaults, settings );
		settings.queue = settings.queue && settings.axis.length == 2;//make sure the settings are given right
		if( settings.queue )
			settings.speed = Math.ceil( settings.speed / 2 );//let's keep the overall speed, the same.
		if( typeof settings.offset == 'number' )
			settings.offset = { left: settings.offset, top: settings.offset };
		
		return this.each(function(){
			var $elem = $(this), t = target, toff, attr = {};
			switch( typeof t ){
				case 'number'://will pass the regex
				case 'string':
					if( /^([+-]=)?\d+(px)?$/.test(t) ){
						t = { top:t, left:t };
						break;//we are done
					}
					t = $(t,this);// relative selector, no break!
				case 'object':
					if( t.is || t.style )//DOM/jQuery
						toff = (t = $(t)).offset();//get the real position of the target 
			}
			$.each( settings.axis.split(''), parse );			
			animate( settings.onAfter );			
			
			function parse( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					act = $elem[0][key];
					
				attr[key] = toff ? toff[pos] + ( $elem.is('html,body') ? 0 : act - $elem.offset()[pos] ) : t[pos];
				
				if( settings.margin && t.css )//if it's a dom element,reduce the margin
					attr[key] -= parseInt( t.css('margin'+Pos) ) || 0;
				
				if( settings.offset && settings.offset[pos] )
					attr[key] += settings.offset[pos];
				
				if( !i && settings.queue ){//queueing each axis is required					
					if( act != attr[key] )//don't waste time animating, if there's no need.
						animate( settings.onAfterFirst );//intermediate animation
					delete attr[key];//don't animate this axis again in the next iteration.
				}
			};
			function animate( callback ){
				$elem.animate( attr, settings.speed, settings.easing, function(){
					if( callback )
						callback.call(this, $elem, attr, t );
				});
			};
		});
	};

})( jQuery );

jQuery.fn.QGetStyle = function(style){
    return getStyle(this.get(0),style);
}

/* Jquery Hint */
jQuery.fn.hint = function () {
  return this.each(function (){
        // get jQuery version of 'this'
        var t = jQuery(this); 
        // get it once since it won't change
        var title = t.attr('title'); 
        // only apply logic if the element has the attribute
        if (title) { 
          // on blur, set value to title attr if text is blank
          t.blur(function (){
            if (t.val() == '') {
              t.val(title);
              t.addClass('HintBlur');
            }
          });
          // on focus, set value to blank if current value 
          // matches title attr
          t.focus(function (){
            if (t.val() == title) {
              t.val('');
              t.removeClass('HintBlur');
            }
          });

          // clear the pre-defined text when form is submitted
          t.parents('form:first()').submit(function(){
              if (t.val() == title) {
                  t.val('');
                  t.removeClass('HintBlur');
              }
          });

          // now change all inputs to title
          t.blur();
        }
  });
}

jQuery.fn.QDisableSelection = function(){
    return this.each(function(){
        this.onselectstart = function(){return false;}
        this.unselectable = "on";
        this.style.MozUserSelect = "none";
    });
}

/*** QHiddenSettings ***/
jQuery.fn.QGetSetting = function(Setting){
    var $ctl = this.find('.QHiddenSettings');
    var str = $ctl.val();
    if (typeof(str) == 'undefined'){ throw(QException(this,"Cannot find QHiddenSettings for control.")); }
    if (Setting == "UniqueID") {
        return $ctl.attr("name");
    }else{
        eval('var s = ' + str);
        if(Setting){
            return s[Setting];
        }
        else { return str }
    }
}
jQuery.fn.QChangeSetting = function (Setting,Value) {
    return this.each(function(){
        var hiddenSettings = this;
        if (hiddenSettings.className.indexOf('QHiddenSettings') == -1){
            hiddenSettings = $(this).find('.QHiddenSettings').get(0);
        }
        if (typeof(hiddenSettings.value) == 'undefined' || hiddenSettings.value == ''){
        }else{
            eval('var s = ' + hiddenSettings.value);
            // find single quote
            var RegExQuote = /[']/g;
            // find comma
            var RegExComma = /[,]/g;
            // find escape character
            var RegExEsc = /[\\]/g;
            /*
            if(typeof(Value) == 'string'){
                Value= Value;
            }*/
            s[Setting] = Value;
            var sAll = '{Changed:true';
            for(var i in s){
                if(i != 'Changed'){
                    if(typeof(s[i]) == 'string'){
                        sAll += ","+i+":'"+s[i].replace(RegExQuote,"\'").replace(RegExComma,"\,").replace(RegExEsc,"\\\\")+"'";
                    }else{
                        sAll += ','+i+':'+s[i];
                    }
                }
            }
            sAll += '}';
            hiddenSettings.value = sAll;
        }
    });
}

jQuery.fn.QHide = function(){ return this.each(function(){ Hide_Ctl(this); }); }

/*** QRequireResource ***/
jQuery.fn.QResourceExists = function(filename, filetype){   
    filename = filename.toLowerCase().replace(/&amp;/g,"&");    
    var found = false;
    if (filetype=="js"){ //if filename is a external JavaScript file
        $("script","head").each(function(){
            if (Right(this.src.toLowerCase(),filename.length) == filename){ found = true; return false; }
        });
        return found;    
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        $("link","head").each(function(){
            if (Right(this.href.toLowerCase(),filename.length) == filename){ found = true; return false; }
        });
        return found;
    }    
}
jQuery.fn.QRequireResource = function(filename, filetype){
    if ($().QResourceExists(filename,filetype)){ return true; }
    QCore.Debug.WriteLine('Resource included: '+filename);
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename.replace(/&amp;/g,"&"));
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename.replace(/&amp;/g,"&"));
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
    
    return true;
}

/*** QMenuItem ***/
function QMenuItem_Init(ev,args){
    args.$ctlsByClass("QMenuH")
        .each(function(){
            $(".QMISort:first",this)
                .sortable({
                    axis:"x",
                    containment:"parent",
                    update:QMenuItem_SortUpdate
                });
        });
    args.$ctlsByClass("QMenuV")
        .each(function(){
            $(".QMISort:first",this)
                .sortable({
                    axis:"y",
                    containment:"parent",
                    update:QMenuItem_SortUpdate
                });
        });
    args.$ctlsByClass("navTree")
        .each(function(){
            var $TopMenu = $(".QMISort:first",this)
            $TopMenu
                .sortable({
                    axis:"y",
                    containment:"parent",
                    update:QMenuItem_SortUpdate
                });
            $(".QMI_Children",$TopMenu)
                .sortable({
                    axis:"y",
                    containment:"parent",
                    update:QMenuItem_SortUpdate
                });
                    //connectWith:[".QMISort .QMI_Children"],
        });
    args.$ctlsByClass("QMI")
        .QDisableSelection()
        .each(function(){       
            $(".navTreeItem:first",this)
                .each(function(){
                    var $navTreeLabel = $(".navTreeLabel:first",this);
                    if ($navTreeLabel.get(0).tagName.toLowerCase() != 'a'){
                        $navTreeLabel.bind("click",QMI.onClick);
                    }
                    var $this = $(this);
                    if ($this.hasClass("QMI_DD")){
                        $this
                            .draggable({
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex:1000
                            })
                            .droppable({
	                            accept: ".QMI_DD",
	                            tolerance: 'pointer',
	                            activeClass: 'QMI_DD_Active',
	                            hoverClass: 'QMI_DD_Hover',
	                            drop: QMenuItem_Drop
                            });                        
                    }
                });
        
        });
}

function QMenuItem_Drop(ev,ui){
    QCore.Debug.WriteLine("QMenuItem_Drop(ev,ui)");
    var dragitm = new QMenuItem(ui.draggable.get(0));
    var dropitm = new QMenuItem(this);
    if (dragitm.UniqueID != dropitm.UniqueID){ dropitm.onDrop(dragitm); }
}
function QMenuItem_SortUpdate(e,ui){
    QCore.Debug.WriteLine("QMenuItem_Sort(ev,ui)");
    var index = ui.element.children().index(ui.item);
    var dragitm = new QMenuItem(ui.item);
    if (dragitm.UniqueID != ''){ dragitm.onSortUpdate(index); }
}
function QMenuItem_Toggle(img,ClientID){
    $(img).toggleClass('QMenuItem_Minus').toggleClass('QMenuItem_Plus');
    $(img).siblings('.QHiddenSettings').QChangeSetting('Expanded',true);
    var $Children = $('#'+ClientID);
    if (!$(img).hasClass('QMenuItem_Minus')){$Children.hide(250);}
    else{$Children.show(300);}
}
function QMenuItem_MoveToChildren(ParentID,ChildID){
    QCore.Debug.WriteLine("QMenuItem_MoveToChildren("+ParentID+","+ChildID+")");
    var ParentElement = document.getElementById(ParentID);
    if (ParentElement == null){throw("Cannot Find Parent Element from ID: "+ParentID);}
    var ChildElement = document.getElementById(ChildID);
    if (ChildElement == null){throw("Cannot Find Child Element from ID: "+ ChildID);}

    var ParentMenu = new QMenuItem(ParentElement);
    var ChildMenu = new QMenuItem(ChildElement);
    ParentMenu.MoveToChildren(ChildMenu);
}
function QMenuItem(ChildCtl){
    if(ChildCtl){
        var $Element = null;
        if ($(ChildCtl).hasClass("QMI")){
            $Element = $(ChildCtl);
        }else{
            $Element = $($(ChildCtl).parents('.QMI').get(0));
        }
        eval('var Settings='+$Element.children('.QHiddenSettings').val());
        this.Settings = Settings;
        this.ClientID = $Element.attr('id');
        this.UniqueID = $Element.QGetSetting("UniqueID");
        this.$element = $Element;
        this.element = $Element.get(0);
        this.$SecondaryRow = $Element.find('.QMI_Children');
        // PROPERTIES
        this.AutoSubmitMode = function(){
            return getAutoSubmitMode(Settings.AutoSubmit);
        }
        this.Checked = function(b){
            if(typeof(b) != 'undefined'){
              this.$element.find(".chk").get(0).checked = b;
              return b;
            }else{
                var checkbox = null;
                var checkboxes = this.$element.find(".chk");
                if (checkboxes.length > 0) { 
                    return checkboxes.get(0).checked;
                }else{
                    return false;
                }
            }
        }
        this.AutoCallBack = function(){
            return this.AutoSubmitMode().AutoCallBack;
        }
        this.isContextMenu = function(){
            return this.Settings.CxtM;
        }
        this.Selected = function(b){
            if(typeof(b) != 'undefined'){
                if (b){ 
                    if (!this.$element.hasClass("QMI_Sel")){
                        $(".QMI_Sel",this.$TopMenu())
                            .removeClass("QMI_Sel")
                            .QChangeSetting("Selected",false)
                            .children(".QMI_SelItem")
                            .removeClass("QMI_SelItem");

                        this.$element
                            .addClass("QMI_Sel")
                            .QChangeSetting("Selected",true)
                            .children(".navTreeItem")
                            .addClass("QMI_SelItem");
                    }
                    return b;
                }else{
                    this.$element
                        .removeClass("QMI_Sel")
                        .children(".QMI_SelItem")
                        .removeClass("QMI_SelItem");
                    return b;
                }
            }else{
                return this.$element.hasClass("QMI_Sel");
            }        
        }
        this._TopMenu = null;
        this.$TopMenu = function(){
            return $(this.TopMenu());
        }
        this.TopMenu = function(){
            if (!this._TopMenu){
                if (this.isContextMenu()){ this._TopMenu = QMI.ContextMenu().TopMenu; }
                else{ this._TopMenu = FindParentFromClass(this.element,"navTree"); }
            }
            return this._TopMenu;        
        }
        this.Value = function(s){
            if(typeof(s) != 'undefined'){
                this.$element.QChangeSetting("Value",s);
                return this;
            }else{
                return this.$element.QGetSetting("Value");
            }
        }
        // METHODS
        this.onCheckChanged = function(chk){
            QMI.CheckChanged.Raise(this);
            if (this.AutoCallBack()){
                QCore.AutoSubmit.CallBack(this.UniqueID,this.Checked(),"CheckChanged",chk);
            }        
        }
        this.onClick = function(){
            if (this.Settings.Selectable){ this.Selected(!this.Selected()); }
            if (this.AutoCallBack()){
                if (this.isContextMenu()){
                    var TopMenuUniqueID = this.$TopMenu().QGetSetting('UniqueID');
                    var SourceUniqueID = QMI.ContextMenu().SourceControlUniqueID;
                    var TargetUniqueID = QMI.ContextMenu().TargetControlUniqueID;
                    QCore.AutoSubmit.CallBack(TopMenuUniqueID,this.UniqueID+'|'+SourceUniqueID+'|'+TargetUniqueID,"ChildClick",this.TopMenu());
                    QMI.QContextMenuHide();
                }else{
                    QCore.AutoSubmit.CallBack(this.UniqueID,'',"Click",this.element);
                }
            }
            return true;
        }
        this.onDoubleClick = function(){
            QCore.AutoSubmit.CallBack(this.UniqueID,'',"DblClick",this.element)
        }
        this.onDrop = function(DragItem){
            QCore.AutoSubmit.CallBack(this.UniqueID,DragItem.UniqueID,"Drop",this.element)
        }
        this.MoveToChildren = function(MenuItem){
            var child = MenuItem.element;
            this.$element.children(".QMenuItem_Transparent").removeClass("QMenuItem_Transparent").addClass("QMenuItem_Plus");
            $(child).appendTo("#"+this.ClientID+"_Children");
        }
        this.onSortUpdate = function(NewIndex){
            QCore.AutoSubmit.CallBack(this.UniqueID,NewIndex,"SortUpdate",this.element)
        }
    }
}
function QMenuItemsObject(){
    
    // PROPERTIES
    this._ContextMenu = null;
    this.ContextMenu = function(o){
        if (typeof(o) != 'undefined'){ this._ContextMenu = o; return o; }
        else{ return this._ContextMenu; }
    };

    // METHODS
    //this._QContextMenuHide = null;
    this.QContextMenuHide = function(){
        if (typeof(this._QContextMenuHide) != 'undefined'){ this._QContextMenuHide(); }
    }
    this.onDblClick = function(child){
        var menuitem = new QMenuItem(child);
        menuitem.onDoubleClick();
    }
    this.CheckChanged = new QEvent("QMenuItem.CheckChanged");
    this.Click = new QEvent("QMI.Click");
    this.onClick = function(e){
        QMI.Click.Raise();
        var menuitem = new QMenuItem(this);
        if (menuitem){
            return  menuitem.onClick();
        }
        return false;
    }
    this.onChk = function(chk){
        var menuitem = new QMenuItem(chk);
        if (menuitem){menuitem.onCheckChanged(chk);}
    }
    
}
var QMI = new QMenuItemsObject();
jQuery.fn.QShow = function(){ return this.each(function(){ Show_Ctl(this); }); }

/********************************************** QDialog */
jQuery.fn.QCloseDialog = function(){
    return this.each(function(){
        var dlg = FindParentFromClass(this,'ui-dialog');
        $(dlg).dialogClose();
    });
}
jQuery.fn.QShowDialog = function(DialogOptions){
    DialogOptions.jQuery = this;
    ShowDialog(DialogOptions);
}

function ShowDialog(DialogOptions){
    DialogOptions = jQuery.extend({
        Buttons:null,
        ContentID:'',
        height: 370,
        jQuery:null,
        PageUrl:'',
        Title: '',
        width: 650,
        resize: false
    }, DialogOptions);
  
    if (DialogOptions.ContentID != ''){
        var container = document.getElementById(DialogOptions.ContentID);
    }
    else if (DialogOptions.PageUrl != ''){
        container = document.createElement('div');
        $(container).attr({id: 'QDialog','class': 'QDialog flora',title: DialogOptions.Title});
        var iHeight = DialogOptions.height-34;
        if (DialogOptions.Buttons != null){ iHeight = iHeight-34;}
	    iframe = document.createElement('iframe');
	    $(iframe)
		    .attr({
				    id			: 'QDialogIframe',
				    src			: DialogOptions.PageUrl,
				    frameborder	: '0',
				    scrolling	: 'auto'
			})
		    .css ({
				    position	: 'relative',
				    top			: '0',
				    left		: '0',
				    width       : (DialogOptions.width-10)+'px',
				    height      : (iHeight)+'px'
			});
		    $(container).append(iframe);
	        $('body').append(container);
    }else{
        throw 'Dialog must have a PageUrl or a ContainerID';
    }
    if (DialogOptions.Buttons == null){ DialogOptions.Buttons = {} }
    try {
        var AspNetFormAction = $('form').attr('action');
        var DialogForm = document.createElement('form');
        $(DialogForm)
            .attr({
                name:'dialogForm',
                method:'post',
                action:AspNetFormAction,
                id:'dialogForm'
            })
            .addClass('QDialog')
            .appendTo('body');
        $(container)
            .removeClass('QDialog')
            .addClass('QDialogContents')
            .appendTo(DialogForm);
        $(DialogForm).dialog({width:DialogOptions.width,height:DialogOptions.height,buttons:DialogOptions.Buttons,resizable:false});
    }catch(e){
        $(container).dialog({width:DialogOptions.width,height:DialogOptions.height,buttons:DialogOptions.Buttons,resizable:false});
    }
}

/********************************************** QSlideShowController */

function QSSControllerObject(ChildCtl) {
    if(ChildCtl){
        this.element = FindParentFromClass(ChildCtl,"QSlideShowController");

        // Methods        
        this.GoSlide = function(SlideID){
            $.islideshow.go({slide:{id:this.SlideShowID(),slide:SlideID}});
        }
        // Properties
        this.SlideShowID = function(){
            return $(this.element).QGetSetting("ID");
        }
    }
}

var QSSGetSlideTimeOut = 0;
function QSSGetSlide(ctl,slide){
    var QSSControl = new QSSControllerObject(ctl);
    clearTimeout(QSSGetSlideTimeOut);
    QSSGetSlideTimeOut = setTimeout(function(){QSSControl.GoSlide(slide);},500);
}

/*** QTextBox ***/
jQuery.fn.QTextBoxCounter = function() {
    $(this).each(function() {
        var max = $(this).attr('maxlength');
        if (typeof(max)!='undefined'){
            var val = $(this).attr('value');
            var cur = 0;
            if(val) // value="", or no value at all will cause an error
              cur = val.length;
            var left = max-cur;
            $(this).after("<div class='counter'>" + left.toString()+"</div>");
            // You can use something like this to align the
            // counter to the right of the input field.
            var c = $(this).next(".counter");
            c.width(27);
            c.css("position","absolute");
            c.css("top",$(this).height() -7);
            c.css("right",23);
            c.css("text-align","center");
            c.css("visibility","hidden");
            c.css("background-color","#fdffbc");

            $(this).focus(function(e){
                var c = $(this).next(".counter");
                c.css("visibility","visible");
            });
            $(this).blur(function(e){
                var c = $(this).next(".counter");
                c.css("visibility","hidden");
            });
            $(this).keyup(function(i) {
              var max = $(this).attr('maxlength');
              var val = $(this).attr('value');
              var cur = 0;
              if(val)
                cur = val.length;
              var left = max-cur;
              $(this).next(".counter").text(left.toString());
              return this;
            });
        }
    });
    return this;
}

/*** Layout Controls ***/
var QLayout = new Object;
QLayout.ThreeColumnControls = new QDictionary("QLayout.ThreeColumnControls")
QLayout.AddThreeCol = function(ClientID, Width, Height, Left, Middle, Right) {
    QLayout.ThreeColumnControls.Add(ClientID, { Width:Width, Height:Height,Left: Left, Middle: Middle, Right: Right });
}
QLayout.onResize = function() {
    if (!QCore.DirectRequestInitRun) {
        QLayout.ThreeColumnControls.Each(function(key, Entry) {
            if (Entry.Width == 'Fill') {
                var $ThreeCol = $(key);
                var NewWidth = $ThreeCol.parent().width();
                $ThreeCol.css('width', NewWidth + 'px');
                $(key + ' > .QThreeColumn_Middle').css('width', NewWidth - Entry.Left - Entry.Right - 1);
            }
        });
    }
}
QCore.Init.AddHandler(QLayout.onResize);
QCore.WindowResize.AddHandler(QLayout.onResize);

/*** QUI Init ***/
function QUI_Init(ev,args){
    QCore.Debug.WriteLine("QUI_Init(ev,args)");
    var $ctls = args.$UpdatedControls;    
    $('.ShowHint',$ctls).hint();
    try{$('.NumberBox',$ctls).numeric({allow:".£,+-%"});}catch(e){}
    try{$('.TimeBox',$ctls).numeric({allow:":.apm"});}catch(e){}    
    $.ImageBox.init({loaderSRC: 'images/waiting.gif',closeHTML:  'close'});
    $('.QFS_Detail .TextArea').QTextBoxCounter();
}

QCore.Init.AddHandler(QUI_Init);
QCore.Init.AddHandler(QMenuItem_Init);
QCore.Init.AddHandler(QContextMenu_Init);

QCore.AutoSubmit.CallBackComplete.AddHandler(QUI_Init);


