/**
 * Core JS library for SWC 
 * version: $Id: swc.js 593 2008-07-10 17:23:27Z szczesnym $
 */
var Swc = {

    DelayId: null,

    // Delays any JS function by intDelay secons with an auto cancel if executed again
    Delay: function(FunctionToCall,Delay) {
		if(typeof(Swc.DelayId) != 'undefined') {
            clearTimeout(Swc.DelayId);
		}
		Swc.DelayId   = FunctionToCall.delay(Delay);
    },

    /**
     * Open / Close popup functions
     */
    OpenPopup: function(Title,Width,Height) {
        startPopup(Title,'divPopupContainer','divPopupTitle', Width, Height);
    },
    ClosePopup: function() {
        stopPopup('divPopupContainer','divPopup');
    },
    
    /**
     * Provides the basic notification functionality
     */
	Notify: function(Message) {
	    if( typeof( window.innerWidth ) == 'number' ) {
	        $('divSaveMessage').style.position   = 'fixed';
	    }
	    $('divSaveMessage').style.top     = 'auto';
	    $('divSaveMessage').style.left    = 'auto';
	    $('divSaveMessage').style.bottom  = '12px';
	    $('divSaveMessage').style.right   = '12px';
	    $('divSaveMessage').innerHTML     = Message;
	    $('divSaveMessage').style.display = 'block';
	    timerScroll = setTimeout(Swc.NotifyStop,2000);
    },
    
    NotifyStop: function() {
        $('divSaveMessage').style.display = 'none';
    }
    
};
/**
 * Core SWC TinyMCE configurations
 * Version: $Id: tiny.js 567 2008-07-03 13:58:00Z szczesnym $
 */
var Tiny = {
  tinyConfigs: {
      'default': {
        mode: "specific_textareas",
        plugins: "spellchecker,media",
        theme: "advanced",
        theme_advanced_toolbar_location: "top",
        theme_advanced_buttons1: "bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist",
        theme_advanced_buttons2: "forecolor,image,code,anchor,html,link,unlink,spellchecker,media",
        theme_advanced_buttons3: "",
        convert_urls: false,
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_path: false,
        theme_advanced_resize_horizontal: false,
        theme_advanced_resizing: true,
        cleanup_on_startup: true,
        apply_source_formatting: true,
        extended_valid_elements: "object[width|height],param[name|value],embed[src|type|wmode|width|height]",
        width: "100%" },
        
    'simple': {
        mode: "specific_textareas",
        theme: "simple",
        width: "100%" }
  },
  
  /**
   * Registers alternative tinyMCE configuration
   */
  addConfig: function(ConfigurationName, ConfigurationObject) {
      Tiny.tinyConfigs[ConfigurationName] = ConfigurationObject;
  },
  
  // Disables tinyMCE on ElementId
  disable: function(ElementId) {
      tinyMCE.execCommand('mceRemoveControl', false, ElementId);
  },
  
  /**
   * Enables editor on any ElementId, with a given ConfigurationName
   */
  enable: function(ElementId, ConfigurationName) {
    if(typeof(ConfigurationName) == 'undefined') {
        ConfigurationName = 'default';
    }
    tinyMCE.settings = Tiny.tinyConfigs[ConfigurationName];
    tinyMCE.execCommand('mceAddControl', true, ElementId);
  }
  
};/**
 * File browser interface for SWC 
 * version: $Id: filebrowser.js 613 2008-07-29 15:43:32Z szczesnym $
 */

var FileBrowser = {

  /**
   * Close the file browser
   */
  close: function() {
      return Swc.ClosePopup();
  },
  
  /**
   * SelectionFunction:
   *  - JS function that will be called on the file, ie. doSomething({FileId});
   *  - {FileId} bracket that will be replaced with an ID of the file
   * Filter: empty, 'Images','PdfDocuments','OfficeDocuments','ZipFiles'
   */
  open: function(SelectionFunction, Filter) {
      return xajax_openFileManager(Filter, SelectionFunction);
  }
  
}
		var currentMenuId   = null;
		document.onclick    = check;
		
		function check(e){
		    if(currentMenuId) {
		        var target  = (e && e.target) || (event && event.srcElement);
		        var obj     = $('AdminMenu_' + currentMenuId);
		        var objIcon = $('AdminMenuIcon_' + currentMenuId);
		        var objBlSet= $('aibs_' + currentMenuId);
		        var objBtSet= $('aibts_' + currentMenuId);
		        if (obj) {
		            if (target!=obj && target!=objIcon && target!=objBlSet && target!=objBtSet) {
		                closeAdminNav(currentMenuId);
		            }
		        }
		    }
		}
		
		
        var PopupsCounter = 0;
        var PageReloadRequired = 0;
		var EditorOnClose = 0;
		
		// POPUPS
        function openPopup(Title, Width, Height) { startPopup(Title,'divPopupContainer','divPopupTitle', Width, Height); }
        function hidePopup() { stopPopup('divPopupContainer','divPopup'); }
		
        function openPopup2(Title, Width, Height) { startPopup(Title,'divPopup2Container','divPopup2Title', Width, Height); }
        function hidePopup2() { stopPopup('divPopup2Container','divPopup2'); }
        
        function startPopup(Title, PopupContainerDiv, PopupTitleDiv, Width, Height) {
            var Dimmer = 'divDimmer';
            if( typeof( window.innerWidth ) == 'number' ) { // Non-IE
                $(Dimmer).style.position = 'fixed';
                intHeight = document.body.parentNode.scrollHeight;
                intWidth  = document.body.parentNode.scrollWidth;
            } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { // IE 6+ in 'standards compliant mode'
                intHeight = Math.max(document.body.parentNode.scrollHeight, document.documentElement.clientHeight);
                intWidth  = Math.max(document.body.parentNode.scrollWidth, document.documentElement.clientWidth);
            } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { // IE 4 compatible (quirk mode)
                intHeight = document.body.parentNode.scrollHeight-20;
                intWidth  = document.body.parentNode.scrollWidth-20;
            }
            $(Dimmer).style.height = intHeight+'px';
            $(Dimmer).style.width  = intWidth+'px';
            intPopWidth = Math.floor(intWidth * 0.9);
            intPopHeight = '90%';
            strTop = '5%';
            strLeft = '5%';
            if(typeof(Width) == 'number') {
              intPopWidth = Width;
              strLeft = ((intWidth - intPopWidth) / 2)+'px';
            }
            $(PopupContainerDiv).style.width  = intPopWidth+'px';
            $(PopupContainerDiv).style.top = strTop;
            $(PopupContainerDiv).style.left = strLeft;
            
            var arrSelects = $$('body select');
            if(arrSelects) {
              for (x=0;x<arrSelects.length;x++) {
                if(!arrSelects[x].descendantOf(PopupContainerDiv)) {
                    arrSelects[x].style.visibility='hidden';
                }
              }
            }
            $(PopupTitleDiv).innerHTML = Title;
            $(Dimmer).style.display = 'block';
            $(PopupContainerDiv).style.display = 'block';
            loadingStop();
            window.scrollTo(0,0);
            new Draggable(PopupContainerDiv, {handle:PopupTitleDiv});
            loadTooltips(PopupContainerDiv);
        }
        
        function stopPopup(PopupContainerDiv,PopupDiv) {
            if(EditorOnClose && currentEditorId) {
                switchOffEditor(currentEditorId);
            }
            Dimmer = 'divDimmer';
			$(Dimmer).style.display = 'none';
			$(Dimmer).style.height = '1px';
			$(PopupContainerDiv).style.display = 'none';
			$(PopupDiv).innerHTML = '';
			if(PageReloadRequired) {
			    printSaveMessage('Reloading Page... Please wait...');
			    document.location=document.location;
			}
            var arrSelects = $$('body select');
            if(arrSelects) {
              for (x=0; x<arrSelects.length; x++) {
                if(!arrSelects[x].descendantOf(PopupContainerDiv)) {
                    arrSelects[x].style.visibility='visible';
                }
              }
            }
        }
		
		function printSaveMessage(Message) {
            Swc.Notify(Message);
		}
				
		function loading() {
		    //$('divLoading').style.display = 'block';
		}
		function loadingStop() {
		    //$('divLoading').style.display = 'none';
		}
		function loadPageVersion() {
		    $('ai_divPageVersion').innerHTML = 'Loading page...';
		}
		
		
		function checkUploadForm() {
		    // You can do some checks here
		    $('ai_FileUploadSubmit').disabled = 'true';
		    $('ai_FileUploadSubmit').value   = 'Uploading...';
		    return xajax.upload('uploadFile','ai_FileManager_UploadForm');
		
		}
		
		
		function openAdminNav(BlockId) {
		    if(currentMenuId) {
		        closeAdminNav(currentMenuId);
		    }
		    currentMenuId   = BlockId;
		    desiredTop      = $('AdminMenuIcon_'+BlockId).offsetTop  + 23;
		    desiredLeft     = $('AdminMenuIcon_'+BlockId).offsetLeft - 229;
		    arrBlocks       = $$('.ai_cb');
            for(x=0;x<arrBlocks.length;x++){
                arrBlocks[x].style.zIndex = '0';
            }
            $('aicb_'+BlockId).style.zIndex           = '1';
		    $('AdminMenu_'+BlockId).style.top         = desiredTop+'px';
		    $('AdminMenu_'+BlockId).style.left        = desiredLeft+'px';
		    $('AdminMenu_'+BlockId).style.display     = 'block';
		}
		
		function closeAdminNav(BlockId) {
		    $('AdminMenu_'+BlockId).style.display     = 'none';
		    currentMenuId   = null;
		}
		
		
		// FUNCTION TO DELAY / CANCELL ONKEYUP
		var ActionTimer = null;
		
		function delayedOnKeyUpAction(FunctionToCall,Delay) {
		    if(ActionTimer) {
		        clearTimeout(ActionTimer);
		    }
		    ActionTimer     = setTimeout(FunctionToCall,Delay);
		}
		
		var MoveBlockId = null;
		var MoveDirection = null;
		var MoveDivId = null;
		
		var ShadowDiv = null;
		var ddRevert = true;
		var myDrags = [];
		
		function startDragging(BlockId) {
		    MoveBlockId = BlockId;
		    //console.log('Dragged BlockId:' + BlockId);
		}
		
		var OverBlockMarked = null;
		
		function calculateDrop(DropBlock,DraggedBlock) {
		
		    Container = DropBlock.parentNode;
		
		    if(ShadowDiv) {
		        ShadowDiv = null;
		    }
		    if($('_Shadow')) {
		        Container = $('_Shadow').parentNode;
		        Container.removeChild($('_Shadow'));
		    }
		
		    ShadowDiv = document.createElement("div");
		    ShadowDiv.setAttribute('id', '_Shadow');
		    ShadowDiv.setAttribute('style','float:left;position:relative;margin:-2px;border:2px dashed #aaa;');
		    ShadowDiv.style.width = DraggedBlock.style.width;//.clientWidth + 'px';
		    ShadowDiv.style.height = DraggedBlock.clientHeight + 'px';
		    MoveDivId = DropBlock.id;
		
		    booBefore = calculateDropBefore(DropBlock,DraggedBlock);
		    if(booBefore) {
		        MoveDirection = 'Before';
		        Container.insertBefore(ShadowDiv, DropBlock);
		        ddRevert = false;
		    }
		    else {
		        MoveDirection = 'After';
		        Container.insertBefore(ShadowDiv, DropBlock.nextSibling);
		        ddRevert = false;
		    }
		}
		
		function calculateDropBefore(DropBlock,DraggedBlock) {
		
		    Dragged_x = getX(DraggedBlock);
		    Drop_x = getX(DropBlock);
		    Dragged_mx = Dragged_x + 0.5 * DraggedBlock.clientWidth;
		    Drop_mx = Drop_x + 0.5 * DropBlock.clientWidth;
		    if(Dragged_mx > Drop_mx) {
		        return false;
		    }
		    return true;
		}
		
		
		function endDragging(BlockId) {
		
		    if($('_Shadow')) {
		        //console.log('End of drag: MoveBlockId = ', MoveBlockId, '; MoveDirection = ', MoveDirection, '; MoveDivId = ', MoveDivId);
		        TargetContainer = $('_Shadow').parentNode;
		        switch(MoveDirection) {
		            case 'Before':
		                TargetContainer.insertBefore($('aicb_'+MoveBlockId), $(MoveDivId));//insertbefore);
		                xajax_moveBlock(MoveBlockId,MoveDivId,'Before');
		                break;
		            case 'After':
		                TargetContainer.insertBefore($('aicb_'+MoveBlockId), $(MoveDivId).nextSibling);//insertbefore);
		                xajax_moveBlock(MoveBlockId,MoveDivId,'After');
		                break;
		        }
		        $('aicb_'+MoveBlockId).style.top = null;
		        $('aicb_'+MoveBlockId).style.left = null;
		
		        TargetContainer.removeChild($('_Shadow'));
		        MoveBlockId = null;
		        MoveDirection = null;
		        MoveDivId = null;
		        ddRevert = true;
		        return true;
		    }
		    else {
		        return true;
		    }
		}
		
		function getY(oElement) {
		    var iReturnValue = 0;
		    while( oElement != null ) {
		        iReturnValue += oElement.offsetTop;
		        oElement = oElement.offsetParent;
		    }
		    return iReturnValue;
		}
		
		function getX(oElement) {
		    var iReturnValue = 0;
		    while (oElement != null) {
		        iReturnValue += oElement.offsetLeft;
		        oElement = oElement.offsetParent;
		    }
		    return iReturnValue;
		}

		var currentEditorId         = null;
		var currentContentBlockId   = null;
		
        if(typeof(tinyMCE) !== 'undefined') {    tinyMCE.init({
        mode : "specific_textareas",
        editor_selector : "mceEditor",
        plugins : "spellchecker,media,youtube,table",
        theme : "advanced",
        theme_advanced_toolbar_location : "top",
        theme_advanced_buttons1 : "bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,forecolor",
        theme_advanced_buttons2 : "image,code,anchor,html,link,unlink,table,spellchecker,youtube,media",
        theme_advanced_buttons3 : "",       
        convert_urls : "false",
        relative_urls : "true",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_path : false,
        theme_advanced_resize_horizontal : false,
        theme_advanced_resizing : true,
        cleanup_on_startup : false,
        cleanup_on_start: false,
        apply_source_formatting : true,
        width: "100%"
    });        }
		
		function switchOnEditor(ElementId, ContentBlockId, PopupEditor) {
		    if(currentEditorId) {
		        switchOffEditor(currentEditorId); 
		        xajax_getHtmlContent(currentContentBlockId,1);
		    }
		    if(PopupEditor) { EditorOnClose = 1; }
		    currentEditorId         = ElementId;
		    currentContentBlockId   = ContentBlockId;
		    
		    $(ElementId).style.height = "300px";
		    //Tiny.enable(ElementId);
		    tinyMCE.execCommand('mceAddControl', false, ElementId);
		}
		
		function switchOffEditor(ElementId) {
		    tinyMCE.execCommand('mceRemoveControl', false, ElementId);
		    //Tiny.disable(ElementId);
		    currentEditorId         = null;
		    EditorOnClose           = 0;
		}
		
		var arrTooltips=[];
        var arrTipIds=[];

        function loadTooltips(ContainerDiv) {
            if(typeof(Tip) == 'undefined') return;
		    if(ContainerDiv) {
		        var arrTips = $$('body #'+ContainerDiv+' [tip]');
		    } else {
		        var arrTips = $$('body [tip]');
		    }
		    arrTipIdsTmp=[];
		    if(arrTips) {
		        for (x=0; x<arrTips.length; x++) {
		          tid = arrTips[x].readAttribute('tip');
		          if(arrTipIds.indexOf(tid) == -1) {
		            arrTipIdsTmp.push(tid);
		            arrTipIds.push(tid);
		          }
		        }
		    }
		    if(arrTipIdsTmp) xajax_loadTooltips(arrTipIdsTmp);
		}
		
		function setTooltip(Tid, Tooltip, booSticky) {
		    var arrTipTags = $$('body [tip='+Tid+']');
		    for (x=0; x<arrTipTags.length; x++) {
		      if(booSticky) {
		        arrTipTags[x].onmouseover=function(){return Tip(Tooltip,STICKY,1,CLOSEBTN,true,CLICKCLOSE,true,TITLE,'Tooltip for: '+Tid);}
	          }
	          else {
	            arrTipTags[x].onmouseover=function(){return Tip(Tooltip);}
	          }
	          arrTipTags[x].onmouseout=function(){UnTip();}
	        }
		}
		
		
		function sfHover() {
			
		    if(document.getElementById("ai_nav") && document.getElementById("ai_nav").getElementsByTagName("LI")){
	            var sfEls = document.getElementById("ai_nav").getElementsByTagName("LI");
	            for (var i=0; i<sfEls.length; i++) {
	                sfEls[i].onmouseover=function() {
	                    this.className+=" sfhover";
	                }
	                sfEls[i].onmouseout=function() {
	                    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
	                }
	            }
			}
        }
        if (window.attachEvent) window.attachEvent("onload", sfHover);
		
        /**
         * CustomMsg: {short:'xxx',weak:'xx',medium:'yyyy',strong:'zzz'}
         */
        function checkPasswordStrength(pwd,did,CustomMsg) {
        
            if(typeof(CustomMsg)=='undefined') {
              CustomMsg = new Object({short: 'Password is too short',
    	                   weak: '<span style="color:red">Password is weak</span>',
                           medium: '<span style="color:orange">Password is ok</span>',
    	                   strong: '<span style="color:green">Password is strong</span>'
    	                   });
            }
            var strength = $(did);
            var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
            var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
            var enoughRegex = new RegExp("(?=.{6,}).*", "g");
            if (pwd.length==0) {
              strength.innerHTML = '';
            } else if (false == enoughRegex.test(pwd)) {
              strength.innerHTML = CustomMsg.short;
            } else if (strongRegex.test(pwd)) {
              strength.innerHTML = CustomMsg.strong;
            } else if (mediumRegex.test(pwd)) {
              strength.innerHTML = CustomMsg.medium;
            } else {
              strength.innerHTML = CustomMsg.weak;
            }
        }
        
        var Track = {
            classPrefix: 'tr_',
            register: function() {
                $$('a[href!="javascript:void(0);"]').invoke('observe','mousedown',Track.log);
	        },
	        log: function(e) {
	            var strClass = $w(e.element().className).find(function(strClass){return strClass.startsWith(Track.classPrefix)});
                if(!strClass) {
                    return true;
                }
                var objLog = { pid: Page.pid, lid: strClass.match('_(.*)').last() }
                var strUrl = '/js/common/ct.tao?'+Object.toQueryString(objLog);
                new Ajax.Request(strUrl, {method: 'get'});
                return true;
            }
        }
        if(typeof(Page) != 'undefined' && Page.ltr) document.observe('dom:loaded',Track.register);
        
        
        