// Do any page loading stuff
pageLoad()

function pageUnload() {
	if(typeof(map)!='undefined') {
		GUnload();
	}
}

var targetObj;
function getContentAJAX(url, target) {
	//document.getElementById(target).innerHTML = 'Loading...';
	targetObj = target;
	
	if (window.XMLHttpRequest) {
		// browser has native support for XMLHttpRequest object
		req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)	{
		// try XMLHTTP ActiveX (Internet Explorer) version
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(req)	{
		req.onreadystatechange = processRequest;
		req.open('GET', url, true);
		req.send(null);
	}
	else	{
		document.getElementById(target).innerHTML = 'Your browser does not support this feature.';
	}
	document.getElementById(target).className = '';
}

function processRequest() {
	var response;
	var target = targetObj;
	
    if (req.readyState == 4) {
        if (req.status == 200) {
        	response = req.responseText;
        } else {
  			response = "Unable to retrieve...";
        }
      
    	document.getElementById(target).innerHTML = response;
	    document.getElementById(target).className = 'scroll';
	}
}


// getBrowserWidth is taken from The Man in Blue Resolution Dependent Layout Script
// http://www.themaninblue.com/experiment/ResolutionLayout/
	function getBrowserWidth(){
		if (window.innerWidth){
			return window.innerWidth;}	
		else if (document.documentElement && document.documentElement.clientWidth != 0){
			return document.documentElement.clientWidth;	}
		else if (document.body){return document.body.clientWidth;}		
			return 0;
	}

// dynamicLayout by Kevin Hale
function dynamicLayout(){
	var browserWidth = getBrowserWidth();

	//Load Thin CSS Rules
	if (browserWidth < 1000){
		changeLayout("pageThin");
	}

	//Load Wide CSS Rules
	if (browserWidth > 999 && document.getElementById('rightMenu')){
		changeLayout("pageWide");
	}
}

// changeLayout is based on setActiveStyleSheet function by Paul Sowdon 
// http://www.alistapart.com/articles/alternate/
function changeLayout(description){
	document.getElementById('page').className = description;
}

//addEvent() by John Resig
function addEvent( obj, type, fn ){ 
   if (obj.addEventListener){ 
      obj.addEventListener( type, fn, false );
   }
   else if (obj.attachEvent){ 
      obj["e"+type+fn] = fn; 
      obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); } 
      obj.attachEvent( "on"+type, obj[type+fn] ); 
   } 
} 
	
//Run dynamicLayout function when page loads and when it resizes.
addEvent(window, 'load', dynamicLayout);
addEvent(window, 'resize', dynamicLayout);

function populateList(source)  {
  sourceList = document.getElementById(source);
  
  if(window.opener.document.getElementById(window.opener.targetListId)!=null)
    targetList = window.opener.document.getElementById(window.opener.targetListId);
  else
    targetList = window.opener.document.getElementById(document.getElementById('targetListId').value);
  
  targetList.options.length = 0; 
  
  for(i=0; i<sourceList.options.length;)  {
    targetList.appendChild(sourceList.options.item(i))        
  }
  
  window.close();
}

function pageLoad()	{
	if(self.parent.frames.length != 0) {
		self.parent.location=document.location;
	}
}

function closeAll()	{
	thisForm = document.getElementById('createCategoryRequest');
	aTags = thisForm.getElementsByTagName('a');
	
	for(i=0; i<aTags.length; i++)	{
		if(aTags[i].className=='pageSectionLink')	{
			divId = aTags[i].nextSibling.id;
			
			togglePageSection(aTags[i], divId)
		}
	}
	
}

function togglePageSection(linkSource, pageSection)	{
	if(linkSource.className=='pageSectionLink')	{
		linkSource.className='pageSectionLinkOff';
		document.getElementById(pageSection).className='pageSectionOff';
	}
	else	{
		linkSource.className='pageSectionLink';
		document.getElementById(pageSection).className='pageSection';
	}
}

function changeImage(target, imgName)	{

	var newImage = new Image();

	newImage.src = imgName;

	document.all[target].src = eval('newImage.src');
}

function isNumeric(sText)
{
	var validChars = '0123456789.';
	var isNumber = true;
	var character;
	var intCount = 0;

	for (intCount = 0; intCount < sText.length && isNumber == true; intCount++)
	{
		character = sText.charAt(intCount);
		if (validChars.indexOf(character) == -1)
		{
			isNumber = false;
		}
	}
	return isNumber;
}


function handleError(msg, url, ln)
{
   // Do you custom code here
   return true;
}


function changeClass(target, className)
{
 	target.className = className;
}

function asciiValue(Char)
{
	// restrict input to a single character
	Char = Char.charAt(0);

	// loop through all possible ASCII values
	var intLoop;
	for (intLoop = 0; intLoop < 256; intLoop++)
	{
		// convert intLoop into a 2-digit hex string
		var hexValue = intLoop.toString(16);
		if (hexValue.length == 1)
			hexValue = "0" + hexValue;

		// insert a % character into the string
		hexValue = "%" + hexValue;

		// determine the character represented by the escape code
		hexValue = unescape(hexValue);

		// if the characters match, we've found the ASCII value
		if (hexValue == Char)
			break;
			
			
	}
	return intLoop;
}


function validate() {
	var myfields = new Array('Order Date', 'Company Name', 'Position', 'Phone', 'Email', 'Contact Site', 'Site Phone', 'Work Description', 'Date Required');
	
	for(var i=0; i<myfields.length; i++) {
		var fieldName = document.getElementById(myfields[i]);
		
		if(fieldName.className=='mandatory' && fieldName.value=='') {
			alert('Please complete the field marked ' + myfields[i]);
			return false;
		}
	}
	
	return true;
}
		

function its_empty(string_value) {
  // Check for the empty string and null
  if (string_value == "" || string_value == null) {
  
    // If either, it's empty so return true
    return true
  }
  
  // Otherwise, it's not empty so return false
  return false
}

function validateEmail(emailField)
{
  var emailError = '';
  
  if(emailField.value == '')
  {
	return false
  }
  
  if(-1 == emailField.value.indexOf("@"))
  { 
     emailError = "Your email must have a '@'."; 
  }
  
  if(-1 == emailField.value.indexOf("."))
  { 
     emailError = "Your email must have a '.' in it."; 
  }
  
  if(-1 != emailField.value.indexOf(","))
  { 
     emailError = "Your email must not have a ',' in it"; 
  }
     
  if(-1 != emailField.value.indexOf("#"))
  { 
     emailError= "Your email must not have an '#' in it."; 
  }
     
  if(-1 != emailField.value.indexOf("!"))
  { 
     emailError = "Your email must not have a '!' in it."; 
  }
  
  if(-1 != emailField.value.indexOf(" "))
  { 
    emailError = "Your email must not have a space in it." ; 
  }
  
  if(emailField.value.length == (emailField.value.indexOf("@")+1) )
  {
     emailError = "Your email must have a domain name after the '@'.";
  }

  if(emailField.value.length == 0)
  { 
    emailError = "Please enter your email."; 
  }
  
  if(emailError != '')
  {
   	 emailField.value = '';
   	 alert(emailError);
	 emailField.focus();
	 return false;
  }
  
  return true;
}

function confirmMatch(password, confirm)
{
	if(password.value != confirm.value)
	{
		confirm.value = '';
		password.value = '';
		password.select();
		alert("Your passwords must match. Please try again.");
	}
}

// This function takes a string of text, the number of chars in the text and a maximum
// If the text is longet than the max it is cropped
function charCount(sourceText, countTarget, count, max) {
	var newCharCount = max - count;
	
	if(newCharCount < 0)	{
		sourceText.select();
		sourceText.value = String(sourceText.value).substring(0,max);
		newCharCount = 0;
	}
	
	var syntaxString = '';
	if(newCharCount != 1)	{
		syntaxString = 's';
	}

	document.getElementById(countTarget).innerHTML = newCharCount + ' Character' + syntaxString + ' Remaining.';
}

// This function is called when the user changes their payment method
// If credit card is chosen then set action to be credit pay otherwise normal pay

function creditPayment(choice, formName, normalAction, creditAction)
{
	if(choice.value == 'Credit Card')
	{
		formName.action = creditAction;
	}
	else
	{
		formName.action = normalAction;
	}
}

// This function switches between two different actions for a given form
function toggleFormAction(action1, action2, formName)
{
	if(formName.action == action1)
	{
		formName.action = action2;
		formName.target = '_new';
	}
	else
	{
		formName.action = action1;
		formName.target = '_self';
	}
}

function popupWindow(path, targetList, popupSize) {
	newWindow = window.open(path, "name", popupSize);
}

function imagePreview(source, siteId, imageName, fullPath) {
	if(source.value=='' || source.value=='upload' || source.value=='Google Map') {
		document.getElementById('preview'+ imageName +'Link').style.display='none';
	}
	else {
		var img = new Image();
		img.src = siteId+'/images_'+siteId+'/'+source.value;
		document.getElementById('preview'+ imageName +'Link').style.display='inline';
		document.getElementById('preview'+ imageName).src=img.src;
		
		img.onload = function() {
			if(document.getElementById('ForceImageHeight'))
				document.getElementById('ForceImageHeight').value = img.height;
			if(document.getElementById('ForceImageWidth'))
				document.getElementById('ForceImageWidth').value = img.width;
		}
	}
}

// Open a new window with the new image in it
function fullImage(path, imageName, name, imageSize)
{
	imageWindow= window.open("", "name", imageSize);

	imageWindow.document.write('<html>');
	imageWindow.document.write('<head>');
	imageWindow.document.write('<title>' + name + '</title>');
	imageWindow.document.write('<link rel="stylesheet" type="text/css" href="' + path + '/screen.css"/>');
	imageWindow.document.write('</head>');
	imageWindow.document.write('<body id="pageBack" topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">');
	imageWindow.document.write('<table class="largeImage" cellpadding="0" cellspacing="0" width="100%" height="100%">');
	imageWindow.document.write('<tr>');
	imageWindow.document.write('<td valign="middle" align="middle">');
	imageWindow.document.write('<table><tr><td><div id="shadow"><div class="productImage"><img src="'+ imageName +'" alt="' + name + '"/></div></div></td></tr></table>');
	imageWindow.document.write('<p><h2>' + name + '</h2></p>');
	imageWindow.document.write('<center><a href="javascript:window.close();" class="button">Close This Window</a></center>');
	imageWindow.document.write('</td>');
	imageWindow.document.write('</tr>');
	imageWindow.document.write('</table>');
	imageWindow.document.write('</body>');
	imageWindow.document.write('</html>');
	imageWindow.focus();
}

function swapImage(target, imgName)
{
   var newImage = new Image();         
   newImage.src = imgName;
   
   alert(this.name);
   
   document.images[target].src = eval('newImage.src');
}

function loadGoogleMap() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("googleMap"));
    map.enableScrollWheelZoom(); 
  }
  else {
  	var mapDiv = document.getElementById("googleMap");
	mapDiv.innerHTML='Sorry, your browser is not compatible with Google Maps.';
  }
}

function createMarker(point, info) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		map.panTo(point);
		marker.openInfoWindowHtml(info);
	});
	return marker;
}

function searchMap(searchText) {
	geocoder = new GClientGeocoder();
	
	if (geocoder) {
      geocoder.getLatLng(
	  searchText,
      function(point) {
        if (!point) {
          alert(searchText + " not found");
        } else {
          map.setCenter(point, 13);
          marker = new GMarker(point);
          map.addOverlay(marker);
          
          marker.openInfoWindowHtml(searchText + search);
        }
      }
    );
  }
}
