var t = '';
var iMove;
var url = "myinfo.php"; // The server-side script
var scrollSpeed = 2;
var moveMark;
var $_GET = new Array();

function populateGet()
{
	/**
	 * arrPath
	 *
	 * Make an array of everything after the domain name in the address bar.
	 * @var array
	 */
	var arrPath		= window.location.pathname.split('/');
	/**
	 * arrSearch
	 *
	 * Make an array of everything after the current page name in the address bar.
	 * @var array
	 */
	var arrSearch	= window.location.search.substr(1,window.location.search.length-1).split('&');

    $_GET['file_name'] = window.location.pathname;

    //Defaulting these to ''
    $_GET['mode'] = '';
    $_GET['job'] = '';

    if ( $_GET['file_name'].substr(0,1) == '/') {
        $_GET['file_name'] = $_GET['file_name'].substr(1,$_GET['file_name'].length-1);
    }

	for ( var intCounter = 0; intCounter < arrSearch.length; intCounter++ ) {
		arrTemp = arrSearch[intCounter].split('=');
		$_GET[arrTemp[0]] = arrTemp[1];
	}
}

function $(div_id)
{
    return document.getElementById(div_id);
}

function moveIt(directions,id_name) {
  var eMode = document.getElementById(id_name);
	switch (directions) {
	  case "up":
			eMode.scrollTop-=scrollSpeed;
	    break;
	  case "down":
	    eMode.scrollTop+=scrollSpeed;
	    break;
	  case "left":
			eMode.scrollLeft+=scrollSpeed;
	    break;
	  case "right":
	    eMode.scrollLeft-=scrollSpeed;
	    break;
	}
  moveMark=setTimeout("moveIt('"+directions+"','"+id_name+"')",scrollSpeed);
}

function updateGallery(group_id)
{
	var location					= './manager/inc/ajaxIncludes/images.php?mode=changeGroup';
	var postVariables				= 'group_id='+group_id;
	clearTimeout(t);
	http1.onreadystatechange =  updateGalleryResponse;
	http1.open('POST', location, true);
	http1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http1.setRequestHeader("Content-length", postVariables.length);
	http1.setRequestHeader("Connection", "close");
  	http1.send(postVariables);
}

function updateGalleryResponse()
{
	if ( http1.readyState == 4 ) {
		var arrResult = http1.responseText.split('|||');
		var count = 3000;
		document.getElementById('mainGallery').innerHTML = arrResult[2];

		if ( arrResult[1] == 1 ) {
			count = 5000;
		}
		t = setTimeout('updateImage('+arrResult[0]+')', count);
	}
}

function updateImage(item_id)
{
	var location					= './manager/inc/ajaxIncludes/images.php?mode=changeImage';
	var postVariables				= 'item_id='+item_id;

	http.onreadystatechange =  updateImageResponse;
	http.open('POST', location, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", postVariables.length);
	http.setRequestHeader("Connection", "close");
  	http.send(postVariables);
}

function updateImageResponse()
{
	if ( http.readyState == 4 ) {
		var arrResult = http.responseText.split('|||');
		var count = 3000;
		document.getElementById('mainPicture').innerHTML = arrResult[2];
		if ( arrResult[1] == 1 ) {
			count = 5000;
		}
		t = setTimeout('updateImage('+arrResult[0]+')', count);
	}
}


function onLoad(pageName)
{

	switch ( pageName ) {
		case "index.php":
			//userNameFocus();
			changeTiger(0);
			break;
		case "gallery.php":
			populateGet();
	    if ( $_GET['loadCart'] && $_GET['loadCart'] == 1 ) {
	        try {
	            addItemToCart();
	        } catch(e) {
	        }
	    }
			break;
		default:
			break;
	}
}

var tigerCounter = 1;
var tigerTimer = '';
function changeTiger(passedInt)
{
	if ( passedInt == 1 ) {
		if ( tigerCounter == 5 ) {
			tigerCounter = 1;
		} else {
			tigerCounter++;
		}
		document.getElementById('homePageRightImage').innerHTML = '<img src="./images/Stage' + tigerCounter + '.jpg" alt="Stage ' + tigerCounter + ' of the Siberian Tiger Painting" /><br />Stage ' + tigerCounter + ': Siberian Tiger';
	}
	tigerTimer = setTimeout('changeTiger(1)', 4000);
}

function unLoad()
{
	if ( t ) {
		clearTimeout(t);
	}
	if ( tigerTimer ) {
		clearTimeout(tigerTimer);
	}
	/*
	if ( globalTimeOutMarker ) {
		clearTimeout(globalTimeOutMarker);
	}
	*/
}

function checkTimeOut()
{
	/*
	if ( globalTimeOutMarker && parseInt(globalMaxTimeOut) != 0 && parseInt(globalTimeOut) >=  parseInt(globalMaxTimeOut) ) {
		clearTimeout(globalTimeOutMarker);
		window.location.href='index.php?mode=signedOut';
	} else {
		var location					= './inc/ajaxIncludes/ajxBugReport.php';
		var postVariables				= 'mode=keepAlive';

		globalTimeOut	+= globalCheckIncrements;
		globalTimeOutMarker = setTimeout('checkTimeOut()',parseInt(globalCheckIncrements)*60000);

		http.onreadystatechange = checkTimeOutResponse;
		http.open('POST', location, true);
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", postVariables.length);
		http.setRequestHeader("Connection", "close");
	   	http.send(postVariables);
	}
	*/
}

function checkTimeOutResponse()
{
	if ( http.readyState == 4 ) {
		/* Solely here to keep the PHP session active */
	}
}

function trim(sString)
{
	return rightTrim(leftTrim(sString));
}

function leftTrim(sString)
{
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

function rightTrim(sString)
{
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function toggle(elementName)
{

	//alert(elementName);
	//alert(window.document.getElementById(elementName).style.display + ' : Prior');
	if ( window.document.getElementById(elementName) ) {
		if ( window.document.getElementById(elementName).style.display == 'block' ) {
			window.document.getElementById(elementName).style.display = 'none';
		} else {
			//alert(window.document.getElementById(elementName).innerHTML);
			window.document.getElementById(elementName).style.display = 'block';
		}
	}/* else {
		alert('Element: "'+elementName+'" was not located.');
	}*/
	//alert(window.document.getElementById(elementName).style.display + ' : Post');

}

function chkLen(strNumber, intLen)
{
	var newVal = '';
	var intStopper = 5;  /* will stop function after intStopper loops */
	var intCounter = 0;

	if ( intLen == '' || intLen == 0 || intLen == undefined ) {
		intLen = 2;
	}

	if ( strNumber == undefined ) {
		strNumber = 0;
	}
	newVal = strNumber.toString();
	while ( newVal.length < intLen && intCounter < intStopper ) {
		newVal = '0'+strNumber;
		intCounter++;
	}
	return newVal;
}

function cleanNumber(strNumber, is_float)
{
	var strSafe = '0123456789';
	var newSafe = '';

	if ( is_float == 1 ) {
		strSafe += '.';
	}

	if ( strNumber == undefined ) {
		return '';
	} else {
		if ( strNumber.length > 0 ) {
			for ( var i = 0; i < strNumber.length; i++ ) {
				if ( strSafe.indexOf(strNumber.substr(i,1)) != -1) {
					newSafe += strNumber.substr(i,1);
				}
			}
		}
		return newSafe;
	}
}


/**
* function emailFocus()
* Will locate the form name with the email form field
* and will put email as a form field as the focus.
*/
function emailFocus()
{
	if ( document.loginForm ) {

		if ( document.loginForm.email ) {

			/* Setting focus to the email field on the login form. */
			document.loginForm.email.focus();

		} /* End if ( document.loginForm.email ) */

	} /* End if ( document.loginForm ) */

} /* End function emailFocus() */

/**
* function time
* This function creates a string for the current time, and calls itself again every 15 seconds.
*/
function time(num)
{
	if ( document.getElementById('time') ) {
		var objDate = new Date();
		var intHours = objDate.getHours();
		var intMinutes = objDate.getMinutes();
		var strAP = 'am';

		if (  intHours >= 12 ) {
			strAP = 'pm';
			if ( intHours > 12 ) {
				intHours-=12;
			} /* End if (  intHours > 12 ) */
		} /* End if (  intHours >= 12 ) */

		intMinutes = intMinutes.toString();

		if ( intMinutes.length < 2 ) {
			intMinutes = '0'+intMinutes;
		} /* End if (  intMinutes.length < 2 ) */
		var myDate = intHours+':'+intMinutes;

		myDate += ' '+strAP;

		document.getElementById('time').innerHTML=myDate;
	}
	setTimeout('time(1)',15000);



} /* End function time() */

/* ======================================== Begin Ajax information ======================================== */
/**
* function getHTTPObject
* This function is set up to
* allow access to the XMLHttpRequest Object
* within JavaScript
*/
function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	@else
		xmlhttp = false;
	@end @*/

	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
} /* End function getHTTPObject */

/* Load the getHTTPObject into the JavaScript http varaible */

var http = getHTTPObject(); // We create the HTTP Object
var http1 = getHTTPObject(); // We create the HTTP Object

/* ========================================= End Ajax information ========================================= */

/**
* function cleanUp
* This function loops through the passed string variable and replaces the reserved char (&) with "__ampersand__"
*/
function cleanUp(strOld)
{
	var newStr = '';

	if ( strOld != undefined && strOld.length > 0 ) {
		for ( var i = 0; i < strOld.length; i++) {
			switch ( strOld.substr(i,1) ) {
				case "|":
					break;
				case "`":
					newStr += '{tld}';
					break;
				case "=":
					newStr += '{eq}';
					break;
				case "&":
					newStr += '{amp}';
					break;
				case "/":
					newStr += '{sl}';
					break;
				case "\\":
					newStr += '{bsl}';
					break;
				case ":":
					newStr += '{col}';
					break;
				case "?":
					newStr += '{que}';
					break;
				case "+":
					newStr += '{pls}';
					break;
				default:
					newStr += strOld.substr(i,1);
					break;
			}
		} /* End for ( var i = 0; i < str.length; i++) */
	}

	return newStr;
} /* End function cleanUp */

function openFloatingLayer()
{
	if ( document.getElementById('floatingLayer').style.display == 'block') {
		document.getElementById('floatingLayer').style.display='none';
		document.getElementById('floatingLayerBackground').style.display='none';
	} else {
		document.getElementById('floatingLayerBackground').style.display='block';
		document.getElementById('floatingLayer').style.display='block';
	}
}

function openFloatingMiniLayer(obj)
{
	if ( document.getElementById('floatingLayerMini').style.display == 'block') {
		document.getElementById('floatingLayerMini').style.display='none';
		document.getElementById('floatingLayerBackground').style.display='none';
	} else {
		document.getElementById('floatingLayerBackground').style.display='block';
		document.getElementById('floatingLayerMini').style.display='block';
	}
}

function addItemToCart()
{
    var strContent = '<a href="#" style="float: right; text-align: right; width: 100px;"onclick="openFloatingLayer();">Close</a><br style="clear: both;" />' +document.getElementById('floatingLayerInput').innerHTML;

    strContent = strContent.replace('id="addToShoppingCart"','id="addToShoppingCartUsed"');
    strContent = strContent.replace(/cart_item_size_/g,'cart_item_used_');

    document.getElementById('floatingLayer').innerHTML = strContent;
    openFloatingLayer();
}

function updateCart()
{
	var strLocation					= './inc/ajaxIncludes/cart.service.php?mode=updateItems';
	var strPostVariables				= 'entity_name=gallery_group_tbl&entity_id='+$('addToShoppingCart').group_id.value;
	var arrInputs = $('addToShoppingCartUsed').getElementsByTagName('INPUT');

	for ( var intInput = 0; intInput < arrInputs.length; intInput++ ) {
	    if ( arrInputs[intInput].id.substr(0,15) == 'cart_item_used_'  ) {
	        strPostVariables += '&' + arrInputs[intInput].id + '=' + parseInt($(arrInputs[intInput].id).value);
	        $(arrInputs[intInput].id.replace('used','size')).value = parseInt($(arrInputs[intInput].id).value);
	    }
	}

	//window.open(strLocation+'&'+strPostVariables,'test');
	http1.onreadystatechange =  updateCartResponse;
	http1.open('POST', strLocation, true);
	http1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http1.setRequestHeader("Content-length", strPostVariables.length);
	http1.setRequestHeader("Connection", "close");
  	http1.send(strPostVariables);
}

function updateCartResponse()
{
    if ( http1.readyState == 4 ) {
        var strContent = '<a href="#" style="float: right; text-align: right; width: 100px;"onclick="closeShoppingCart();">Close</a><br style="clear: both;" />' +http1.responseText;
        $('floatingLayer').innerHTML = strContent;
    }
}

function closeShoppingCart()
{
    openFloatingLayer();
}

function verifyCustomer()
{
	var msg = '';

	if ( $('first_name').value.length < 1 ) {
		msg += 'Please enter your first name.\n';
	}

	if ( $('last_name').value.length < 1 ) {
		msg += 'Please enter your last name.\n';
	}

	if ( $('email').value.length < 1 || !checkEmail($('email')) ) {
		msg += 'Please enter a valid e-mail.\n';
	}

	if ( $('address').value.length < 1 ) {
		msg += 'Please enter your address.\n';
	}

	if ( $('city').value.length < 1 ) {
		msg += 'Please enter your city.\n';
	}

	if ( $('state_id').value == 0 ) {
		msg += 'Please select a state.\n';
	}

	if ( $('postal_code').value.length < 5 ) {
		msg += 'Please enter a zip code.\n';
	}

	if ( msg.length > 0 ) {
		alert(msg);
		return false;
	} else {
		var strLocation					= './inc/ajaxIncludes/cart.service.php?mode=proceedToCheckout';
		var strPostVariables		= 'first_name=' + $('first_name').value +
																'&last_name=' + $('last_name').value +
																'&email=' + $('email').value +
																'&address=' + $('address').value +
																'&address2=' + $('address2').value +
																'&city=' + $('city').value +
																'&state_id=' + $('state_id').value +
																'&postal_code=' + $('postal_code').value;

		//window.open(strLocation+'&'+strPostVariables,'test');
		http1.onreadystatechange =  verifyCustomerResponse;
		http1.open('POST', strLocation, true);
		http1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http1.setRequestHeader("Content-length", strPostVariables.length);
		http1.setRequestHeader("Connection", "close");
  	http1.send(strPostVariables);
	}

}

function verifyCustomerResponse()
{
	if ( http1.readyState == 4 ) {
	  var test = 0;
	  if ( test == 1 ) {
	  	alert("The amount that should be sent to paypal is: $" + http1.responseText + "; however, while we are in test mode, I will only send the amount of $1.00.");
		  $('payPalAmount').value = "1.00";
		} else {
		  $('payPalAmount').value = http1.responseText;
		}
		$('payPalForm').submit();
		window.location.href='?thanks=true';
	}
}

/**
 * checkEmail
 *
 * Checks to see if the email is a valid email string
 * @param object objField
 * @return bit
 */
function checkEmail(objField)
{
    /**
     * regExEmail
     *
     * Contains regular expression to search for email pattern
     * @var regular Expression
     */
    var regExEmail = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
    /**
     * regEx
     *
     * Regular Expression Object
     * @var object
     */
    var objRegEx = new RegExp(regExEmail);

    if ( !objRegEx.test(objField.value) ) {
            return false;
    } else {
        return true;
    }
}