
// custom prototype methods

String.prototype.nl2br = function () {
	return this.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2') ;
};

(function(){
	
	var eventMatchers = {
		'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
		'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
	}
	var defaultOptions = {
		pointerX: 0,
		pointerY: 0,
		button: 0,
		ctrlKey: false,
		altKey: false,
		shiftKey: false,
		metaKey: false,
		bubbles: true,
		cancelable: true
	}
	
	Event.simulate = function(element, eventName) {
		var options = Object.extend(defaultOptions, arguments[2] || { }) ;
		var oEvent, eventType = null ;
		
		element = $(element) ;
		
		for (var name in eventMatchers) {
			if (eventMatchers[name].test(eventName)) { eventType = name ; break ; }
		}
		
		if (!eventType)
		throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported') ;
		
		if (document.createEvent) {
			oEvent = document.createEvent(eventType) ;
			if (eventType == 'HTMLEvents') {
				oEvent.initEvent(eventName, options.bubbles, options.cancelable) ;
			}
			else {
				oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
				options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
				options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element) ;
			}
			element.dispatchEvent(oEvent) ;
		}
		else {
			options.clientX = options.pointerX ;
			options.clientY = options.pointerY ;
			oEvent = Object.extend(document.createEventObject(), options) ;
			element.fireEvent('on'+eventName, oEvent) ;
		}
		return element ;
	}
	
	Element.addMethods({simulate: Event.simulate}) ;
})() ;

Element.addMethods ({
	scrollToSide : function (e, side) {
		e = $(e) ;
		
		if (side == 'top') {
			e.scrollTop = 0 ;
			return true ;
		}
		else if (side == 'right') {
			e.scrollLeft = e.scrollWidth ;
		}
		else if (side == 'bottom') {
			e.scrollTop = e.scrollHeight ;
			return true ;
		}
		else if (side == 'left') {
			e.scrollLeft = 0 ;
		}
		
		return false ;
	}, 
	disabledClass : function (e, dir) {
		e = $(e) ;
		
		if (dir == null) {
			return e.hasClassName('disabled') ;
		}
		if (dir === true) {
			e.addClassName('disabled') ;
		}
		if (dir === false) {
			e.removeClassName('disabled') ;
		}
	}, 
	readonlyClass : function (e, dir) {
		e = $(e) ;
		
		if (dir == null) {
			return e.hasClassName('readonly') ;
		}
		if (dir === true) {
			e.addClassName('readonly') ;
		}
		if (dir === false) {
			e.removeClassName('readonly') ;
		}
	}, 
	checkedClass : function (e, dir) {
		e = $(e) ;
		
		if (dir == null) {
			return e.hasClassName('checked') ;
		}
		if (dir === true) {
			e.addClassName('checked') ;
			return true ;
		}
		if (dir === false) {
			e.removeClassName('checked') ;
			return true ;
		}
	},
	slideToggle : function (e, dur) {
		e = $(e) ;
		
		if (e.visible() == true) {
			e.slideUp(dur) ;
		}
		else {
			e.slideDown(dur) ;
		}
	},
	slideDown : function (e, dur) {
		e = $(e) ;
		
		if (e.sliding == true) {
			return ;
		}
		
		e.sliding = true ;
		
		if (!dur) {
			dur = .4 ;
		}
		
		new Effect.SlideDown(e, {
			duration : dur, 
			afterFinish : function () {
				e.sliding = false ;
			}
		}) ;
	},
	slideUp : function (e, dur) {
		e = $(e) ;
		
		if (e.sliding == true) {
			return ;
		}
		
		e.sliding = true ;
		
		if (!dur) {
			dur = .4 ;
		}
		
		new Effect.SlideUp(e, {
			duration : dur, 
			afterFinish : function () {
				e.hide() ;
				e.sliding = false ;
			}
		}) ;
	}, 
	showing : function (e) {
		e = $(e) ;
		
		if (e.visible() == false) {
			return false ;
		}
		
		if (e.getHeight() == 0 && e.getWidth() == 0) {
			return false ;
		}
		
		return true ;
	}
}) ;

Element.addMethods('SELECT', {
	selectedOption : function (s) {
		s = $(s) ;
		return s.select('[selected]')[0] ;
	}
}) ;

Element.addMethods('FORM', {
	submitNormal : function (f) {
		f = $(f) ;
		f.simulate('submit') ; // FIX - doesn't work in IE?
	}
}) ;

var $I = function (id) {
	// iframe functions
	id = $(id) ;
	var win = id.contentWindow || id.contentDocument.defaultView ;
	//var doc = id.contentDocument || id.contentWindow.document ;
	Element.extend(win.document.body) ; // for IE
	
	win.autosizeHeight = function (slide) {
		if (slide) {
			if (id.i_aH_e) {
				id.i_aH_e.cancel() ;
			}
			
			id.i_aH_e = new Effect.Morph(id, {
				style : {'height': this.getBodyHeight()+'px'},
				duration : .4
			}) ;
		}
		else {
			id.setStyle({'height':this.getBodyHeight()+'px'}) ;
		}
	}
	
	win.getBodyHeight = function () {
		var mbh = 0 ;
		
		if (win.document.body.getLayout) {
			mbh = win.document.body.getLayout().get('margin-box-height') ;
		}
		
		return Math.max(win.document.body.scrollHeight, mbh) ;
	}
	
	return win ;
}

// 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) {
		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 is_email(email) {
   if(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(email) == false) {
      return false;
   }
   else {
	   return true ;
   }
}

function validateFile(e, ext) {
	var ok = false ;
	var ext_str = '' ;
	
	$A(ext).each(function(i) {
		ext_str = ext_str+"."+i+"\r\n" ;
		
		if (e.value.toLowerCase().search("."+i) != -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) ;
}

// Window functions

var windows = {} ;


function popup(url, win_name) {
	// opens new window with URL of img url
	
	url = url.replace('-thumb.', '-full.') ;
	
	if (!win_name) {
		win_name = "popupwin" ;
	}
	
	if (windows[win_name]) {
		windows[win_name].close() ;
	}
	
	win = window.open('', win_name, "resizable=1,scrollbars=0,location=0,status=0,toolbar=0,menubar=0,width=350,height=350") ;
	
	windows[win_name] = win ;
	
	var img = new Image() ;
	img.src = url ;
	
	if (img.complete == true) {
		resize() ;
	}
	else {
		img.onload = function () {resize() ;} ;
	}

	function resize() {
		win.location = url ;
		
		var w = img.width - win.document.body.clientWidth + 0 ;
		var h = img.height - win.document.body.clientHeight + 0 ;
		
		win.resizeBy(w, h) ;
		win.focus() ;
		win.document.close() ;
		img.onload = null ;
	} ;
	
	return false ;
}

function preview(file, nw, nh, win_name, win_title) {
	// opens new window with img as element in HTML document
	
	file = file.replace('https://', '') ;
	file = file.replace('http://', '') ;
	file = file.replace('www.sonorandesigngroup.com', '') ;
	file = file.replace('-thumb.', '-full.') ;
	
	if (!win_name) {
		win_name = "preview" ;
	}
	
	if (windows[win_name]) {
		windows[win_name].close() ;
	}
	
	var q = $H({
		'file' : file, 
		'width' : nw,
		'height' : nh,
		'win_title' : win_title
	}) ;
	
	q = q.toQueryString() ;
	
	preview_window = window.open("/common/preview.php?"+q, win_name, "resizable=1,scrollbars=0,location=0,status=0,toolbar=0,menubar=0,width=350,height=350") ;
	
	windows[win_name] = preview_window ;
	
	preview_window.focus() ;

	return false ;	
}

/* Processing function */

var procWin = {
	img : new Image(), 
	
	src : '/common/images/loading.gif', 
	
	
	show : function () {
		if (!$('procWin')) {
			$(document.body).insert('<table id=\"procWin\" cellspacing=\"0\" cellpadding=\"0\" style=\"position: fixed; z-index: 1000; top: 0px; left: 0px; width: 100%; height: 100%; \"> <tr> <td style=\"vertical-align: middle; text-align: center; /*linear gradient not supported*/; \"> <table cellspacing=\"0\" cellpadding=\"0\" style=\"margin: auto; \"> <tr> <td> <div style=\"padding: 45px 75px; background-color: #eee; border: solid 6px #d5d5d5; border-radius: 20px; box-shadow: 0px 0px 20px 0px rgba(102, 102, 102, 1); \"> <p style=\"margin-top: 0px; color: #777; font-size: 20px; font-weight: normal; text-shadow: 2px 2px .1em #bbb; \">Processing</p> <img src=\"/common/images/loading.gif\" id=\"procWin_img\" alt=\"Loading\" /> </div> </td> </tr> </table> </td> </tr> </table>') ;
		}
	}, 
	
	hide : function () {
		if ($('procWin')) {
			$('procWin').remove() ;
		}
	}, 
	
	init : function () {
		procWin.img.src = procWin.src ;
	}
} ;

procWin.init() ;

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);
} ;

function fail(message) {
	procWin.hide() ;
	if (message) {
		alert(message) ;
	}
	return false ;
}

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

/*
var disabled_uploads = [] ;

function revertFileInputs() {
	$A(disabled_uploads).each(function (e) {
		e.disabled = false ;
	}) ;
}
*/

function formSubmitCallback() {
	var max_file_uploads = 100;
	
	$$('form').each (function(f) {
		//revertFileInputs() ;
		
		Event.observe(f, 'submit', function (ev) {
			var fifs = 0 ;
			var inc = 0 ;
			
			$$('input[type="file"]').each(function (e) {
				if (e.readAttribute('disabled')) {
					return ;
				}
				
				/*
				if (e.value == '') {
					e.disabled = true ;
					disabled_uploads[++inc] = e ;
				}
				else {
					++fifs ;
				}
				*/
				
				++fifs ;
			}) ;
			
			if (fifs > max_file_uploads) {
				ev.stop() ;
				//revertFileInputs() ;
				return fail('You have exceeded the maximum number of file uploads.  Please contact the webmaster.') ;
			}
			
			$$('input[type="checkbox"][off]').each(function (e) {
				if (!e.hcb) {
					var hcb = new Element('input', {
						'type' : 'hidden', 
						'name' : e.readAttribute('name')
					}) ;
					
					e.insert({'after':hcb}) ;
					e.name = '' ;
					e.hcb = hcb ;
				}
				
				if (e.checked == true) {
					var value_attr = e.value ;
				}
				else {
					var value_attr = e.readAttribute('off') ;
				}
				
				e.hcb.value = value_attr ;
			}) ;
			
			$$('input[type="radio"][on]').each(function (e) {
				var name_attr = evaluate_template(e.readAttribute('name'), {'value' : e.value}) ;
				var on = e.readAttribute('on') ;
				var off = e.readAttribute('off') ;
				
				if (e.checked == true) {
					var value_attr = on ;
				}
				else {
					var value_attr = off ;
				}
				
				if (off || e.checked == true) {
					hr = new Element('input', {
						'type' : 'hidden', 
						'name' : name_attr,
						'value' : value_attr
					}) ;
					
					e.insert({'after':hr}) ;
				}
				
				e.name = '' ;
			}) ;
		}) ;
	}) ;
}

document.observe('dom:loaded', formSubmitCallback) ;

/* 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 ;
}

// session vars 

function session(post, red) {
	if (typeof post === 'string') {
		var q = post.indexOf('?') ;
		
		if (q !== false) {
			if (!red) {
				red = post.substring(0, q) ;
			}
			
			post = post.parseQuery() ;
		}
	}
	
	post.ajax = 1 ;
	
	var url = '/common/session.inc' ;
	
	new Ajax.Request(url, {
		parameters : post, 
		asynchronous : false, 
		onSuccess : function(r) {
			var json = r.responseJSON ;
			
			if (!json) {
				alert('Invalid response from server') ;
			}
			else if (json.ok == 1) {
				if (red) {
					if (red === '') {
						red = location ;
					}
					
					location = red ;
				}
			}
			else {
				alert('ERROR: '+json.message) ;
			}
		}, 
		onFailure : function() {
			alert('Your request has failed') ;
		}
	}) ;
}

function evaluate_template(str, replacements) {
	var template = new Template(str) ;
	return template.evaluate(replacements) ;
}

/*
if (Effect) {
	document.observe('dom:loaded', function () {
		var e = document.body.insert('<div style="height: 0px; line-height: 0px; "></div>') ;
		Effect.morph(e, {'opacity':0}) ;
	}) ;
}
*/


