// Pop Up Window

var showImage ;

function popUp(image) {	
	image = image.replace('-thumb.', '-full.') ;
	thisImage = new Image() ;
	thisImage.src = (image) ;
	popUpResize(image) ;
}

function popUpResize(image) {
	if((thisImage.width != 0) && (thisImage.height != 0)) {
		popUpDisplay(image) ;
	}
	else {
		doResize = "popUpResize('"+image+"')" ;
		resizeDelay = setTimeout(doResize, 20) ;
	}
}

function popUpDisplay(image) {
	newWidth = thisImage.width + 20 ;
	newHeight = thisImage.height + 20 ;
	popUpDim = "width="+newWidth+",height="+newHeight ;
	showImage = window.open(image, "popUp", popUpDim+", resizable=1, scrollbars=1") ;
}

// Cookie Functions

function setcookie(c_name, c_value, c_expire, c_path, c_domain, c_secure) {
	// c_expire unit is seconds
	
	//need to check to see if a cookie exists with the same name since it will not automatically overwrite it. 
	
	cookie_value = c_name+"="+escape(c_value) ;
	
	if (c_expire == null) {
		cookie_value += "" ;
	}
	else {
		c_expire = c_expire / (60 * 60 * 24) ;
		var exdate=new Date() ;
		exdate.setDate(exdate.getDate()+c_expire) ;
		cookie_value += "; expires="+exdate.toGMTString() ;
	}
	
	if (c_path != null) {
		cookie_value += "; path="+escape(c_path) ;
	}
	
	if (c_domain != null) {
		cookie_value += "; domain="+escape(c_domain) ;
	}
	
	if (c_secure != null && c_secure != false && c_secure != 'false') {
		cookie_value += "; secure" ;
	}
		
	document.cookie = cookie_value ;
}

function getcookie(c_name) {
	if (document.cookie.length>0) {
		c_start = document.cookie.indexOf(c_name + "=") ;
		
		if (c_start != -1) { 
			c_start = c_start + c_name.length+1 ; 
			c_end = document.cookie.indexOf(";",c_start) ;
			
			if (c_end == -1) {
				c_end = document.cookie.length ;
			}
			
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	
	return null;
}

// String Functions

function replaceAll(find, replace, string) {
	while (string.search(find) >= 0) {
		string = string.replace(find, replace) ;
	}
	
	return string ;
}

function validateFile(e, ext) {
	var ok = false ;
	var ext_str = '' ;
	
	$H(ext).each(function(i) {
		ext_str = ext_str+"."+i.key+"\r\n" ;
		
		if (e.value.toLowerCase().search("."+i.key) != -1) {
			ok = true ;
		}
	}) ;
	
	if (ok != true) {
		alert("This file must be in one of the following formats:\r\n"+ext_str) ;
		regenInput(e) ;
	}
}

function regenInput(e) {
	e.value = "" ;
	var n = e.cloneNode(true);
	e.parentNode.insertBefore(n, e) ;
	e.parentNode.removeChild(e) ;
}

// Ajax Functions

/* PROTOTYPE AJAX EXAMPLE 

function functionName(vars) {
	// var vars = {} ;
	vars["ajax"] = 1 ;
	
	var url = "/myurl.php" ;
	
	new Ajax.Request(url, {
		parameters : vars, 
		onSuccess: function (req) {
			var response = req.responseText ;
			var json = req.responseJSON ;
			
			alert(response) ;
		}, 
		onFailure: function (req) {
			alert("Connection failed") ;
		}
	}) ;
}
*/

// DOM functions 

function insertAfter(referenceNode, newNode) {
	referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling) ;
}

// php javascript functions (see javascript_php.js)

function urlencode( str ) {
                             
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

// Button Effect 

function upEffect(cur){
	if(document.getElementById) {
		cur.className='button_up' ;
	}
}

function normalEffect(cur){
	if(document.getElementById) {
		cur.className='button' ;
	}
}

// Window functions

function popup(url, title, options) {
	var newWin = window.open(url, title, options) ;
	
	if(!newWin) {
		newWin = window.open('',title, options);
		newWin.location.href = url;
	}
	
	return newWin ;
}

function resizeWin(e) {
	if(document.all) {
		winHeight=document.all[e].offsetHeight;
		winWidth=document.all[e].offsetWidth;
	}
	window.resizeTo(winWidth+20,winHeight+20);
}

function preview(file, nw) {
	file = file.replace('-thumb.', '-full.') ;
	file = file.replace('_thumb.', '_full.') ;
	
	var vars = {} ;
	vars["ajax"] = 1 ;
	vars["file"] = file ;
					
	var url = "/common/preview_ajax.php" ;
			
	new Ajax.Request(url, {
		parameters : vars, 
		onSuccess: function (req) {
			var json = req.responseJSON ;
			
			if (json.ok !== 1) {
				alert("File could not be found") ;
				return ;
			}
									
			var aw = json.width ;
			var ah = json.height ;
			
			if (nw) {
				var nh = nw / aw * ah ;
			}
			else {
				nw = aw * 1 ;
				nh = ah * 1 ;
			}
			
			var bw = (nw * 1) + 20 ;
			var bh = (nh * 1) + 20 ;
						
			if (bw < 200) {
				bw = 200 ;
			}
			if (bh < 150) {
				bh = 150 ;
			}
			
			if (typeof preview_window != 'undefined') {
				try {preview_window.close()}
				catch (err) {}
			}
						
			var url = "/common/preview.php?file="+urlencode(file)+"&width="+nw+"&height="+nh ;
			var options = "width="+bw+", height="+bh+", resizeable=1, scrollbars=0" ;
			preview_window = window.open(url, "preview", options) ; 
			preview_window.focus() ;
		}, 
		onFailure: function (req) {
			alert("Your request has failed") ;
		}
	}) ;
}

/* Processing function */

function processingInit() {
	var html = '<div id="false_body" style="position: fixed; z-index: 1000; background-image: url(/common/main_bg.png); width: 100%; height: 100%; top: 0px; left: 0px; ">	<table style="height: 100%; width: 100%; margin: auto; ">		<tr>			<td style="padding: 0px; text-align: center; vertical-align: middle; ">				<table style="margin: auto; background-color: #eee; border: solid 1px #666; ">					<tr>						<td style="padding: 45px 75px; ">							<p style="margin-top: 0px; color: #000; font-size: 16px; font-family: arial; ">PROCESSING</p>							<div id="processing_loading"><img src="/common/loading.gif" alt="loading" /></div>						</td>					</tr>				</table>			</td>		</tr>	</table></div>' ;
	$(document.body).insert(html) ;
}


loading_preload = new Image() ;
loading_preload.src = ('/common/loading.gif') ;

HTMLElement.prototype.click = function() {
	var evt = this.ownerDocument.createEvent('MouseEvents');
	evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
	this.dispatchEvent(evt);
}

/* Give checkbox an off value */
/* example <input type="checkbox" name="cb" id="cb" value="onvalue" off="offvalue" /> */

function checkboxInit() {
	var hcb ;
	
	$$("form").each (function(f) {
		Event.observe(f, 'submit', function(ev) {
			$$("input[type='checkbox'][off]").each(function(e) {
				hcb = new Element('input', {'type':'hidden'}) ;
				e.insert({'before':hcb}) ;
				hcb.writeAttribute({'name':e.readAttribute('name')}) ;
				e.writeAttribute({'name':''}) ;
				
				if (e.checked == true) {
					hcb.value = e.value ;
				}
				else {
					hcb.value = e.readAttribute('off') ;
				}
			}) ;
		}) ;
	}) ;
}

/* get radio button group value.  returns value or null */

function radio(fn) {
	var r = document.getElementsByName(fn) ;
	
	var v = null ;
	
	$A(r).each(function(e) {
		if (e.checked == true) {
			v = e.value ;
		}
	}) ;
	
	return v ;
}

Event.observe(window, 'load', checkboxInit) ;

// session vars 

function session(vars, redirect) {
	vars["ajax"] = 1 ;
	
	var url = "/common/session.php" ;
	
	new Ajax.Request(url, {
		parameters : vars, 
		onSuccess: function(req) {
			if (redirect) {
				location = redirect ;
			}
			else {
				location.reload() ;
			}
		}, 
		onFailure: function(req) {
			alert("Your request has failed") ;
		}
	}) ;
	
	return false ;
}


