// --------------------------------------------------------------------------- validate
function VEMAIL(email)
{
	validformat = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
	if (validformat.test(email))
	{
		return true;
	}
	else
	{
		return false;
	}
}
function MIN(value,mlength){if(value.length<mlength){return false;}else{return true;}}
function MAX(value,mlength){if(value.length>mlength){return false;}else{return true;}}
function NUM(v){v = v.replace('.', ''); if(v.search("[^0-9]")==-1){return true;}else{return false;}}
function CNUM(v){c=0;for(i=0;i<v.length;i++){if(NUM(v.charAt(i))==true){c++;}}return c;}
function ALPHA(v){if(v.search("[^A-Za-z]")==-1){return true;}else{return false;}}
function ALPHANUM(v){if(v.search("[^A-Za-z0-9]")==-1){return true;}else{return false;}}
function EXT(v){return v.substring(v.lastIndexOf('.')+1,v.length);}

function VEXT(v,safe){validExt=false; ext=v.substring(v.lastIndexOf('.')+1,v.length); ext=ext.toLowerCase(); safe=safe.toLowerCase();	safe=safe.split(","); for(arrIndex in safe){if(safe[arrIndex]==ext){validExt=true;}} return validExt;}

function RESTRICT(v,list){if(v.search("[/"+list+"/]")==-1){return true;}else{return false;}}
function VWEBSITE(website){if(website.substring(0,7)!="http://"){return true;}else{return false;}}
function VFILENAME(v){validformat=/^([a-zA-Z0-9])+([a-zA-Z0-9_\.\-])+([a-zA-Z0-9])+$/; if(validformat.test(v)&&v.length<31&&v.length>3){return true;}else{return false;}}
function VFQDN(v){parts=v.split("."); valid=true; validformat=/^([a-zA-Z0-9\-])+$/; for(i in parts){ if(i==0&&parts[i]=="www"){valid=false;} if(validformat.test(parts[i])==false){valid=false;} } if(parts.length<2){valid=false;} if(v.length>255||v.length<3){valid=false;} return valid; }
function DECIMAL(v,d){
vparts=v.split(".");
switch(true){
case vparts.length>2:return false; break;
case (vparts.length>1&&vparts[1].length>d):return false; break;
case !NUM(vparts[0]):return false; break;
case (vparts.length>1&&!NUM(vparts[1])):return false; break;
default: return true;
}//switch(true){
}//function DECIMAL(v,d){

// --------------------------------------------------------------------------- GID
function GID(id){element=document.getElementById(id);return element;}
// endGID

// --------------------------------------------------------------------------- GXY
function GXY(xy){
var x,y;
if (self.innerHeight) // all except Explorer
{
x = self.innerWidth;
y = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
x = document.documentElement.clientWidth;
y = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
x = document.body.clientWidth;
y = document.body.clientHeight;
}
if(xy=='x'){return x;}else{return y;}
}

// --------------------------------------------------------------------------- win
sizepos_options=new Array("width=","height=","top=","left=");
function WIN(f,n,sizepos,attributes){
opt_string=new Array();

sizepos=sizepos.split(".");
for(i in sizepos){
opt_string.push(sizepos_options[i]+sizepos[i]);
}

attributes=attributes.split(".");
for(i in attributes){
opt_string.push(attributes[i]+"=1");
}

opt_string=opt_string.toString(",");
window.open(f,n,opt_string);
}
//eg WIN("upload.gif.htm","uploadprogress","300.200.300.400","scrollbars.resizable");

function openuploadgif(){
HTTP_HOST=location.toString();
HTTP_HOST=HTTP_HOST.substring(0,HTTP_HOST.indexOf("/",7));
win = window.open("/resources/elements/uploadgif.php", "dep", "height=160,width=400,top=320px,left=320px");
onunload=closeuploadgif;
}

function closeuploadgif(){
if (win && win.open && !win.closed) win.close();
}

// --------------------------------------------------------------------------- validation
FORMRULES=new Array();
PREVALIDATEFUNCTION=null;
PREPOSTFUNCTION=null;
REGEXRULE=new Array();
REGEXERROR=new Array();
function MSP_validate(frmnumber){

if(PREVALIDATEFUNCTION!=null){PREVALIDATEFUNCTION();}
if(frmnumber==null){frmnumber=0;}
formerrors=0;
//loop thru elements
for(i=0;i<document.forms[frmnumber].elements.length;i++){
frmname=document.forms[frmnumber].elements[i].name;
frmvalue=document.forms[frmnumber].elements[i].value;
frmelement=document.forms[frmnumber].elements[i];
frm_type = document.forms[frmnumber].elements[i].type;

//find rule
formrule=null;
for(r=0;r<FORMRULES[frmnumber].length;r++){
if(FORMRULES[frmnumber][r][0]==frmname){formrule=r;}
}//end find rule

//apply rule
if(formrule!=null){
rules=FORMRULES[frmnumber][formrule][1].split("|");
//test for required
required=false;
for(testrule in rules){
rule=rules[testrule].split(":"); 
if(rule[0]=="req"){required=true;}
}//for(testrule in rules){

//find and apply rule
//alert(formrule+" "+frmname+" "+rules);
output="";
for(applyrule in rules){
rule=rules[applyrule].split(":");
rulename=rule[0];
rulevars=rule[1];
//alert(rulename)
switch(rulename){
case "req":
if(!MIN(frmvalue,1)){output+=" required";}
break;	

case "min":
if(!MIN(frmvalue,rulevars)){output+=" min("+rulevars+")";}
break;	

case "max":
if(!MAX(frmvalue,rulevars)){output+=" max("+rulevars+")";}
break;

case "minval":
if(Number(frmvalue)<Number(rulevars)){output+=" min value("+rulevars+")";}
break;

case "maxval":
if(Number(frmvalue)>Number(rulevars)){output+=" max value("+rulevars+")";}
break;

case "email":
if((frmvalue!=""&&!VEMAIL(frmvalue))||required&&!VEMAIL(frmvalue)){output+=" invalid";}
break;

case "website":
if((frmvalue!=""&&VWEBSITE(frmvalue))||required&&VWEBSITE(frmvalue)){output+=" must contain http://";}
break;

case "fqdn":
if(!VFQDN(frmvalue)){output+=" invalid fqdn";}
break;

case "num":
if(!NUM(frmvalue)){output+=" numbers only";}
break;

case "dec":
if(!DECIMAL(frmvalue,rulevars)){output+=" "+rulevars+" decimal(s) only";}
break;

case "alpha":
if(!ALPHA(frmvalue)){output+=" letters only";}
break;

case "alphanum":
if(!ALPHANUM(frmvalue)){output+=" letters or numbers only (no spaces)";}
break;

case "ext":
if(frmvalue!=""&&!VEXT(frmvalue,rulevars)){output+=" invalid - accepted("+rulevars+")";}
if (frmvalue != '')
{
	PREPOSTFUNCTION = openuploadgif;
}

break;

case "restrict":
if(!RESTRICT(frmvalue,rulevars)){output+=" char's not allowed "+rulevars;}
break;

case "check":
if(frmelement.checked==false){output+=" "+rulevars;}
break;

case "filename":
	regex = new RegExp(/[0-9a-z\.\-\_]/ig);
	if(!regex.test(frmvalue)){output+=" invalid filename";}
break;

case "regex":
/*
example [declare the following before FORMRULES
REGEXRULE[0]="^[abc]"; // frmvalue begins with any of abc // quotes are delimiter
REGEXERROR[0]="Warning"; // customized warning 
FORMRULES[0]=new Array(
['name','regex:0']);
*/
regex=new RegExp(REGEXRULE[rulevars]);
if(!regex.test(frmvalue)){output+=" "+REGEXERROR[rulevars];}
break;

case "allowed":
regex=new RegExp(rulevars);
allowed=true;
for(ai in frmvalue){
if(!regex.test(frmvalue[ai])){output+=" allowed char's are "+rulevars.substring(1,(rulevars.length-1)); break;}//if(!regex.test(frmvalue[i])){
}//for(i in str){
break;

case "unique":
rulevars=rulevars.split(",");
foundmatch=0;
for(ri=0;ri<rulevars.length;ri++){if(rulevars[ri].toLowerCase()==frmvalue.toLowerCase()){foundmatch++;}}
if(foundmatch>0){output+=" not unique ";}
break;
}//switch

}//applyrule
if(output!=""){
formerrors++; 
GID(frmname+"_error").innerHTML=output;//img_false+output;
GID(frmname+"_error").className="errorcellerror";
}else{
GID(frmname+"_error").innerHTML="valid";//img_true;
GID(frmname+"_error").className="errorcellvalid";
}
}//end apply rule

	if (frm_type == 'file' && frmvalue != '')
	{
		PREPOSTFUNCTION = openuploadgif;
	}

}//end loop

if(formerrors==0){
if(PREPOSTFUNCTION!=null){PREPOSTFUNCTION();}
if (REQUIREUNIX)
{
	now = new Date();
	unix = now.getTime() / 1000;
	form = document.forms[0];
	valid = document.createElement('input');
	valid.type = 'hidden';
	valid.name = 'UNIX' + (now.getMonth() + 1) + now.getDate();
	valid.value = Math.round(unix);
	form.appendChild(valid);
}
return true;
}else{
return false;
}
}

/* validation usage 
example
<script language="javascript" type="text/javascript">
<!--
FORMRULES[0]=new Array(
['name','min:5|max:30'],
['email','email'],
['email','min:5|max:50|email|num|alpha|alphanum|ext:jpg,png|restrict:\'\$abc']
);
img_true="<img src='../../assets/images/validation/true.gif'>";
img_false="<img src='../../assets/images/validation/false.gif'>";
-->
</script>

<form action="../action.php" name="apple" method="post" onSubmit="return MSP_validate()">
<table align="center" width="400px" style="padding:100px 0px">

<tr><td nowrap="nowrap"><input name="name" type="text"><span id="name_error" class="error_block"></span></td></tr>
<tr><td nowrap="nowrap"><input name="email" type="text"><span id="email_error" class="error_block"></span></td></tr>
<tr><td><input name="submit" type="submit"></td></tr>
</table>
</form>
end example

call function with form index number (first form is 0, assumes 0 if not given) for use with multiple forms
FORMRULES array element usage
['form name','testfor:optional variables|a:b|etc..']

options [x=integer,na=,ext=dotless extension]
min:x
max:x
email
alpha
num
alphanum
ext:ext,ext,ext
restrict:[string of restricted characters] escape the following \ | () [ { ^ $ * + ? .

must define 
ing_true, img_false - relative to self/document
must have 
error display elements - format for id is inputname_error where inputname is the EXACT name of the input 
being tested


*/
loadAfterMenu = new Array();
if(typeof(MENUCLASSES)=="undefined"){MENUCLASSES=new Array("level01up","level02up","level03up");}
onload=MENUEVENTS;
function MENUEVENTS(){
targetElement=document.getElementsByTagName('div');
for(i=0;i<targetElement.length;i++){
for(mc in MENUCLASSES){
//if(targetElement[i].className==MENUCLASSES[mc]){
if(targetElement[i].className.search(MENUCLASSES[mc])>=0){
targetElement[i].onmouseover=HOVER;
targetElement[i].onmouseout=OUT;
//alert(targetElement[i].innerHTML);
}//if(targetElement[i].className==MENUCLASSES[mc]){
}//for(mc in MENUCLASSES){
}//for(i=0;i<targetElement.length;i++){

targetElement=document.getElementsByTagName('button');
for(i=0;i<targetElement.length;i++){
targetElement[i].onmouseover=HOVER;
targetElement[i].onmouseout=OUT;
}//for

if (loadAfterMenu)
{
    for (i = 0; i < loadAfterMenu.length; i++)
    {
        eval(loadAfterMenu[i]);
    }
}
}//fun
function HOVER(){this.className=this.className.replace(/up/g,"ov");} 
function OUT(){this.className=this.className.replace(/ov/g,"up");}


function FINDRADIO(radioobjects){for(i=0;i<radioobjects.length;i++){if(radioobjects[i].checked){return radioobjects[i].value; i=radioobjects.length;}}}

function NUMBERFORMAT(integer,roundto,trailing){
//round to decimal
factor=new Number(Math.pow(10,roundto));
integer=Math.round(integer*factor)/factor;
//format to decimal
if(trailing!=0){
integer=new String(integer);
if(integer.indexOf(".")==-1){integer+=".";}
while(integer.substring(integer.indexOf("."),integer.length).length<trailing+1){integer+="0";}
}//if(trailing!=0){
return integer;
}//function NUMBERFORMAT(integer,places,force){

function MSP_colorpicker(path, target){
switch(path){
case "default":path="/resources/javascripts/colorpicker/swatch.php";break;
case "testing":path="swatch.php";break;
case "editor":path="../../../resources/javascripts/colorpicker/swatch.php";break;
}//switch(path){
topval=(screen.availHeight/2)-130;
leftval=(screen.availWidth/2)-85;
window.open(path+"?target="+target,"","top="+topval+"px,left="+leftval+"px,width=290px,height=350px,status=yes,resizable=1,toolbar=no,menubar=no,scollbars=yes,location=0");
}//function MSP_colorpicker(path,target){

function swatch_color_picker(swatch_name)
{
	MSP_colorpicker('default', 'swatch_update_color(\'' + swatch_name + '\', color)');
}

function swatch_update_color(swatch_name, color)
{
	GID(swatch_name + '_swatch').style.backgroundColor = color;
	document.forms[0].elements[swatch_name].value = color.substring(1);
}

function MSP_imagepicker(path,target){
switch(path){
case "default":path="../resources/javascripts/imagepicker/browser.php";break;
case "testing":path="browser.php";break;
case "editor":path="../../../resources/javascripts/imagepicker/browser.php";break;
}//switch(path){
topval=(screen.availHeight/2)-180;
leftval=(screen.availWidth/2)-300;
window.open(path+"?target="+target,"","top="+topval+"px,left="+leftval+"px,width=600px,height=400px,status=yes,scrollbars=yes,toolbar=no,menubar=no,location=0");
}

function make_num(el){if(isNaN(el.value)){el.value=1;}}//function make_num(el){

function MSP_getcookie(cookiename){
foundcookie=false;
storedcookies=document.cookie.split(";");
for(i in storedcookies){
storedpair=storedcookies[i].split("=");
storedcookiename=storedpair[0].replace(" ","");
if(storedcookiename[0]==" "){storedcookiename=storedcookiename.substr(1);}
storedcookievalue=storedpair[1];
if(storedcookiename==cookiename){foundcookie=storedcookievalue;}
}//for(i in storedcookies){
return foundcookie;
}//function MSP_getcookie(cookie){

function XMLAJAX(request, response)
{
	//request.show_request = 1;
	//"http://"+location.host+
	request_handler = '/resources/phpscripts/ajax/control.php?';
	request_handler += 'method=' + request.method;
	
	for (i = 0; i < request.pairs.length; i ++)
	{
		request_handler += '&' + request.pairs[i].name + '=' + request.pairs[i].value;
	}
	
	request_handler += '&cache_clear=' + Math.floor(Math.random()*1000);
	
	if (request.show_request)
	{
		prompt('Request', location.host + request_handler);
	}
	
	var xmlhttp_object;
	try{xmlhttp_object=new XMLHttpRequest();}catch(e){
	try{xmlhttp_object=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){
	try{xmlhttp_object=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){
	xmlhttp_object=false;
	}//try{ajax_object=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){ 
	}//try{ajax_object=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){
	}//try{ajax_object=new XMLHttpRequest();}catch(e){
	xmlhttp_object.onreadystatechange=function(){
	if(xmlhttp_object.readyState==4){
	response(xmlhttp_object.responseText);
	}//if(xmlhttp_object.readyState==4){
	}//xmlhttp_object.onreadystatechange=function(){
	xmlhttp_object.open("GET", request_handler, true);
	xmlhttp_object.send(null);
}
/*
simple local example
pairs = [
{"name":"local", "value":"action"},
{"name":"org", "value":"test"}
];
create DOC_ROOT/assets/phpscripts/ajax/action.php
XMLAJAX({"method":"local", "pairs":pairs}, return_function);
*/

function get_lookup_value_off(lookup)
{
	switch(lookup.mode)
	{
		case "single":
			//target = document.forms[0].elements[lookup.fieldid];
			search_value = document.forms[0].elements['F' + lookup.dependancy.id].value;
			
			alert(search_value);
			pairs=[
			{"name":"mode","value":lookup.mode},
			{"name":"sourcefield","value":lookup.fieldid},
			{"name":"searchvalue","value":searchvalue}
			];
		break;
		case "all":
		fieldvalues="";
		for(i=0;i<lookup.fields.length;i++){
		element=document.forms[0].elements[lookup.fields[i]];
		switch(true){
		case (element.length>1&&element[0].type=="radio"):
		value="";
		for(r=0;r<element.length;r++){
		if(element[r].checked){value=element[r].value; r=element.length;}
		}//for(r=0;r<element.length;r++){
		name=element[0].name;
		break;
		default:
		value=element.value;
		name=element.name;
		}//switch(true){
		
		field_values+='i:'+lookup.fields[i]+';s:'+value.length+':"'+value+'";';
		}
			
		field_values = 'a:' + lookup.fields.length + ':{' + field_values + '}';
		prompt(field_values, field_values);
		pairs=[
		{"name":"mode","value":lookup.mode},
		{"name":"dataset","value":lookup.dataset},
		{"name":"fieldvalues","value":fieldvalues}
		];
		break;
	}
	
	//XMLAJAX({"method":"datasetlookup", "pairs":pairs}, fill_lookup_value);

}

function fill_lookup_value_off(result)
{
	alert(result);
/*
errors=new Array();
result=eval('('+result+')');
for(i=0;i<result.fieldvalues.length;i++){
document.forms[0].elements["field"+result.fieldvalues[i].id].value=unescape(result.fieldvalues[i].value);
if(result.fieldvalues[i].error){errors.push(result.fieldvalues[i].name+" Returned "+result.fieldvalues[i].error);}
}//for(i=0;i<result.fieldvalues.length;i++){
if(errors.length>0){alert(errors.join("\n"));}
*/
}//function fill_lookup_value(result){

function set_custom_option(target,guide,regex,error){
if(target.value=="custom"){
option=null;
while(option==null){
option=prompt(guide);
if(option==null){option=false;}
if(!regex.test(option)){alert(error); option=null;}
}//while(!option){

for(i=0;i<target.length;i++){
if(option==target.options[i].value){
target.options[i].selected="selected";
option=false;
}//if(option==target.options[i].value){
}//for(i=0;i<target.length;i++){

if(option){
target.options[target.length-1]=new Option(option,option);
target.options[target.length-1].selected="selected";
target.options[target.length]=new Option("custom","custom");
}//if(option){
}//if(target.value=="custom"){
}//function set_custom_option(target,guide,regex,error){


function autoplay_mp3(){
//eraseCookie("autoplay_window");
if(readCookie("autoplay_window")==null){
winheight=15;
winwidth=500;
winleft=(GXY('x')/2)-(winwidth/2);
wintop=(GXY('y')/2)-winheight-200;
window.open("/resources/elements/mp3.php","autoplay","height="+winheight+",width="+winwidth+",left="+winleft+",top="+wintop);
createCookie("autoplay_window","open",1);
}//if(readCookie("autoplay_window")==""){

}//function autoplay_mp3(){

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}//function createCookie(name,value,days) {

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}//function readCookie(name) {

function eraseCookie(name) {
createCookie(name,"",-1);
}//function eraseCookie(name) {


function toggle(el,status){
switch(status){
case "show":
GID(el).style.visibility="visible";
GID(el).style.position="relative";
break;
case "hide":
GID(el).style.visibility="hidden";
GID(el).style.position="absolute";
break;
}//switch(status){
}//function toggle(el,status){

function EMPTYNODE(node){
node=GID(node);
while(node.hasChildNodes()){
node.removeChild(node.firstChild);
}//while (node.hasChildNodes()){
}//function EMPTYNODE(node){

function getGetKey(getKey)
{
    getValue = false;
    getString = location.search.substr(1);
    keyPairs = getString.split('&');
    
    for (i in keyPairs) 
    {
        getArray = keyPairs[i].split('=');
        if (getArray[0] == getKey) 
        {
            getValue = getArray[1];
        }
    }
    return getValue;
}

function parse_query(string)
{
	get = new Object();
	pairs = string.split('&');
	for (i in pairs)
	{
		pair = pairs[i].split('=');
		eval("get." + pair[0] + " = '" + pair[1] + "'");	
	}

	return get;
}

function darkenScreen(mode)
{
    if (mode)
    {
        div = document.createElement('div');
        div.style.height = (document.body.scrollHeight + 50) + 'px';
        div.style.width = '100%';
        div.style.left = 0;
        div.style.top = 0;
        div.style.position = 'absolute';
        div.style.zIndex = 10;
        div.style.background = 'url(/resources/images/misc/' + mode + 'percentblack.png)';
        div.id = 'darkenScreen';
        //div.onclick = testclick;
        document.body.appendChild(div);
    }
    else
    {
        document.body.removeChild(GID('darkenScreen'));
    }   
}

String.prototype.toCapitalCase = stringCapitalize;
function stringCapitalize()
{
	words = this.split(' ');
	thisString = new Array();
	for (i in words)
	{
		thisWord = new Array();
		word = words[i].split('');
		for (x in word)
		{
			if (x == 0)
			{
				thisWord.push(word[x].toUpperCase());
			}
			else
			{
				thisWord.push(word[x]);
			}			
		}
		thisString.push(thisWord.join(''));
	}
	
	thisString = thisString.join(' ');
	return thisString;
}

function confirm_delete_check(el, notice)
{
	if (!confirm('Do you really want to delete ' + notice + '?'))
	{
		el.checked = '';	
	}

}

function custom_option(el, regex, warning)
{
	if (el.value == 'custom')
	{		
		switch (regex)
		{
			case 'int':
				regex = '[0-9]';
				warning = 'integers only';
			break;
		}
		
		regex = new RegExp(regex);
		val = false
		while (val == false && val != null)
		{
			val = prompt('enter custom value');	
			
			switch (true)
			{
				case val == null:
					el.options[0].selected = 'selected';
				break;
				
				case regex.test(val) == false:
					val = false;
					alert('ERROR :: ' + warning);
				break;
				
				default:
					el.options[el.length] = new Option(val, val);
					el.value = val;
				break;				
			}
		}
	}
}

depends_old = [
		   {"name":"style", 
		   	"inputs":[
					  {"value":"table", "id":["sortable"]}, 
					  {"value":"list", "id":["columns"]}, 
					  {"value":"calendar", "id":["options[calendar][showtime]"]}
					  ]
			},			
		   {"name":"oprhabed", "inputs":"list"}
		   ];

function show_input_options(el)
{
	active = false;
	for (i in depends)
	{
		if (depends[i].name == el.name)
		{
			active = depends[i].inputs;
		}
	}
	
	if (active)
	{
		for (i in active)
		{
			if (active[i].value == el.value)
			{
				visibility = 'visible';
				position = 'relative';
			}
			else
			{
				visibility = 'hidden';
				position = 'absolute';	
			}	
			
			for (e in active[i].id)
			{		
				id = active[i].id[e] + '_input_container';
				if (GID(id))
				{
					GID(id).style.visibility = visibility;
					GID(id).style.position = position;	
				}
			}
		}
	}
}


function image_picker(target)
{
	top_value = (screen.availHeight / 2) - 180;
	left_value = (screen.availWidth / 2) - 300;
	
	url = '/resources/javascripts/imagepicker/browser.php?target=' + target;
	
	win_options = 'top=' + top_value + 'px,' +
					'left=' + left_value + 'px,' +
					'width=600px,' +
					'height=400px,' +
					'status=yes,' +
					'scrollbars=yes,' +
					'toolbar=no,' +
					'menubar=no,' +
					'location=0';
					
	window.open(url, 'file_picker', win_options);
}

control_select_file_object = new Object();

function update_file_browser(file)
{
	element = control_select_file_object.element;
	controller = control_select_file_object.controller;
	full_file_path = '/assets/uploads/' + file;
	document.forms[0].elements[element].value = full_file_path;
	label = controller.options[0].value;	
	controller.options[0] = new Option(label + ' [' + file + ']', label);
	reset_options = ["select", "preview", "remove"];
	for (i in reset_options)
	{
		option = new Number(i) + 1;
		control = reset_options[i];
		controller.options[option] = new Option(control, control);
	}
}

function control_file_browser(controller, element)
{
	switch (controller.value)
	{
	case 'select':
		control_select_file_object.element = element;
		control_select_file_object.controller = controller;
		image_picker('update_file_browser');
	break;
	
	case 'preview':	
		preview_image(document.forms[0].elements[element].value);
	break;
	
	case 'remove':
		document.forms[0].elements[element].value = '';
		label = controller.options[0].value;		
		controller.options[0] = new Option(label + ' [none]', label);
		controller.remove(2);
		controller.remove(2);
	break;		
	}
	
	controller.selectedIndex = 0;	
}

function destroy_node(node)
{
	while (node.hasChildNodes())
	{
		node.removeChild(node.firstChild);
	}
	
	node.parentNode.removeChild(node);
}

function get_center_pos(object)
{
	pos = new Object();
	pos.left = (GXY('x') / 2);
	pos.left = pos.left - (object.width / 2) + 'px';
	
	pos.top = (GXY('y') / 2);
	pos.top = pos.top - (object.height / 2) - 100 + 'px';

	return pos;
}

function preview_image(image)
{
	darkenScreen(70);
	div = document.createElement('div');
	div.style.position = 'absolute';	
	div.style.background = '#FFFFFF';
	div.style.padding = '30px';
	div.style.border = '1px #000000 solid';
	div.style.zIndex = GID('darkenScreen').style.zIndex + 1;
	div.onclick = function ()
	{
		darkenScreen(); 
		destroy_node(this);
	}
	
	img = document.createElement('img');
	img.src = image;
	
	pos = get_center_pos(img);
	div.style.left = pos.left;
	div.style.top = pos.top;
	close_notice = document.createElement('div');
	close_notice.style.textAlign = 'center';
	close_notice.style.cursor = 'pointer';
	close_notice.style.paddingTop = '30px';
	close_notice.appendChild(document.createTextNode('click to close'));

	div.appendChild(img);	
	div.appendChild(close_notice);	
	
	document.body.appendChild(div);
}

function inline_search_query(event, search_page, input_id)
{	
	if (is_key(event, 'enter') || event == 'click')
	{
		location = search_page + '?q=' + GID(input_id).value;
	}
}

function is_key(event, key)
{
	var code = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	switch (key)
	{
	case 'enter':
		if (code == 13)
		{
			return true;
		}
	break;
	}
	
	return false;
}

function create_element(type, name)
{
	var element = null;
	
	element = document.createElement('<' + type + ' name="' + name + '">');
	
	if (!element || element.nodeName != type.toUpperCase())
	{
		element = document.createElement(type);
		element.name = name;
	}
	
	return element;
}

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=true;this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

