/*
	Dependencies: (make sure these are loaded first)
		friz.js

	USAGE: This script requires a <div id="build_site"></div> to add content to
	in order to get around IE's issues with adding elements directly to the body of a page.
	You can use the div for whatever you would like or you can set its display to none.  Either is fine.
	Make sure the script is not called before the element has been rendered.  The easiest way to 
	do that is to have the following just before the </body> tag:
	<div id="build_site"></div>
	<script type="text/javascript" src="/path/to/this/file/friz_popup.js"></script>
*/

if(!friz.popup) { friz.popup = {}; }

friz.popup = function (){
	
	 // variable to contain the reference to the <div id="build_site"></div> used for putting things in the page
	var build_site=false;
	// variable to hold alerts that run on after another to keep the alert integrity
	//var alerts=new Array();
	var popupCalls = new Array();
	
    /*
		    an array of tags to check for the confirm option
		    if you change this array you may need to adjust the
		    updateElements function as well.
    */
    var confirm_tags = new Array("form","a","button");	
    
	/*
		variables related to the popup
	*/
	var backdrop,dialog,btnConfirm,btnCancel,dialog_message,popup_timer;
	
	window.alert = function(txt){ addCall(txt,'ok','friz_info.png',0); }; //addAlert;
	/*
	    Initializes the constuction of the friz.popup system
	*/	
	function Init(){

	    // if the build_site exists we are going to capture it
	    if(document.getElementById("build_site")){
		    build_site = document.getElementById("build_site");
		    buildPopup(); // if the build site exists, lets build!!
		    
		    updateElements(); // alters the elements on the page that need confirmation
	    }
		
		if(popupCalls.length > 0)
			popupInit(popupCalls[0]);
	}
	/*
		Alert function
	*/
/*	function addAlert(txt){
		alerts.push(txt);
		popupAlert();
	}*/
	
	function addCall(message,buttons,image,wait){
		popupCalls.push({
						message : message,
						buttons : buttons,
						image : image,
						wait : wait
						});
		
		if(popupCalls.length == 1 && btnCancel){
			popupInit(popupCalls[0]);
		}
	}
	
/*	function popupAlert(){
		if((dialog_message) && alerts.length > 0){
			if(dialog.style.display=="none"){
				popupInit(alerts.shift(),"ok","friz_info.png",0);
			}
		}
	}*/
	
	/*
		Creates the dialog structures
	*/
	function buildPopup(){
		// the backdrop to prevent access to the rest of the screen
		backdrop=document.createElement("div");
		backdrop.className = "friz_backdrop";
		// the actual dialog box
		dialog=document.createElement("div");
		dialog.className="friz_dialog";
		// the buttons
		btnConfirm=document.createElement("input");
		btnConfirm.setAttribute("type","button");
		btnConfirm.setAttribute("value","Yes");
		btnConfirm.style.visibility="hidden";
		btnCancel=document.createElement("input");
		btnCancel.setAttribute("type","button");
		btnCancel.setAttribute("value","No");
		btnCancel.style.visibility="hidden";
		
		// add the event listeners for the buttons
		friz.addEvent(btnConfirm,"click",popupConfirm);
		friz.addEvent(btnCancel,"click",popupCancel);
		
		// the text and button positioning elements
		dialog_message = document.createElement("p");
		var tmpElement = document.createElement("p");
		
		// build the dialog box
		tmpElement.appendChild(btnConfirm);
		tmpElement.appendChild(btnCancel);
		dialog.appendChild(dialog_message);
		dialog.appendChild(tmpElement);
		build_site.appendChild(backdrop);
		build_site.appendChild(dialog);
	}

	/*
		Checks elements for the confirm attribute set to true
		and adds an event listener to the show the confirm
		dialog
	*/
	function updateElements(){
		var obj; // element group array
		var ti, i; // increment variables
		var evnt; // the event name to attach the call to
		var func; // a temp function
		var func2; // because sometimes you need it
		
		for( ti = 0; ti < confirm_tags.length; ti++ ) {
			var obj=document.getElementsByTagName(confirm_tags[ti]);

			for( i = 0; i < obj.length; i++ ){
				if(obj[i].getAttribute("confirm")=="true" && (!obj[i].getAttribute("oldevnt"))){
					switch(obj[i].tagName.toLowerCase()){
						case "form":
							evnt = "submit";
						break;
						case "a":
							if(typeof obj[i].getAttribute("onclick") == 'function'){
								func = obj[i].onclick;
								obj[i].setAttribute("onclick",
													function(){ 
														func();
														window.location.href=obj[i].getAttribute("href");
													});
							} else {
								obj[i].setAttribute("onclick",
													"window.location.href='"
													+ obj[i].getAttribute("href") + "'");
							}
						default:
							evnt = "click";
						break;
					}
					
					if(obj[i].getAttribute("on"+evnt)){
						obj[i].setAttribute("oldevnt",obj[i].getAttribute("on"+evnt));
						obj[i].removeAttribute("on"+evnt);
					}
					
					if(obj[i]["on"+evnt]){
						obj[i].setAttribute("oldevent",obj[i]["on"+evnt]);
						obj[i]["on"+evnt]=null;
					}
					
					friz.addEvent(obj[i],evnt,confirmInit);
				}
			}
		}
	}
	
	/*
		The function that initiates confirm popups for autoloaded
		confirm items
	*/
	
	function confirmInit(e){
		e = e ? e : window.event;
		var src = e.srcElement ? e.srcElement : e.target;
		
		while(!src.getAttribute("confirm")){
			src = src.parentNode;
		}
		
		if(src.getAttribute("confirm")==="true"){
			var msg = src.getAttribute("confmsg");
			btnConfirm.objRef = src;
			//popupInit(msg,"yesno","friz_info.png",0)
			addCall(msg,"yesno","friz_info.png",0);
		}
		
		e.preventDefault ? e.preventDefault() : e.returnValue = false;
		return false;
	}

	
	function popupInit(params){
		var message = params["message"] ? params["message"] : "An alert was called with no message.<br />Some sort of error, maybe?";
		var buttons = params["buttons"] ? params["buttons"] : "";
		var image = params["image"] ? params["image"] : "";
		var wait = params["wait"] ? params["wait"] : 0;
		//clearTimeout(popup_timer);
		if(typeof message == "object"){
			dialog_message.style.display="none";
			dialog_message.parentNode.insertBefore(message,dialog_message);
		} else {
			dialog_message.style.display="block";
			dialog_message.innerHTML = message;
		}
		
		if(image){
			dialog.style.backgroundImage="url('" + friz.path + "images/"+image+"')";
		} else {
			dialog.style.backgroundImage="";
		}
		
		switch(buttons) {
			case "ok":
				btnConfirm.style.display = "none";
				btnCancel.style.display = "inline";
				btnCancel.value = "Ok";
				btnCancel.style.textAlign="center";
				btnCancel.style.visibility="visible";
			break;
			
			case "yesno":
				btnConfirm.style.display = "inline";
				btnConfirm.value="Yes";
				btnConfirm.style.textAlign="center";
				btnConfirm.style.visibility="visible";
				btnCancel.style.display = "inline";
				btnCancel.value = "No";
				btnCancel.style.textAlign="center";
				btnCancel.style.visibility="visible";
			break;
			
			case "none":
				btnConfirm.style.display = "none";
				btnCancel.style.display = "none";
			break;
		}
		
		popup_timer = window.setTimeout(popup,wait);
	}
	
	function popup(){
        backdrop.style.display = "block";
        dialog.style.display = "block";
	    var ww = friz.windowWidth();
	    var wh = friz.windowHeight();
	    var sh = document.body.parentNode.scrollHeight;
	    var sw = document.body.parentNode.scrollWidth;
	    var st = document.body.parentNode.scrollTop;
	    var sl = document.body.parentNode.scrollLeft;
	    var dw = dialog.offsetWidth;
	    var dh = dialog.offsetHeight;
		backdrop.style.height = sh + "px";
		backdrop.style.width = sw + "px";
		var ts = 0.15;
		while(((wh*ts)+dh) > wh && (wh*ts) > 2){
			ts -= 0.01;
		}
		
		if(((wh*ts)+dh) > wh) {
			dialog.style.top = "2px";
			dialog.style.height = (wh - 5) + "px";
			dialog.style.overflowY = "scroll";
		} else {
		       dialog.style.top = (wh * ts) + "px";
		}
        dialog.style.left = ((ww/2) - (dw/2)) + "px";
	}
	
	function popupCancel(){
		clearTimeout(popup_timer);
		popupCalls.shift();
		if(popupCalls.length > 0){
			popupInit(popupCalls[0]);
		} else {
			backdrop.style.display="none";
			dialog.style.display="none";
			if(dialog_message.style.display=="none"){
				dialog_message.parentNode.removeChild(dialog_message.previousSibling);
				dialog_message.style.display="block";
			}
			dialog_message.innerHTML = "";
			btnConfirm.style.display="none";
			btnCancel.style.display="none";
		}
	}
	
	function popupConfirm(){
		//xmlRequest(confirmUrl,"");
		popupCancel();
		if(btnConfirm.objRef && btnConfirm.objRef.getAttribute("oldevnt")){
			if(typeof btnConfirm.objRef.getAttribute("oldevnt") == 'function'){
				btnConfirm.objRef.oldevnt();
			} else {
				eval(btnConfirm.objRef.getAttribute("oldevnt"));
			}
		} else {
			if(!btnConfirm.objRef.getAttribute("oldevnt") && btnConfirm.objRef.form && btnConfirm.objRef.getAttribute("type")=="submit"){
				btnConfirm.objRef.form.submit();
			} else {
				if(btnConfirm.objRef.tagName.toLowerCase()=="form"){
					btnConfirm.objRef.submit();
				}
			}
		}
		
	}
	
	return {
		call:function(message,buttons,image,wait){
			addCall(message,buttons,image,wait);
		},
		
		cancel:function(){
			popupCancel();
		},
		
		Init:function(){
		    Init();
		},
		
		reInit:function(){
			updateElements();
		},
		
		confirmInit:function(e){
			confirmInit(e);
		},
		
		get:function(url){
			friz.xmlhttp.call(url,'',xmlAlert);
		}
		
	};
}();