document.observe('dom:loaded',bindUI_page_action);
var app_progress
var files_load
function bindUI_page_action(){
	//setting all links
	$$('a.inner_link').invoke('observe','click',pa_action_inner_link);
	
	//starting SWFAddress
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
	
	//starting lightbox so we will have it handy
    Lightbox.init();
    
    
    
    
}


function create_json_menus(json, opt){
	//This function created the menus in the right places
	var p_in=null;
	//The vars enables us to present sub menus in another menu when one of the pages from it is selected
	if (typeof(opt)!='undefined' && opt){ //we have extra options
		if (opt.for_menu && opt.present_in){
			p_in=[opt.for_menu,opt.present_in]
		}
	}
	
	//first we find the menus that we have in the json
	var menus=[], t="", v="",w=false;
	for (var i=0,lim=json.size(); i<lim;i++){
		if (json[i]["pso"]==0){
			menus.push(json[i]["p_m"]);
		}
	}
	menus=menus.compact().uniq();
	
	//create ul elements for these menus, and change the unit in the menu to the element
	for (i=0,lim=menus.size(); i<lim;i++){
		var id="ul_menu" + menus[i]
		var class_name="menu" + menus[i]
		var t="<ul id='ul_menu" + menus[i] + "' class='ul_menu" + menus[i] + "'></ul>"
		if ($("holder_menu" + menus[i])){
			$("holder_menu" + menus[i]).update(t);
		}
	}
	
	//insert the li into the right places
	for (i=0,lim=json.size(); i<lim;i++){
		if (json[i]["pso"]==0){ //inserting main menus
			t="<li id='p_" + json[i]["pid"] + "'><a href=\"" + json[i]["pl"] + "\""
			if (json[i]["psl"]==0){ t+=" class='inner_link' "}
			t+=" rel='" + json[i]["pid"] + "'>" + json[i]["ptm"] + "</a></li>"
			if ($("ul_menu" + json[i]["p_m"])){
				$("ul_menu" + json[i]["p_m"]).insert({'bottom': t});
			}
		}else { //inserting submenus
			sub_menuid='ul_subof_p' + json[i]["pso"];
			if (!$(sub_menuid)){ //we need to create the sub element
				v="<ul id='" + sub_menuid + "'></ul>";
				if ($("p_" + json[i]["pso"])){
					$("p_" + json[i]["pso"]).insert({'bottom': v});
				}
			}
			
			//create the li
			t="<li id='p_" + json[i]["pid"] + "'><a href=\"" + json[i]["pl"] + "\""
			if (json[i]["psl"]==0){ t+=" class='inner_link' "}else{}
			t+=" rel='" + json[i]["pso"] + "'>" + json[i]["ptm"] + "</a></li>"
			
			//insert the li
			$(sub_menuid).insert({'bottom': t});
			
			//do we want to create a presentation sub menu?
			if (p_in!=null){
				sub_menuid='ul_subof_present' + json[i]["pso"];
				if (!$(sub_menuid)){ //we need to create the sub element
					v="<ul id='" + sub_menuid + "' class='sub_present" + p_in[1] + "' style='display:none;'></ul>";
					if ($('holder_menu' + p_in[1])){
						$('holder_menu' + p_in[1]).insert({'top': v});
					}
				}
				
				//insert the li
				$(sub_menuid).insert({'bottom': t});
			}
			
		}
		t=""
		v=""
	}

	
	//bind the menus
	for (i=0,lim=menus.size(); i<lim;i++){
		var id="ul_menu" + menus[i]
		if ($(id)){
			new ProtoFish(id, '200', 'hover', false, true, true);
		}
	}
	
	//bind the inner link to all menus
	
	
	//adding the functionality of the sub menu presentation
	if (p_in==null){
		$$('ul a.inner_link').invoke('observe','click',pa_action_inner_link);
	}else{
	
		$$('ul a.inner_link').each(function(item){
			$(item).observe('click',function(event){
				pa_action_inner_link(event);
				$$('ul.sub_present'+ p_in[1]).invoke('hide');
			});
		});
		
		
		css_rule='#holder_menu' + p_in[0] + ' ul.ul_menu' + p_in[0] + ' li ul';
		//alert(j_l);
		$$(css_rule).each(function(item){
			item=$(item).up(0).down(0);
			show_present_sub(item,p_in[1]);
		});
		css_rule='#holder_menu' + p_in[0] + ' ul.ul_menu' + p_in[0] + ' li ul li a';
		$$(css_rule).each(function(item){
			show_present_sub(item,p_in[1]);
		});
		
		css_rule='#holder_menu' + p_in[1] + ' ul.sub_present' + p_in[1] + ' li a';
		$$(css_rule).each(function(item){
			show_present_sub(item,p_in[1]);
		});
	}
}


function show_present_sub(item,p_in){
	$(item).stopObserving();
	$(item).observe('click', function(event){
		pa_action_inner_link(event);
		$$('ul.sub_present'+ p_in).invoke('hide');
		rel=this.readAttribute('rel');
		if ($('ul_subof_present' + rel)){
			$('ul_subof_present' + rel).show();
		}
	});
}


function pa_load_page(url, param){
	//we always send the g_id
	var g_id=getUrlVars()["g_id"].split("#").first();
	if (param){
		param+="&g_id=" + g_id
	}else{
		param="g_id=" + g_id
	}
	var t,p;
	new Ajax.Request(url, {
		parameters : param,
		method: 'post',
		onCreate: function(){
			$$('#maincol a.inner_link').invoke('stopObserving');
			t=window.setTimeout(function(){uploading_all()},1500);
			p=window.setTimeout(function(){
			uploading_all_off();
			prb_msg();
			SWFAddress.back();
			},10000);
		},
		onFailure: function(transport){
			uploading_all_off();
			Lightbox.hideBox();
			$('maincol').update(transport.responseText);
			window.clearTimeout(t);
			window.clearTimeout(p);
			prb_msg();
		},
		onSuccess: function(transport) {
			uploading_all_off();
			window.clearTimeout(t);
			window.clearTimeout(p);
			
			//remove all js that the previous page uploaded dynamically 
			$$('div.js_toload').each(function(item){
				pa_unloadjs($(item).innerHTML);
			});
			
			//update the page
			$('maincol').update(transport.responseText);
			
			
			//bind new inner_link
			$$('#maincol a.inner_link').invoke('stopObserving');
			$$('#maincol a.inner_link').invoke('observe','click',pa_action_inner_link);
			window.scrollTo(0,0);
			
			//check if we have js_toload and load it
			$$('div.js_toload').each(function(item){
				pa_loadjs($(item).innerHTML);
			});
			
			
			if ($('reg_only_page')){
				if ($F('reg_only_page')==1 && $('addthis')){
					$('addthis').hide();
				}
			}else{
				$('addthis').show();
			}
			
			
		},
		on302: function(transport){
			alert(transport.status);
		}
  	});
}

function first_page(){
	page_links=window.location.href.split("#/");
	pa_load_page(page_links[1]);
	//pa_load_page(window.location.href.split("#/"))
}

function pa_action_inner_link(event){
	Event.stop(event);
	var item=Event.findElement(event, 'a');
	var url=$(item).href;
	SWFAddress.setValue(url);
}


function pa_loadjs(jsarray){
	jsarray=jsarray.split(",")
	//load the script and check if it has been loaded already
	for (i=0,lim=jsarray.size(); i<lim;i++){
		filename = jsarray[i].substring(jsarray[i].lastIndexOf('/')+1)
		filename=filename.split(".").first();
		function_name="bindUI_" + filename
		if (eval("typeof(" + function_name + ")== 'function'")){//this means that the js is not loaded already
			eval(function_name + "()");	
		}else{
			LazyLoad.js(jsarray[i]);
		}
	}
}


function pa_unloadjs(jsarray){
	jsarray=jsarray.split(",")
	var targetelement="script";		//determine element type to create nodelist from
	var targetattr="src";			//determine corresponding attribute to test for

	for (i=0,lim=jsarray.size(); i<lim;i++){
		filename = jsarray[i].substring(jsarray[i].lastIndexOf('/')+1)
		filename=filename.split(".").first();
		
		var allsuspects=document.getElementsByTagName(targetelement)
		for (var x=allsuspects.length; x>=0; x--){ //search backwards within nodelist for matching elements to remove
			if (allsuspects[x] && allsuspects[x].getAttribute(targetattr)!=null && allsuspects[x].getAttribute(targetattr).indexOf(filename)!=-1)
				allsuspects[x].parentNode.removeChild(allsuspects[x]) //remove element by calling parentNode.removeChild()
		}
	}
 
}



// ---------------------SWFAddress changes -------------------------

function formatTitle(title) {
    //return (title != '/' ? ' / ' + toTitleCase(title.substr(1, title.length - 2).replace(/\//g, ' / ')) : '');
    return "Registration Site"
}

function toTitleCase(str) {
    return str.substr(0,1).toUpperCase() + str.substr(1).toLowerCase();
} 


function handleChange(event) {
    
	var index, rel, links = $$('a'), path = event.path;
    if (path.substr(path.length - 1) != '/') {
        path += '/';
    }
    
    for (var i = 0, l, link; link = links[i]; i++) {
        index = link.rel.indexOf('?');
        rel = (index > -1) ? link.rel.substr(0, index) : link.rel;
        //link.className = (rel == path) ? 'selected' : '';
    }
    
    // get the current URL
	var url = event.value;
	//get the parameters
	var params='';
	if (url.match(/\?(.+)$/)!=null){
		params = RegExp.$1;
	}
 
    path=path.substring(1,path.length-1);
    pa_load_page(path, params);
    //alert(event.parameters);
    SWFAddress.setTitle(formatTitle(path));
    
}

function copyLink() {
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData('Text', SWFAddress.getBaseURL() + SWFAddress.getValue());
    } else {
        alert('Unsupported browser.');
    }
}




//--------------------------- FORMS UTILITIES ---------------------------------
function submit_ajax(form_id){
	var t,p;
	//if there is a file that is uploading we wait it to finish, otherwise we can move forward
	if (files_load && typeof(files_load.is_finished)=='function'){
		if (!files_load.is_finished()){
			msg="<div class='prb_msg_error'>The files have not finished uploading.<br>"
			msg+="Please wait until the files finish uploading and then try again."
			msg+="</div>";
			msg+="<div class='prb_msg_errorOK'><a href='#' onclick='Event.stop(event);Lightbox.hideBox()'>OK</a></div>";
			Lightbox.showBoxString(msg);
			return false;
		}
	}
	
	url=$(form_id).action;
	
	new Ajax.Request(url, {
		parameters : $(form_id).serialize(),
		method: 'post',
		onCreate: function(){
			t=window.setTimeout(function(){uploading_all("Processing ...")},500);
			p=window.setTimeout(function(){
			uploading_all_off();
			prb_msg();
			},16000);
		},
		onFailure: function(transport){
			uploading_all_off();
			Lightbox.hideBox();
			window.clearTimeout(t);
			window.clearTimeout(p);
			$('maincol').update(transport.responseText);
			prb_msg();
		},
		onSuccess: function(transport) {
			uploading_all_off();
			window.clearTimeout(t);
			window.clearTimeout(p);
			
			var json=transport.responseText.evalJSON(true);
			var send_to=json[0]["send_to"];
			var cl=json[0]["cl"];
			var sl=json[0]["sl"];
			var errors=json[0]["errors"];
			var send_message=json[0]["send_message"];
			
			if (errors){ //if there where errors or a message we wanted to send to the user we send it
				msg="<div class='prb_msg_error prb_msg_black'>The server was not able to complete the transaction :-(<Br>"
				msg+="This is the message that was returned:<br><br>"
				msg+="<div class='prb_msg_error_inner'>" + errors + "</div>";
				msg+="</div>";
				msg+="<div class='prb_msg_errorOK'><a href='#' onclick='Event.stop(event);Lightbox.hideBox()'>OK</a></div>";
				Lightbox.showBoxString(msg);
				//find the submit button and disable it
				$$('input[type="submit"]').invoke('enable');
		
			}
			
			if (send_message){
				$('maincol').update(send_message);
				window.scrollTo(0,0);
				return false;
			}
			
			//var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
			//regexp.test(send_to) || 
			if (sl==1){
				//we are sending the user to a new page not view ajax
				newURL = send_to
				window.location=newURL;
			}else{
				// we add an extra / since the system does not give it
				SWFAddress.setValue("/" + send_to);
			}
			
			if (cl){
				app_progress.setPercentage(cl);
			}
			
			
			
			
		}
  	});
}



function uploading_all(text){
	if (!text){ text="Loading... ";}
	var str="<div id='loading_all_box'>";
		str+="<img src='/reg/imgs/big_loading.gif'><Br>" + text + "</div>";
	$(document.body).insert({'top':str});
	Element.show('overlay');
	Lightbox.center('loading_all_box');
	Lightbox.bind_stop();
	return false;
}

function uploading_all_off(){
	if ($('loading_all_box')){
		$('loading_all_box').remove();
		$('overlay').hide();
		Lightbox.bind();
	}
}


function prb_msg(){
	msg="<div class='prb_msg_error'>This seems to be taking a little longer than expected :-(<Br>"
	msg+="Please wait a few more seconds and if nothing happens, try the action again.<br>"
	msg+="If the problem persists, please contact us so we can fix it right away.</div>";
	msg+="<div class='prb_msg_errorOK'><a href='#' onclick='Event.stop(event);Lightbox.hideBox()'>OK</a></div>";
	Lightbox.showBoxString(msg);
}


function lightbox_error(txt){
	msg="<div class='prb_msg_error'>" + txt + "</div>"
	msg+="<div class='prb_msg_errorOK'><a href='#' onclick='Event.stop(event);Lightbox.hideBox()'>OK</a></div>";
	Lightbox.showBoxString(msg);
}