var modalBox = new Class ({

	container: "modalboxWrap",
	
	launch: function (url,width,height,color) {
	
		
		if ($defined($('modalBox')))
			$('modalBox').destroy();
	
	
		var windowSize = window.getSize();
	
		if (! $defined($('modalBlanket'))) {
			
			if( window.innerHeight && window.scrollMaxY ) {
				
			}
			else if( document.body.scrollHeight > document.body.offsetHeight ) // all but Explorer Mac
			{
				pageWidth = document.body.scrollWidth;
				pageHeight = document.body.scrollHeight;
			}
			else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
			{ 
				pageWidth = document.body.offsetWidth + document.body.offsetLeft; pageHeight = document.body.offsetHeight + document.body.offsetTop; 
			}
			pageWidth = "100%";
			pageHeight = "100%";
			
			var blanket = new Element("div", {'id': 'modalBlanket'});
			blanket.setStyle("height", pageHeight);
			blanket.setStyle("width", pageWidth);
			//console.log(pageWidth);
			//console.log(pageHeight);
			blanket.setStyle("display", "block");
			blanket.setStyle("position", "absolute");
			blanket.setStyle("top", 1);
			blanket.setStyle("left", 1);
			blanket.setStyle("background", "black");
			blanket.setStyle("opacity", .5);
			blanket.setStyle("z-index", 1000);
		
			blanket.inject($(this.container));
			
			blanket.addEvent('click', function () {this.close()}.bind(this));
		}
	
		if (! $defined($('modalBox'))) {
			var box = new Element("iframe", {'id': 'modalBox'});
			
			var boxTop = (windowSize.y - height) / 2;
			if (boxTop < 0) boxTop = 0;
			
			var boxLeft = (windowSize.x - width) / 2; 
			if (boxLeft < 0) boxLeft = 0;
			
			if (height > windowSize.y) height = windowSize.y - 50;

			var barHeight = 25; 
			
			var boxWrap = new Element("div", {id: 'boxWrap'});
			boxWrap.setStyle("position", "fixed");
			boxWrap.setStyle("top", boxTop);
			boxWrap.setStyle("left", boxLeft);
			
			box.setStyle("position", "relative");
			box.setStyle("height", height);
			box.setStyle("width", width);
			box.setStyle("border", "1px solid black");
			box.setStyle("padding", "4px");
			box.setStyle("margin", "4px");
			box.setStyle("z-index", "1000");
			box.setStyle("background", "black");
			box.setStyle("overflow", "auto");
			box.setStyle("z-index", 10001);
			
			box.setProperty("id", "modalBox");
			
			box.inject(boxWrap);
			boxWrap.inject($(this.container));
			/*
			var content = new Element("div", {id: 'modalContent'});
			content.setStyle("height", height - barHeight - 8);
			content.setStyle("width", width);
			content.setStyle("overflow", "auto");
			
			content.inject(box);
			*/
			box.src = url;
			box.marginhwidth = 10;
			box.marginheight = 10;
			if ($defined($('formHeader'))) {
				
			}
			
			var bar = new Element("div", {id: 'toolBar'});
			
			bar.inject(box);
			
			
		}
		
		return true;
		
		box.load(url, {complete: function () {
			
			
			if ($defined('formFooter')) {
				
				var bar = $defined('formFooter');
				bar.setStyle("position", "absolute");
				bar.setStyle("top", height - barHeight);
				bar.setStyle("height", barHeight);
				bar.setStyle("width", width);
				bar.setStyle("border", "1px solid black");
				bar.setStyle("background-color", "#ddd");
				
			}
			
		}});
		
		return box;
	
	},
	
	close:  function () {
	
		$('modalBlanket').destroy();
		$('modalBox').destroy();
	
	}
});

modalBox = new modalBox();

function form2url(wformid,encode_it){
  
  if (kform = document.getElementById(wformid)){
    var fkeys = new Array();
    var fvals = new Array();
    var str = "";
    var no,i;
    var inputFields = kform.getElementsByTagName("INPUT");
    for(no=0;no<inputFields.length;no++){
      if (inputFields[no].type.toLowerCase() == "checkbox"){
        if(inputFields[no].checked){
          fkeys[fkeys.length] = inputFields[no].name;
          fvals[fvals.length] = "on";
        }
      } else if (inputFields[no].type.toLowerCase() != "button" && inputFields[no].type.toLowerCase() != "submit"){
        fkeys[fkeys.length] = inputFields[no].name;
        fvals[fvals.length] = inputFields[no].value;
      }
    }
    var selectBoxes = kform.getElementsByTagName("SELECT");
    for(no=0;no<selectBoxes.length;no++){
      fkeys[fkeys.length] = selectBoxes[no].name;
      fvals[fvals.length] = selectBoxes[no].value;
    }
    var selectBoxes = kform.getElementsByTagName("TEXTAREA");
    for(no=0;no<selectBoxes.length;no++){
      fkeys[fkeys.length] = selectBoxes[no].name;
      fvals[fvals.length] = selectBoxes[no].value;
    }
 
    for(i=0;i<fkeys.length;i++){
      str += "&"+fkeys[i]+"="+(fvals[i]?escape((encode_it?encode64(fvals[i]):fvals[i])):"");
    }
 
    return str;
  }
}
 
 
// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;
 
   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
 
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
 
      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }
 
      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
 
   return output;
}
function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;
 
   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));
 
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
 
      output = output + String.fromCharCode(chr1);
 
      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);
 
   return output;
}


/*
Script: mootools.ddmenu.99.js
 ddmenu is a simple MooTools-based script to create you're own context menus
 
License:
 MIT-style license.

Author:
jan angel manolov <email@webhike.de>  <http://netjard.de/lab/ddmenu>

 Changelog:
 v.1.0 [6/17/08]
	- MooTools 1.2 Ready
 
 v0.99 [6/9/08]
	- the ddmenu works good, no bugs concidered since the last update.
	- waiting for the mootools 1.2 release, to get a final version of the ddmenu.
	- url chanched to <netjard.de/labs/ddmenu>
 
v.0.2.1 [2/11/08]
    Fixes for MooTools 1.2 Beta 2 

v.0.2 [1/1/08]
    Scroll-save, correct positioning
    Ctrl and Shift Switches
    Fade In
    CSS-Styles reworked and adapted
    This Demo Page and Google Code registration
    
v.0.1</span> [11/07]
    Initial Version with a basic menu script structure
    Event-calls and enableItems(), enableOnlyThisItems() Functions
    Adapted the complex when-menu-is-opened events on the System Context Menu Style

	
Use enableThisItemsOnly and enableItems to enable or disable menu items by they're ids

    enableThisItemsOnly ([item1,item2], true)   	-> disable all other
    enableThisItemsOnly (item)                    	-> same
    enableThisItemsOnly ([item1,item2], false)  	-> enable all other

    enableItems ([item1,item2])           			-> enable this items
    enableItems (item1)                   			-> same 
    enableItems ([item1,item2], false)    			-> disable this thems
    enableItems ()                        				-> enable all items    
    enableItems (false)                   			-> disable all      
*/

var DDMenu = new Class ({

    Implements: [Events, Options],
    
    options: {
        onOpen: $empty,
        onClose: $empty,
        onItemSelect: $empty, 
        observe_disabled_items: false,                                     //call onItemSelect() on disabled items?
        rightclick_to_open: true,                                          //open menu on rightclick (if browser supports contextmenu-events)
        crtl_switch: true,                                                 //allow to switch between default menu and dd
        shift_with_contentmenu: true, //not ie                                  						//show default & dd menu together
        fade_in: true,
        cursorx: 2,                                                        //distance to cursors-coords
        cursory: 1,
        opacity: 0.95                                                      //menu transparency
    },
    
    initialize: function (menu, bindon, options) {
    
        this.setOptions (options);
        this.eMenu = $(menu);
        this.eBindon = $(bindon);
        
        this.eMenu.setStyles ({ 
            position: 'absolute', 
            'z-index': 9999, 
            display: 'none'
        });

        this.open = this.open.bindWithEvent(this);
        this.close = this.close.bind(this);
        this.preOpenEvent = this.preOpenEvent.bind(this)
        this.menuEvent = this.menuEvent.bindWithEvent(this);
        
        this.clickedElement = $empty;
        
        this.eBindon.addEvents ({
            'mousedown': function () { this.eBindon.addEvent ('contextmenu', $break) }.bind(this),
            'mouseup': this.preOpenEvent
        });
        
        //this.eMenu.getElements('li.item a').addEvent('click', $break); //safari bug :(
        $$('#'+menu+' li a').addEvent('click', $break);
    },

    //while hidden

    preOpenEvent: function (event) {  
    
        if (event.shift) {
            this.eBindon.removeEvent ('contextmenu', $break);
        }
        else if (this.options.crtl_switch && event.rightClick && event.control) { //open browser default contextmenu
            this.eBindon.removeEvent ('contextmenu', $break);
            return true; 
        }
        
        event.preventDefault();
        if (this.eMenu.style.display == 'block') this.close(event);
        
        this.clickedElement = $(event.target);

        if (event.rightClick) {
            if (this.options.crtl_switch && event.control) return true;
            else if (this.options.rightclick_to_open) this.open(event);
        }
        if (event.control) this.open(event);
		  else return true;

        return false;        
    },
    
    
    open: function (event) { 
        
        this.eMenu.setStyles ({opacity: 0, display: 'block', 'z-index':99999, top:event.page.y + this.options.cursory, left:event.page.x + this.options.cursorx});
        
        var coords = {};
        this.eMenu.getPosition().y-$(document.body).getScroll().y+this.eMenu.getSize().y < $(document.body).getSize().y ?
            coords.y = event.page.y + this.options.cursory :
            coords.y = event.page.y - this.eMenu.getSize().y + this.options.cursory;
        if (coords.y<$(document.body).getScroll().y+1) coords.y = $(document.body).getScroll().y+1;
        
        this.eMenu.getPosition().x-$(document.body).getScroll().x+this.eMenu.getSize().x < $(document.body).getSize().x ?
            coords.x = event.page.x + this.options.cursorx :
            coords.x = event.page.x - this.eMenu.getSize().x + this.options.cursorx;

        if (coords.x<$(document.body).getScroll().x+1) coords.x = $(document.body).getScroll().x+1;
        
        if (event.shift) coords.x = event.page.x - this.eMenu.getSize().x - this.options.cursorx;

        this.eMenu.setStyles({ top: coords.y, left: coords.x });
        
        if (this.options.fade_in) {
            var op = this.options.opacity;
            var fadein = new Fx.Morph (this.eMenu, {duration:200}).start({ 'opacity': [.32, op] });
        }
        else this.eMenu.style.opacity = this.options.opacity;
        


        window.addEvent ('blur', function () { if (!Browser.Engine.trident) this.close() }.bind(this)); //ie throws currious blur events
        document.addEvent ('mousedown', this.menuEvent);
        
        this.eMenu.addEvents({
            'contextmenu': function () {return false},
            'mouseup': this.menuEvent
        });
        

        this.fireEvent('onOpen', event);
    },
    
    
    //while opened
    
    menuEvent: function (event) { 
        
        event.preventDefault();
        
        var item = $(event.target);

        if (item == this.eMenu || item == this.eMenu.getElement('ul')) return false; 
        
        item = this.ascendTo(item, ['item','sepline','title']); 
        
        if (item === false) {
            this.close(event); //outer event
        }
        else if (item.hasClass('item') && event.type == 'mouseup') {
            if (!(item.getElement('a').hasClass('disabled') && !this.options.observe_disabled_items)) {
                this.action(item); 
                this.close(event); 
            }
        }
    },    
    
    
    close: function (event) {
            
        this.eMenu.style.display = 'none';         
          
        document.removeEvent ('mousedown', this.menuEvent);
        window.removeEvent ('blur', function () {if (!Browser.Engine.trident) this.close()}.bind(this));
        this.eMenu.removeEvents();
                     
        this.fireEvent('onClose', event);    
    },
    
    
    action: function (item) {
        
        //this.clickedElement.focus();
        this.fireEvent('onItemSelect', [item.get('id'), this.clickedElement, this.eBindon]);
        return;
    },
    
    
    ascendTo: function (el, peakto) {
    
        if (el == window) return false;
        
        var ascel = el;
                
        while (ascel.get('tag') != 'html') { 
            
            for (var i=0; i<peakto.length; i++) {
                if (ascel.hasClass(peakto[i])) return ascel;
            }
            ascel = ascel.getParent(); 
        }
        
        return false;        
    },
    
      
    

    
    enableThisItemsOnly: function (items, enable) {
        
        if (!$chk(enable) && enable!=false) enable = true;
        if ($type(items) == 'string') items = [items];
        if (!items.length) return;
        
        enable == true ?
            this.eMenu.getElements ('li.item a').addClass('disabled') :
            this.eMenu.getElements ('li.item a').removeClass('disabled');                

        items.each (function (item) {
            enable == true ? 
                this.eMenu.getElement('li#'+item+' a').removeClass('disabled') :
                this.eMenu.getElement('li#'+item+' a').addClass('disabled');
        }.bind(this));            
    },
    
    
    enableItems: function (items, enable) {
    
        if (!$chk(items) && items!=false) items = true;
        if ($type(items) == 'boolean') {
            items == true ? 
                this.eMenu.getElements ('li.item a').removeClass('disabled') : 
                this.eMenu.getElements ('li.item a').addClass('disabled');
            return;
        }     
    
        if (!$chk(enable) && enable!=false) enable = true;
        if ($type(items) == 'string') items = [items];

        items.each (function (item) {
            enable == true ? 
                this.eMenu.getElement('li#'+item+' a').removeClass('disabled') :
                this.eMenu.getElement('li#'+item+' a').addClass('disabled');
        }.bind(this));
    }
    
});


$break = function () {return false;}


