/*
 *
 *	panel.js
 *	Javascript for describe.php
 *	Created by Ian White
 *	Copyright 2008.
 *
 */


/*
 * Panel Class
 *
 * Creates, styles, assembles and inserts all of the elements required for a
 * describe panel.
 *
 */
function Panel() {

	this.panel            = null;
	this.style_chooser    = null;
	this.catagory_chooser = null;
	this.style_form       = null;
	
	this._startX    = 0;         // mouse starting positions
	this._startY    = 0;
	this._offsetX   = 0;         // current element offset
	this._offsetY   = 0;
	this._oldZIndex = 0;         // we temporarily increase the z-index during drag	
	this._dragElement;           // needs to be passed from OnMouseDown to OnMouseMove
	
	var me = this;


	/*
	 * initialize()
	 *
	 * This function does all of the content creation work.
	 *
	 */
	this.initialize = function() {
	
		// Grab the body element so that we can insert the editor
		body = document.getElementsByTagName('body').item(0);

		for(i=0; i< document.styleSheets.length; i++) {
			if(document.styleSheets[i].cssRules) { 
				for(j=0; j < document.styleSheets[i].cssRules.length; j++) {
					
					if(document.styleSheets[i].cssRules[j].selectorText != 'body' && document.styleSheets[i].cssRules[j].cssText.substr(0,7) != '@import' && document.styleSheets[i].cssRules[j].cssText.substr(0,6) != '@media') {
						sel = document.styleSheets[i].cssRules[j].cssText;
						parts = sel.split('{');
						
						names = parts[0].match(/([^,]+)\s*/g);
						
						new_name = "";
						for(k=0; k < names.length; k++) {
							if(!names[k].match(/\s*body\s*/i)) {
								new_name += "body>div#holder_div " + names[k] + ", ";
							}
						}
						
						if(new_name) {
							new_name = new_name.slice(0, -2);
							
							document.styleSheets[i].deleteRule(j);
							document.styleSheets[i].insertRule(new_name + " { " + parts[1], j);
							
						}					
					}
				}
			}
			else {
			
				
				//alert(document.styleSheets[i].cssText);
				rules = document.styleSheets[i].cssText.split('}');
				rule_num = 0;
				for(j=0; j < rules.length - 1; j++) {
					parts = rules[j].split('{');
					//alert('inspecting ' + parts[0]);
					if(!parts[0].match(/(^|\w*|>\w*)body[\w>#]/) && !parts[0].match(/@import/) && !parts[0].match(/@media/)) {
						sel = parts[0];
						//alert('reconstituting selector: ' + sel);
						
						
						names = parts[0].match(/([^,]+)\s*/g);
						
						new_name = "";
						for(k=0; k < names.length; k++) {
							if(!names[k].match(/\s*body\s*/i)) {
								new_name += "body>div#holder_div " + names[k] + ", ";
							}
						}
						
						if(new_name && parts[1]) {
							new_name = new_name.slice(0, -2);
							new_name = new_name.replace(/^\s+|\s+$/m, '');
							new_def  = parts[1].replace(/^\s+|\s+$/m, '');
							//alert("removing rule " + rule_num + ' ' + parts[0]);
							//alert('adding rule: ' + new_name + '\n' + parts[1]);
							document.styleSheets[i].removeRule(rule_num);
							document.styleSheets[i].addRule(new_name, parts[1]);
							rule_num--;
							
						}
						rule_num++;
					}
				}
			}
		}
		
		
		// Create all of the elements and style them.
		
		// Create the editor window, set its class and id
		this.panel = document.createElement('div');
		this.panel.id = 'panel';
		
		this.panel.style.inherit = "none";
		
		this.panel.style.position = 'absolute';
		this.panel.style.top = '50px';
		this.panel.style.left = (document.body.clientWidth - 300) + 'px';
		this.panel.style.padding = '0px';
		this.panel.style.backgroundImage = 'url(http://www.ianowhite.com/describe_files/background.png)';
		this.panel.style.color = 'white';
		this.panel.style.fontSize = '12px';
		this.panel.style.fontFamily = 'Verdana';
		this.panel.style.textAlign = 'left';
		this.panel.style.zIndex = '10000';
		this.panel.style.cursor = 'default';


		// Create the title bar that allows the window to be draggable
		titleBar = document.createElement('div');
		
		titleBar.style.inherit = "none";
		
		titleBar.style.position = 'relative';
		titleBar.style.backgroundImage = 'url(http://www.ianowhite.com/describe_files/top.png)';
		//titleBar.style.backgroundColor = 'none';
		titleBar.style.width = '250px';
		titleBar.style.height = '35px';
		titleBar.style.textAlign = 'center';
		titleBar.style.marginTop = '-25px';
		
		
		top_left = document.createElement('img');
		top_left.src = 'http://www.ianowhite.com/describe_files/topleft.png';
		top_left.style.position = 'absolute';
		top_left.style.left = '0px';
		top_left.style.marginLeft = '-25px';
		
		top_right = document.createElement('img');
		top_right.src = 'http://www.ianowhite.com/describe_files/topright.png';
		top_right.style.position = 'absolute';
		top_right.style.left = '100%';
		
		title = document.createElement('span');
		title.innerHTML = "Ian White's Portfolio";
		title.style.inherit = "none";
		title.style.lineHeight = '40px';
		title.style.fontFamily = 'Verdana';
		title.style.color = 'white';
		title.style.fontSize = '12px';
		title.style.fontWeight = 'bold';
		
		titleBar.appendChild(top_left);
		titleBar.appendChild(title);
		titleBar.appendChild(top_right);
				
		// Create the text container
		container = document.createElement('div');
		container.style.width = "250px";
		container.style.fontSize = "11px";
		container.style.lineHeight = "18px"
		

		// Project Name
		name_block = document.createElement('div');
		name_block.style.marginBottom = '5px';
		name_block.style.marginTop = '5px';
		
		name_span = document.createElement('span');
		name_span.style.fontWeight = 'bold';
		name_span.innerHTML = "Project: ";
		
		name_value = document.createElement('span');
		name_value.innerHTML = __floater_name;
		
		name_block.appendChild(name_span);
		name_block.appendChild(name_value);
		container.appendChild(name_block);
		
		// Project Technologies
		tech_block = document.createElement('div');
		tech_block.style.marginBottom = '5px';
		tech_block.style.marginTop = '5px';
		
		tech_span = document.createElement('span');
		tech_span.style.fontWeight = 'bold';
		tech_span.innerHTML = "Technologies: ";
		
		tech_value = document.createElement('span');
		tech_value.innerHTML = __floater_tech;
		
		tech_block.appendChild(tech_span);
		tech_block.appendChild(tech_value);
		container.appendChild(tech_block);
		
	
		// Project Description
		desc_block = document.createElement('div');
		desc_block.style.marginBottom = '5px';
		desc_block.style.marginTop = '5px';
		
		desc_span = document.createElement('span');
		desc_span.style.fontWeight = 'bold';
		desc_span.innerHTML = "Description: ";
		
		desc_value = document.createElement('span');
		desc_value.innerHTML = __floater_desc;
		
		desc_block.appendChild(desc_span);
		desc_block.appendChild(desc_value);
		container.appendChild(desc_block);
		
		
		// Project Link
		if(__floater_link) {
			link_block = document.createElement('div');
			link_block.style.marginBottom = '5px';
			link_block.style.marginTop = '5px';
			
			link_span = document.createElement('span');
			link_span.style.fontWeight = 'bold';
			link_span.innerHTML = "Link: ";
			
			link_value = document.createElement('a');
			link_value.href = __floater_link;
			link_value.innerHTML = __floater_link;
			link_value.style.color = 'white';
			link_value.style.cursor = 'pointer';
			
			link_block.appendChild(link_span);
			link_block.appendChild(link_value);
			container.appendChild(link_block);
		}
		
		// Source Files
		if(__floater_sources.length) {
			source_block = document.createElement('div');
			source_block.style.marginBottom = '5px';
			source_block.style.marginTop = '5px';
			
			source_span = document.createElement('div');
			source_span.style.fontWeight = 'bold';
			source_span.innerHTML = "Source Files: ";
			
			source_block.appendChild(source_span);
			
			for(i=0; i < __floater_sources.length; i++) {
				source_value = document.createElement('a');
				source_value.href = __floater_sources[i].url;
				source_value.innerHTML = __floater_sources[i].name;
				source_value.style.color = 'white';
				source_value.style.display = 'block';
				source_value.style.cursor = 'pointer';
				source_block.appendChild(source_value);
			}

			container.appendChild(source_block);
		}
		
		
		// The next four blocks are responsible for decorating the editor window to make
		// it look like a floating window with drop shadows and rounded borders.
		left_decorator = document.createElement('div');
		right_decorator = document.createElement('div');
		left_corner_decorator = document.createElement('div');
		right_corner_decorator = document.createElement('div');
		bottom_decorator = document.createElement('div');
		
		left_decorator.style.backgroundImage = 'url(http://www.ianowhite.com/describe_files/left.png)';
		left_decorator.style.width = '25px';
		left_decorator.style.height = '100%';
		left_decorator.style.marginLeft = '-25px';
		left_decorator.style.marginTop = '10px';
		left_decorator.style.top = '0px';
		left_decorator.style.left = '0px';
		left_decorator.style.position = 'absolute';
		
		left_corner_decorator.style.backgroundImage = 'url(http://www.ianowhite.com/describe_files/bottomleft.png)';
		left_corner_decorator.style.width = '25px';
		left_corner_decorator.style.height = '25px';
		left_corner_decorator.style.marginLeft = '-25px';
		left_corner_decorator.style.top = '100%';
		left_corner_decorator.style.left = '0px';
		left_corner_decorator.style.position = 'absolute';
		
		right_decorator.style.backgroundImage = 'url(http://www.ianowhite.com/describe_files/right.png)';
		right_decorator.style.width = '25px';
		right_decorator.style.height = '100%';
		right_decorator.style.top = '0px';
		right_decorator.style.marginTop = '10px';
		right_decorator.style.left = '100%';
		right_decorator.style.position = 'absolute';
		
		right_corner_decorator.style.backgroundImage = 'url(http://www.ianowhite.com/describe_files/bottomright.png)';
		right_corner_decorator.style.width = '25px';
		right_corner_decorator.style.height = '25px';
		right_corner_decorator.style.top = '100%';
		right_corner_decorator.style.left = '100%';
		right_corner_decorator.style.position = 'absolute';
		
		bottom_decorator.style.backgroundImage = 'url(http://www.ianowhite.com/describe_files/bottom.png)';
		bottom_decorator.style.width = '100%';
		bottom_decorator.style.height = '25px';
		bottom_decorator.style.top = '100%';
		bottom_decorator.style.left = '0px';
		bottom_decorator.style.position = 'absolute';
		
		left_decorator.innerHTML = '&nbsp;';
		left_corner_decorator.innerHTML = '&nbsp;';		
		right_decorator.innerHTML = '&nbsp;';
		right_corner_decorator.innerHTML = '&nbsp;';
		bottom_decorator.innerHTML = '&nbsp;';
		
		this.panel.appendChild(titleBar);
		this.panel.appendChild(left_decorator);
		this.panel.appendChild(right_decorator);
		this.panel.appendChild(left_corner_decorator);
		this.panel.appendChild(right_corner_decorator);
		this.panel.appendChild(bottom_decorator);
		this.panel.appendChild(container);
		
		
		if (this.panel.addEventListener){
			this.panel.addEventListener('mousedown', me.OnMouseDown, false);
			document.addEventListener('mouseup'  , me.OnMouseUp, false);
		} else if (this.panel.attachEvent){
			this.panel.attachEvent('onmousedown', me.OnMouseDown);
			document.attachEvent('onmouseup', me.OnMouseUp);
			
			top_left.style.marginTop = "-13px";
			top_right.style.marginTop = "-13px";
		}


		// Isolate the page so that the styles don't affect our viewer.
		holder = document.createElement('div');
		holder.id = "holder_div";
		holder.style.margin = '0px';
		holder.style.padding = '0px';
		
		for(i=0; i<body.childNodes.length; i++) {
			if(body.childNodes[i].nodeType != 3) {
				holder.appendChild(body.childNodes[i]);
				i--; 
			}
		}
		
		// Insert the isolated page back into the html document
		body.appendChild(holder);
		
		
		// Insert the completed editor window into the body of the page
		body.appendChild(this.panel);

		// Fix some last minute display issues.
		left_decorator.style.height = panel.offsetHeight-10 + "px";
		right_decorator.style.height = panel.offsetHeight-10 + "px";
	}
	
	
	this.ExtractNumber = function(value) { 
		n = parseInt(value); 
		return n == null || isNaN(n) ? 0 : n; 
	} 
	
	/*
	 * OnMouseDown()
	 * arg: e - a mousedown event
	 *
	 * This is run when the user mouses down on the panel. It adds the necessary
	 * event handlers to the document.
	 *
	 */
	this.OnMouseDown = function(e) {
	    // IE is retarded and doesn't pass the event object
	    if (e == null) 
	        e = window.event; 

	    // IE uses srcElement, others use target
	    target = document.getElementById('panel');

	    // for IE, left click == 1
	    // for Firefox, left click == 0
	    if (e.button == 1 && window.event != null || e.button == 0)
	    {
	        // grab the mouse position
	        me._startX = e.clientX;
	        me._startY = e.clientY;
			

	        // grab the clicked element's position
	        me._offsetX = ExtractNumber(target.offsetLeft);
	        me._offsetY = ExtractNumber(target.offsetTop);


	        // bring the clicked element to the front while it is being dragged
	        me._oldZIndex = target.style.zIndex;
	        target.style.zIndex = 10000;

	        // we need to access the element in OnMouseMove
	        me._dragElement = target;

	        // tell our code to start moving the element with the mouse
	        document.onmousemove = me.OnMouseMove;

	        // cancel out any text selections
	        document.body.focus();

	        // prevent text selection in IE
	        document.onselectstart = function () { return false; };

	        // prevent text selection (except IE)
	        return false;
	    }
	}
    
    
    /*
	 * OnMouseMove()
	 * arg: e - a mousemove event
	 *
	 * This handles the actual movement of the panel
	 *
	 */
    this.OnMouseMove = function(e)
	{
		document.body.focus();
	    if (e == null) 
	        var e = window.event; 

	    // this is the actual "drag code"
	    me._dragElement.style.left = (me._offsetX + e.clientX - me._startX) + 'px';
	    me._dragElement.style.top = (me._offsetY + e.clientY - me._startY) + 'px';
	}
	
	/*
	 * OnMouseUp()
	 * arg: e - a mouseup event
	 *
	 * This stops the OnMouseMove function from responding to mouse movements which
	 * stops the dragging action of the panel.
	 *
	 */
	this.OnMouseUp = function(e)
	{
	    if (me._dragElement != null)
	    {
	        me._dragElement.style.zIndex = me._oldZIndex;

	        // we're done with these events until the next OnMouseDown
	        document.onmousemove = null;
	        document.onselectstart = null;

	        // this is how we know we're not dragging      
	        me._dragElement = null;

	    }
	}
	
	
	
	this.initialize();
}



// Preload all of the editor images
img1 = new Image(25,35);
img2 = new Image(25,35);
img3 = new Image(25,25);
img4 = new Image(25,25);
img5 = new Image(2, 35);
img6 = new Image(2, 25);
img7 = new Image(25, 2);
img8 = new Image(25, 2);
img9 = new Image(68,16);
img10= new Image(10,10);

img1.src = "http://www.ianowhite.com/describe_files/topleft.png";
img2.src = "http://www.ianowhite.com/describe_files/topright.png";
img3.src = "http://www.ianowhite.com/describe_files/bottomleft.png";
img4.src = "http://www.ianowhite.com/describe_files/bottomright.png";
img5.src = "http://www.ianowhite.com/describe_files/top.png";
img6.src = "http://www.ianowhite.com/describe_files/bottom.png";
img7.src = "http://www.ianowhite.com/describe_files/left.png";
img8.src = "http://www.ianowhite.com/describe_files/right.png";
img9.src = "http://www.ianowhite.com/describe_files/bottom.png";
img10.src= "http://www.ianowhite.com/describe_files/background.png";

if (window.addEventListener){
	window.addEventListener('load', Panel, false); 
} else if (window.attachEvent){
	window.attachEvent('onload', Panel);
}