var siteId;

// Do any page loading stuff
pageLoad();

function pageLoad()	{
	//Run dynamicLayout function when page loads and when it resizes.
	addEvent(window, 'load', dynamicLayout);
	addEvent(window, 'resize', dynamicLayout);

	//Check if page is unning in frame then exit frame
	if(self.parent.frames.length != 0) {
		self.parent.location=document.location;
	}

	jQuery(document).ready(function() {
		siteId = document.getElementById('siteId').value;
		
		// Set up  openers fo open close section		
		$('div.openClose').addClass('closed');
		$('div.openClose').click(function() {
			$(this).toggleClass('closed').next().toggle('slow');
			return false;
		}).next().hide();
		
		$('.showNextRow')
			.css("cursor","pointer")
			.attr("title","Click to expand/collapse")
			.click(function(){
				$(this).next().toggle();
		}).next().hide();			
		
		// Set any openClose secions to start open
		$('div.openClose.open').toggleClass('closed').next().toggle('slow');
		
		$('.showNextRow').toggle(
			function () {
				$(this).next().css({'display':'table-row'});
			},
			function () {
				$(this).next().css({'display':'none'});
			}
		).next().hide();
		
		// If lightbox elements then include lightbox plugin
		if($('a[rel=lightbox]').length > 0) {
			$.include(siteId + '/scripts/lightbox/lightbox.css'); 
			$.include(siteId + '/scripts/lightbox/lightbox.js', applyLightBox); 
		}
		
		if($('input.dateField').length > 0) {
			$.include(siteId + '/scripts/datePicker/datePicker.css'); 
			$.include(siteId + '/scripts/datePicker/datePicker.js', applyDatePicker); 
		}
		
		if($('input.colour').length > 0) {
			$.include(siteId + '/scripts/colourPicker.js'); 
		}
		
		if($('table.sortable').length > 0) {
			$.include(siteId + '/scripts/tableSorter/tableSorter.css'); 
			$.include(siteId + '/scripts/tableSorter/tableSorter.min.js', applySortable); 
		}
	});
}

function applySortable() {
	$('table.sortable').tablesorter(); 
}

function applyLightBox() {
	$('a[rel=lightbox]').lightBox();
}

function applyDatePicker() {
	Date.format = 'yyyy-mm-dd';
	$('input.dateField').datePicker({startDate:'1980-01-01'});
}

function applyColourPicker() {
	iColorPicker();
}

function pageUnload() {
	if(typeof(map)!='undefined') {
		GUnload();
	}
}

ajaxArray = new Array(); 
ajaxTarget = new Array(); 
function getContentAJAX(url, target) {
	var index = 0;
	var maxSimultaneousRequests = 10;
	
	// Find an empty slot in the AJAX array
	while (ajaxArray[index] && index < maxSimultaneousRequests) {
		index++;
	}
	
	if (index < maxSimultaneousRequests) { 
		if (window.XMLHttpRequest) {
			// browser has native support for XMLHttpRequest object
			ajaxArray[index] = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)	{
			// try XMLHTTP ActiveX (Internet Explorer) version
			ajaxArray[index] = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		if(ajaxArray[index]) {
			ajaxArray[index].onreadystatechange = processRequest;
			ajaxArray[index].open('GET', url, true);
			ajaxArray[index].send(null);
			ajaxTarget[index] = target;
		}
		else {
			if(document.getElementById(target)) {
				document.getElementById(target).innerHTML = '<div class="notification">Your browser does not support this feature.</div>';	
			}
		}
	}
}

function processRequest() {
	var response;
	
	for (var index = 0; index < ajaxArray.length; index++) {
		if (ajaxArray[index] && ajaxArray[index].readyState == 4) { 
			if (ajaxArray[index].status == 200) {
				response = ajaxArray[index].responseText;
			} else {
				response = '<div class="exception">Unable to retrieve...</div>';
			}
		  
			if(document.getElementById(ajaxTarget[index])) {
				document.getElementById(ajaxTarget[index]).innerHTML = response;
			}
			ajaxArray[index] = null;
			ajaxTarget[index] = null;
		}
	}
}


// 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(){
	// Does this page have the correct classes
	if(document.getElementById('page')) {
		var browserWidth = getBrowserWidth();
		var page = document.getElementById('page');
		
		//Load Thin CSS Rules
		if (browserWidth < 1000){
			page.className = 'pageThin';
		}

		//Load Wide CSS Rules
		if (browserWidth > 999 && document.getElementById('rightMenu')){
			page.className = 'pageWide';
		}
		else {
			page.className = 'pageThin';
		}
	}
}

//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] ); 
   } 
} 

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 selectImage(imagePath) {
	//Takes a image path and assigns it as the value of a target control
	
	field = window.top.opener.browserWin.document.forms[0].elements[window.top.opener.browserField]; 
	field.value = '/' + window.top.opener.projectName + '/' + window.top.opener.siteId + '/images_' + window.top.opener.siteId + '/' + document.getElementById(imagePath).value;
	
	if (field.onchange != null) 
		field.onchange();
		
	window.top.close();
	window.top.opener.browserWin.focus();
}

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 toggleClass(target, className) {
	if(target.className.indexOf(className) > 0) {
		target.className = target.className.replace(' ' + className, '');
	}
	else {
		target.className = target.className + ' ' + className;
	}
}

function changeImage(target, imgName)	{
	var newImage = new Image();
	newImage.src = imgName;
	document.getElementById(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;
}


// Called with parameter of name of form to validate. Form objects with a value of manditory="true" must contain
// values.
function validateForm(formName) {
	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, imageName, siteId) {
	var img = new Image();
	img.onload = function() {
		if(document.getElementById('ForceImageHeight'))
			document.getElementById('ForceImageHeight').value = img.height;
		if(document.getElementById('ForceImageWidth'))
			document.getElementById('ForceImageWidth').value = img.width;
	}
	
	if(source=='' || source=='upload' || source=='Google Map') {
		document.getElementById('preview'+ imageName +'Link').style.display='none';
	}
	else if(source.indexOf('http') != -1) {
		img.src = source;
		document.getElementById('preview'+ imageName +'Link').href = source;
		document.getElementById('preview'+ imageName +'Link').style.display='inline';
		document.getElementById('preview'+ imageName).src=img.src;
	}
	else {
		img.src = siteId+'/images_'+siteId+'/'+source;
		document.getElementById('preview'+ imageName +'Link').href = siteId+'/images_'+siteId+'/'+source;
		document.getElementById('preview'+ imageName +'Link').style.display='inline';
		document.getElementById('preview'+ imageName).src=img.src;
	}
}

// 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();
	map.clearOverlays();
	
	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);

					var latLng = marker.getLatLng();
					document.getElementById('mapX').value = latLng.lng();
					document.getElementById('mapY').value = latLng.lat();
				}
			}
		);
	}
}
