/* * * * * * * * * * * * * * * * * * *
 * Just-Click-Photography javascript *
 * document. Provides various website*
 * enhancements                      *
 * * * * * * * * * * * * * * * * * * */
 
document.onkeydown = pagenavigation; // Function to run on keyup event
var keysEnabled = true; // Are navigation keys enabled for picture pages?

/* Parse the URL on the pictures page
   Look for any tab=1 etc items in the bookmarks
   Navigate to the specified tab page as specified
 */
function parseURL()
{
	var location = window.location.href;
	
	// If there is a # in the page url
	if (location.indexOf("#") != -1)
	{
		hash = location.substr(location.indexOf("#") + 1);
		var hashParams = hash.split(/[\?#|=|&|\/]/);
		
		// If there are hash paramters
		if (hashParams.length)
		{
			// If the first paramater is empty, remove it
			if (hashParams[0] == "")
			{
				hashParams.shift();
			}
			
			// If there are hash paramters
			if (hashParams.length)
			{
				// Loop for every item
				for (var i in hashParams)
				{
					i = parseInt(i); // Convert string to int
					// If value is the tabpage variable
					if (hashParams[i] == "tabpage")
					{
						var pageID = hashParams[(i + 1)]; // Set the PageID
						change_tabpage(pageID); // Change the tabpage
					}
					// Loads a picture from the ID specified
					else if (hashParams[i] == "pictureid")
					{
						var pictureID = hashParams[(i + 1)];
						loadPictureFromID(pictureID);
					}
				}
			}
		}
	}
}

/* Generate the page URL bookmark section
   Set the item to the value specified
   Updating if it exists, creating if it does not
 */
function sethashparam(item, value)
{
	// First get all hash values
	var location = window.location.href;
	var hashValues = []; //new Array();
	var hashFound = false;
	
	// If there is a # in the page url
	if (location.indexOf("#") != -1)
	{
		hash = location.substr(location.indexOf("#")+1);
		
		// Split each hash item from the url
        var hashSplitItems = hash.split('&');
		
		// If items retreived from the split
		if (hashSplitItems.length)
		{
			// foreach hashValue
			for (var i in hashSplitItems)
			{
				// Split equals sign
				var thisHash = hashSplitItems[i].split('=');
				
				// If this hash is a valid item,value pair
				if (thisHash.length == 2)
				{
					var hashName = thisHash[0];
					var hashValue = thisHash[1];
					
					// If this is the item we are editing
					// Set the array to the new value
					if (hashName == item)
					{
						hashValues[i] = new Array(hashName, value);
						hashFound = true; // The hash was found
					}
					// Set item array for this hash item
					else
					{
						hashValues[i] = new Array(hashName, hashValue);
					}
				}
			}
		}
	}
	
	// If the hash item to set was not found
	// Put it into the array
	if (hashFound == false)
	{
		hashValues[hashValues.length] = new Array(item, value);
	}
	
	
	// Create the hashstring from the array
	var hashString = "";
	for (var i = 0; i < hashValues.length; i++)
	{
		// Create the first element
		if (hashString.length == 0)
		{
			hashString = hashValues[i][0] + "=" + hashValues[i][1];
		}
		// Create alternate elements
		else
		{
			hashString += "&" + hashValues[i][0] + "="+ hashValues[i][1];
		}
	}
	
	// Set the hash value in the URL
	window.location.hash = hashString;
}

/* Navigate to the specified page */
function nav(location)
{
	top.self.location.href = location;
}

/* Open the specified page in a new window */
function popup(pageurl)
{
	window.open (
		pageurl,
		'album_pop',
		"width=" + (screen.width - 9) + "," +
		"height=" + (screen.height - 100) +	"," +
		"toolbar=no,resizable=yes,scrollbars=yes,location=no,top=0,left=0,fullscreen=0,status=yes");
	return false;	
}

/* Change tabpage on the picture information
   page according to the tab that was clicked */
function change_tabpage(pageID)
{
	// Tab - Info
	if (pageID == 1)
	{
		document.getElementById('tabbar_info').className = "tabbar_info tabinfo_selected";
		document.getElementById('tabbar_pricing').className = "tabbar_pricing tabinfo_selected";
		document.getElementById('tabbar_enquire').className = "tabbar_enquire tabinfo_selected";
		
		document.getElementById('tabinfo').style.display = "block";
		document.getElementById('tabpricing').style.display = "none";
		document.getElementById('tabenquire').style.display = "none";
	}
	// Tab - Pricing
	else if (pageID == 2)
	{
		document.getElementById('tabbar_info').className = "tabbar_info tabpricing_selected";
		document.getElementById('tabbar_pricing').className = "tabbar_pricing tabpricing_selected";
		document.getElementById('tabbar_enquire').className = "tabbar_enquire tabpricing_selected";
		
		document.getElementById('tabinfo').style.display = "none";
		document.getElementById('tabpricing').style.display = "block";
		document.getElementById('tabenquire').style.display = "none";
	}
	// Tab - Enquire
	else if (pageID == 3)
	{
		document.getElementById('tabbar_info').className = "tabbar_info tabenquire_selected";
		document.getElementById('tabbar_pricing').className = "tabbar_pricing tabenquire_selected";
		document.getElementById('tabbar_enquire').className = "tabbar_enquire tabenquire_selected";
		
		document.getElementById('tabinfo').style.display = "none";
		document.getElementById('tabpricing').style.display = "none";
		document.getElementById('tabenquire').style.display = "block";
	}
	
	// Update the page url
	sethashparam('tabpage', pageID);
	
	// Cancel page navigation
	return false;
}

/* Validate enquiry form */
function validateenquiry(ajax)
{
	var picid = document.getElementById('picid').value;
	var name = document.getElementById('name').value;
	var email = document.getElementById('email').value;
	var message = document.getElementById('message').value;
	var captcha = document.getElementById('security_code').value;
	
	var error = false;
	var errormsg = '';
	
	/* Check Name Field */
	if(name.length < 3)
	{
		document.getElementById('nametxt').style.color = '#FFCC00';
		error = true;
		errormsg += 'The name field is required and must be two or more characters!<br />';
	}
	else
	{
		document.getElementById('nametxt').style.color = '#FFF';
	}
	
	/* Check E-mail field */
	if(chkemail(email) == false)
	{
		document.getElementById('emailtxt').style.color = '#FFCC00';
		error = true;
		errormsg += 'The specified email address is invalid!<br />';
	}
	else
	{
		document.getElementById('emailtxt').style.color = '#FFF';
	}
	
	/* Check the user typed a message */
	if(message.length < 10)
	{
		document.getElementById('messagetxt').style.color = '#FFCC00';
		error = true;
		errormsg += 'Please enter a longer message to send with your enquiry!';
	}
	else
	{
		document.getElementById('messagetxt').style.color = '#FFF';
	}
	
	/* Process the results */
	if(error == true)
	{
		document.getElementById('messagearea').style.color = '#FFCC00';
		document.getElementById('messagearea').innerHTML = '<strong>Please correct the errors listed below</strong><br />' + errormsg;
	}
	else
	{
		if(ajax == true)
		{
			//send the form via ajax so the result can be in this div box, otherwise fall back to sending it without JS
			document.getElementById('messagearea').innerHTML = 'Sending your message.<br />Please wait...';
			sendajax('enquiry','name='+name+'&email='+email+'&message='+message+'&picid='+picid+'&security_code='+captcha+'&ajax=true');
		}
		else
		{
			document.getElementById('messagearea').style.color = '#FFF';
			document.getElementById('messagearea').innerHTML = 'Thanks :) Please wait...' + errormsg;
			return true;
		}
	}
	
	return false;
}

/* Check Email Addresses is Valid */
function chkemail()
{
	var emailaddr
	emailaddr = document.getElementById('email').value;
	var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if(emailaddr.match(pattern))
	{
		return true;
	}
	else
	{
		return false;
	}
}

/* Color Picker Popup */
function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=335');");
	
	return false;
}

/* Captcha Processing */
function clearcode(){
	var codebox = document.getElementById('security_code').value
	if(codebox == 'Enter the code shown above'){
		document.getElementById('security_code').value = '';
		document.getElementById('security_code').style.color = '#000000';
	}
}

/* Refresh the captcha image */
function refreshimage(){
	document.getElementById('captcha').src = '/captcha/image/?' + Math.random();
	return false;
}

/* Navigate pictures via the left & right keyboard keys */
function pagenavigation(e)
{
	// Firefox uses the parameter e in the function call
	// Internet explorer uses event for the event data.
	if (!e)
	{
		e = event;
	}
		
	var thisDocument = location.href;
	if(keysEnabled && thisDocument.indexOf("/picture/") != -1)
	{
		var keyCode = e.which;
		if (keyCode == undefined)
		{
			keyCode = e.keyCode;
		}
		
		var albumID = document.getElementById('albumid').value;
		var pictureNumber = parseInt(document.getElementById('pictureNumber').value);
		var fullscreen = false;
		
		// Fullscreen mode?
		if(thisDocument.indexOf("/picture/full") != -1)
		{
			fullscreen = true;
		}
		
		// Back Button
		if (keyCode == 37 || keyCode == 66) // Left Arrow OR b button
		{
			loadPicture(albumID, (pictureNumber - 1));
		}
		// Next Button
		else if (keyCode == 39 || keyCode == 78) // Right Arrow OR n button
		{
			loadPicture(albumID, (pictureNumber + 1));
		}
	}
}

/* Builds the navigation links for an album based on the Picture Number and Number of Pictures */
function BuildPictureNavLinks(picno, noofpics)
{
	var albumid = document.getElementById("albumid").value;
	var picno = parseInt(picno);
	var noofpics = parseInt(noofpics);
	var recstart = 1;
	var recend = noofpics;
	var dostartdots = false;
	var doenddots = false;
	var menuList = document.getElementById("menu");
	
	// Clear all nodes from the menu
	while (menuList.hasChildNodes())
	{
		menuList.removeChild(menuList.firstChild);
	}
	
	
	// If part of the last 6 pictures
	if(picno <= Math.ceil(11/2))
	{
		recstart = 1;
		if(noofpics <= 11)
		{
			recend = noofpics;
		}
		else
		{
			recend = 11;
			doenddots = true;
		}
	}
	// if part of the first 6 pictures
	else if(picno > (noofpics - Math.ceil(11/2)))
	{
		if(noofpics <= 11)
		{
			recstart = 1;
		}
		else
		{
			dostartdots = true;
			recstart = noofpics - 11;
		}
		recend = noofpics;
	}
	// any where between the first and last 6 pictures
	else
	{
		dostartdots = true;
		recstart = (picno - 5);
		recend = (picno + 5);
		doenddots = true;
	}
		
	//create the list elements
	if(dostartdots === true)
	{
		var item = document.createElement("LI");
		item.innerText = '...';
		
		menuList.appendChild(item);
	}
	
	// For every element in the menu	
	for(var i = recstart; i <= recend; i++)
	{
		var item = document.createElement("LI");
		
		// If this picture is the current one, bold it
		if(picno == i)
		{
			item.innerHTML = '<a href="/jump_to_picture/' + albumid + '/' +  i + '/" style="border-bottom:dotted 1px #FFF;"><strong>' + i + '</strong></a>';
		}
		else
		{
			item.innerHTML = '<a href="/jump_to_picture/' + albumid + '/' + i + '/">' + i + '</a>';
		}
		
		menuList.appendChild(item);
	}
	
	if(doenddots === true)
	{
		var item = document.createElement("LI");
		item.innerText = '...';
		
		menuList.appendChild(item);
	}
}

function enablekeys(){ keysEnabled = true; }
function disablekeys(){ keysEnabled = false; }
