// photoProofPro v2.5.0
// (c) 2006 Joseph Pelosi (ilgstudio.com)
// 8/23/2006
// ------------------------
// Global Functions
// requires Prototype JavaScript framework, version 1.5.0_rc0
// --------------------------------

function showThumbs(){
	if ($('thumbnailLoader')){
		Element.hide('thumbnailLoader');
		Element.show('thumbnailContainer');
		//Effect.SlideDown('thumbnailContainer', {duration: 0.3});
	}
}

/*function embedObject(filename, flashName, width, height, variableNames, variableValues, color) {
	if (!color){
		color="#FFFFFF";
	}
	document.write('<object style="vertical-align: bottom" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+width+'" height="'+height+'" id="'+flashName+'Flash" align="middle">\n');
	document.write('<param name="allowScriptAccess" value="sameDomain" />\n');
	document.write('<param name="movie" value="'+filename+'" />\n');
	document.write('<param name="quality" value="high" />\n');
	document.write('<param name="bgcolor" value="'+color+'" />\n');

	var flashVars = '';

	if (variableNames && variableNames != ''){
		var varNamesArr  = variableNames.split("|");
		var varValuesArr = variableValues.split("|");
		for (var i=0; i<varNamesArr.length; i++){
			if (varNamesArr[i] != ''){
				flashVars += varNamesArr[i]+"="+varValuesArr[i]+"&";
			}
		}
	}
	if (flashVars != '')	{
		document.write('<param name="flashVars" value="'+flashVars+'" />');
		document.write('<embed src="'+filename+'" flashVars="'+flashVars+'" quality="high" bgcolor="'+color+'" width="'+width+'" height="'+height+'" name="'+flashName+'Flash" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	} else {
		document.write('<embed src="'+filename+'" quality="high" bgcolor="'+color+'" width="'+width+'" height="'+height+'" name="'+flashName+'Flash" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	}
	document.write('</object>\n');
}*/

function showHideLayer(layerID, sh){
	oLayer = $(layerID);
	if (sh=="show"){
		oLayer.style.display = "block";
	} else {
		oLayer.style.display = "none";
	}
}

function display(elID, what) {
	if ($(elID)){
		var myElement = $(elID);
		myElement.innerHTML = what;
	}
}

function addTo(elID, what){
	display(elID, $(elID).innerHTML+what);
}

function imgRollover(el, url){
	$(el).src=url;
}

function changeImg(el, url){
	$(el).src=url;
}

function preloadImage(img){
	preImg= new Image();
	preImg.src=img;
}
/* ======================================= */

function castVote(dir,imgName, imgID){
	
	$('voteMsg').update('processing vote...');
	Element.show('voteMsg');
	Element.hide('voteFields');
	/*<span id="starsDetail">[[stars]]</span>
		<span id="totalVoteDisplay">(<span id="voteNum">[[votes]]</span> Votes)</span>
		<span id="voteAverageDisplay">[[avg]]</span>*/
	var viewerType = $F('viewerType');
	var thisVote = parseInt($F('voteSelect'));
	var score = parseInt($F('score'));
	var newVotes = parseInt($F('votes'))+1;
	var newScore = thisVote+score;
	
			var requestOptions = {
						method : 'post',
						parameters : "action=castVote" +
						"&imgID=" + imgID +
						"&score=" + thisVote +
						"&newScore=" + newScore +
						"&file=" + imgName +
						"&votes=" + newVotes +
						"&path=" + dir +
						"&viewerType=" + viewerType,
						onComplete: voteCast
					  };
			 
	new Ajax.Request('includes/admin_AJAX_actions.php', requestOptions);
}



function voteCast(originalRequest){
	//alert (originalRequest.responseText);
	$('voteMsg').update('');
	Element.hide('voteMsg');
	Element.show('voteFields');
	eval("var response = ("+originalRequest.responseText+")");
	$('votes').value = response.votes;
	$('score').value = response.newScore;
	display('voteAverageDisplay', response.avgDisplay);
	display('starsDetail', response.stars);
	display('voteNum', response.votes);
	//alert('stars_'+activeImage+" ---- "+response.thumbStars);
	
	display('stars_'+(activeImage), response.thumbStars);
	$('voteStr_'+(activeImage)).style.display = "inline";
	display('voteTot_'+(activeImage), response.votes);
	display('voteAvg_'+(activeImage), response.avg);
	
}
// #####################################
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
		 	return pair[1];
		}
	} 
}
// #####################################
function changeMode(mymode, loadpage){
// ----------------------------------------
// vars
// mymode: (str) 'BW' or 'color'
// loadpage: (bln) flag to load page, or only change display text
// ----------------------------------------
	 var mode = mymode;
	 var p   = $F('p');
	 var ipp = $F('ipp');
	 var dir = $F('dir');
	 var recordID = $F('rid');
	 var o   = getQueryVariable('o');
	 //
		if (!ipp) { ipp='all'; }
		if (!o) { o='img'; }
		if (p==null){
			p=1;
		}
	
	if (loadpage){
		document.location.href = "?recordID="+recordID+"&action=openbook&mode="+mode+"&dir="+dir+"&p="+p+"&ipp="+ipp+"&o="+o;		
	} else {
		if (mode == "BW"){
			display('modeChange','<a href="javascript:changeMode(\'color\', true);">Show Color</a>');
		} else {
			display('modeChange','<a href="javascript:changeMode(\'BW\', true);">Show B&amp;W</a>');
		}
	}
}
// #######################################
function sortImages(){
	// submits form with new sort value;
	// called onchange of 'sortSelect' seclectbox
	 var p = $F('p');
	 var ipp = $F('ipp');
	 var o = $F('sortSelect');
	 var rid = $F('rid');
	 var dir = $F('dir');
	 var mode = $F('mode');
	 //
	 if (!ipp) { ipp='all'; }
	 if (!o) { o='img'; }
	 if (!p) { p='all'; }
	 if (!mode) { mode=''; }
	 var page = 1; 
	
	 var URL = "?recordID="+rid+"&dir="+dir+"&mode="+mode+"&action=openbook&p="+page+"&o="+o+"&ipp="+ipp;
	 document.location.href=URL;
}
// =============================================================
// CLIENT GALLERY ONLY
// =============================================================
	
	function collapseDiv(div){
		if ($(div)){
			if ($(div).style.display != "none"){
				Effect.BlindUp(div, {duration: 0.3});
				//Effect.BlindUp('postCommentForm', {duration: 0.3, queue:'front'});
			}
		}	
	}

	function toggleActiveForm(divId){
		var opt = {
				duration: 0.5,
				queue:'end',
				afterFinished: Element.hide('emailStatus')
		}
		if (divId=='postCommentForm') { //emailpageform
			collapseDiv('emailPageForm');
			collapseDiv('pastOrdersContainer');
			
		} else if (divId=='emailPageForm') {
			collapseDiv('postCommentForm');
			collapseDiv('pastOrdersContainer');
		} else {
			collapseDiv('postCommentForm');
			collapseDiv('emailPageForm');
			
		}
		Effect.toggle(divId, 'blind', opt);
	}
	
	function doEmailPage(divId){
		if (validate(divId, emailValidationArr)){
			//alert ('email Page Here.');
					var recordID = parseInt($F('recordID'));
					var requestOptions = {
								method : 'post',
								parameters : "action=emailClientPage" +
								"&recordID=" + recordID +
								"&recips=" + $F('ep_recip') +
								"&name=" + $F('ep_name') +
								"&email=" + $F('ep_email') +
								"&message=" + $F('ep_comm'),
								onComplete: pageSent
							  };
					Element.show('emailStatus');		 
					display('emailStatus', 'sending email...');
					new Ajax.Request('includes/admin_AJAX_actions.php', requestOptions);

		}
		return false;
	}
	
	function pageSent(originalRequest){
		//alert (originalRequest.responseText);
		eval("var response = ("+originalRequest.responseText+")");
		Element.show('emailStatus');
		display('emailStatus', response.msg);
		$('ep_name').value = '';
		$('ep_recip').value = '';
		$('ep_email').value = '';
		$('ep_comm').value = '';
		
		//
	}


	function doCommentPost(divId, valArr){
		if (validate(divId, valArr)){
			//alert ('email Page Here.');
					var recordID = parseInt($F('recordID'));
					var requestOptions = {
								method : 'post',
								parameters : "action=postComment" +
								"&recordID=" + recordID +
								"&comm_name=" + $F('comm_name') +
								"&comm_email=" + $F('comm_email') +
								"&comm_comm=" + $F('comm_comm'),
								onComplete: commentPosted
							  };
					new Ajax.Request('includes/admin_AJAX_actions.php', requestOptions);
		}
		return false;
	}
	
	
	function commentPosted(originalRequest){
		//alert (originalRequest.responseText);
		eval("var response = ("+originalRequest.responseText+")");
		display('commentContainer', response.commentsHTML);
		$('comm_name').value = '';
		$('comm_email').value = '';
		$('comm_comm').value = '';
	}
	
	function addToLightbox(filename){
		var recordID = parseInt($F('recordID'));
		var requestOptions = {
			method : 'post',
			parameters : "action=addToLightbox" +
			"&recordID=" + recordID +
			"&file=" + filename,
			onComplete: addedToLightbox
		  };
		  new Ajax.Request('includes/admin_AJAX_actions.php', requestOptions);
		
	}
	
	function addedToLightbox(originalRequest){
		alert (originalRequest.responseText);
		eval("var response = ("+originalRequest.responseText+")");
	}
	
	function toggleDefaultPass(pass){
		if ($('useDefaultPass').checked == true){
			$('confirmPass').value = pass;
			$('newPass').value = pass;
		} else {
			$('confirmPass').value = '';
			$('newPass').value = '';		
		}
		
	}
	function toggleLogoUpload(val){
	
		//alert(val);
		if (val==1){
			Element.show('uploadField');
			Element.show('prev_ownerLogo');
			Element.hide('prev_ownerName');
		} else {
			$('logo').value='';
			Element.hide('uploadField');
			Element.hide('prev_ownerLogo');
			Element.show('prev_ownerName');
			
		}
		
	}
	
	function toggleDefaultUser(){
		
		
			if ($('useDefaultUser').checked == true){
				if (Trim($F('name1'))==''||Trim($F('name2'))==''){
					alert('First and Last name cannot be blank.');
				} else {
					defaultuser = Trim($F('name1')).substring(0,1)+""+Trim($F('name2'));
					$('username').value = defaultuser.toLowerCase();
				}
			} else {
				$('username').value = '';
			}
		}
	
	function validateUserInfo(){
		
			//if (Trim($F('username'))!=''){
				checkUserExists();
			//}
			
			return false;
		
	}
	
	
	function checkUserExists(){
		
		alert('checking user');
		uName = Trim($F('username'));
		if (uName != ""){
			
			var requestOptions = {
					method : 'post',
					parameters : "action=checkUserName" +
					"&username=" + uName,
					onComplete: userChecked
				  };
			new Ajax.Request('includes/admin_AJAX_actions.php', requestOptions);
			
		} else {
			var validationArr = new Array();
			validationArr.push("empty|name1|First Name cannot be blank");
			validationArr.push("empty|name2|Last Name cannot be blank");
			validationArr.push("match|newPass,confirmPass|Passwords do not match");
			if(validate('adduser', validationArr)){
				alert ('we\'re all good1');
				$('adduser').submit();
				//return true;
			} else {
				return false;
			}
			
			
		}
		
	}
	
	function userChecked(originalRequest){
		eval("var response = ("+originalRequest.responseText+")");
		alert(response);
		if(response.usrExists){
			alert ('This username already exists, please choose another');
			return false;
		} else {
			var validationArr = new Array();
			validationArr.push("empty|name1|First Name cannot be blank");
			validationArr.push("empty|name2|Last Name cannot be blank");
			validationArr.push("match|newPass,confirmPass|Passwords do not match");
		
			if(validate('adduser', validationArr)){
				alert ('we\'re all good2');
				$('adduser').submit();
				//return true;
			} else {
				return false;
			}
			
		}
	}
	
	
	function getUserName(){
		if ($('useDefaultUser').checked == true){
				if (Trim($F('name1'))==''||Trim($F('name2'))==''){
					alert('First and Last name cannot be blank.');
					$('useDefaultUser').checked = false;
				} else {
					var requestOptions = {
								method : 'post',
								parameters : "action=getUserName" +
								"&fname=" + $F('name1') +
								"&lname=" + $F('name2'),
								onComplete: usernameGenerated
							  };
					new Ajax.Request('includes/admin_AJAX_actions.php', requestOptions);	
				}
		} else {
			$('username').value = '';
			
		}
	}
	
	
	function usernameGenerated(originalRequest){
		eval("var response = ("+originalRequest.responseText+")");
		//alert(response.msg);
		$('username').value = response.usrName;
	}
	
	
	function clearStatusMessage(){
		//display('columnMessage', '');
		$('columnMessage').update('');
	}
		
	function setStatusMessage(msg){
		//display('columnMessage', msg);
		$('columnMessage').update(msg);
	}
	
	
	
	function Trim(STRING){
		STRING = LTrim(STRING);
		return RTrim(STRING);
	}
	
	function RTrim(STRING){
		while(STRING.charAt((STRING.length -1))==" "){
			STRING = STRING.substring(0,STRING.length-1);
		}
		return STRING;
	}
	
	
	function LTrim(STRING){
		while(STRING.charAt(0)==" "){
			STRING = STRING.replace(STRING.charAt(0),"");
		}
		return STRING;
	}
	


function showSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}
// -------------------------------------------------
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});



	// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	//alert ('getting page size')
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


function getElementsByClassName__(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements);
}


function initHighlight(normClass, overClass) {
		
		if (!document.getElementsByTagName){ return; }
		//var allfields = document.getElementsByTagName("input");
		//allfields =+ document.getElementsByTagName("textarea");
		//var allfields = getElementsByClassName__(document, "*", normClass);
		
		if ($('mainContent')){
			var allfields = $('mainContent').getElementsByClassName(normClass);
		} else {
			var allfields = document.getElementsByClassName(normClass);
		}
		
		// loop through all input tags and add events
		for (var i=0; i<allfields.length; i++){
			var field = allfields[i];
			//if ((field.getAttribute("type") == "text") || (field.getAttribute("type") == "password") || field.getAttribute("") ) {
				//if (field.className == normClass){
				field.onfocus = function () {this.className = overClass;
				 if ($('touched')){
					 $('touched').value=1;
				 }
				}
				field.onblur = function () {this.className = normClass;}
				//}
			//}
		}
	}
	
function activateTextfieldHighlight(){
	initHighlight('textfields', 'textfieldsActive');
}
	
	
	
// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}	