/* ****************************************
 * This file contains:
 * cartManager: utility object for managing cart cookies
 * array_search(): function for searching which index an element of an array is found at
 * get_cookie(), set_cookie(): functions for handling cookies
 * formTools: utility object for handling form functions (search bar, contact form)
 */

var cartManager = {
	add : function (id){
		var jobs = get_cookie('cart');
		if(jobs){
			jobs = jobs.split(',');
		} else {
			jobs = new Array();
			alert("Welcome to your job cart:\n\n Add as many jobs as you like, but don't forget to check out when you are done.");
		}
		if(jobs.length >= 30) {
			alert("Our cart can only handle 30 jobs at a time.\n\nPlease submit the jobs currently in your cart,\nthen you can add more.");
			return false;
		}
		if(array_search(id, jobs)>-1) return false;//don't add existing items
		jobs.push(id);
		//jobs.sort();
		var cookieString = jobs.join(",");
		set_cookie("cart", cookieString);
		this.update()
		return true;
	},
	
	checkItem : function (id){
		var jobs = get_cookie('cart');
		if(jobs){
			jobs = jobs.split(',');
			if(array_search(id, jobs)>-1) return true;//jobId found
		}
		return false;//either no jobs, or job not found
	},
	
	clear : function() {
		set_cookie("cart", "");//blank out the cart
		//this.update();
		document.location = document.location;
		return true;
	},
	
	confirmclear : function() {
		if(confirm("Are you sure you want to clear ALL items from your cart?")) {
			return this.clear();
		}
		return false;
	},
	
	confirmSend : function(target) {
		if(get_cookie('cart')==null)
			if(!confirm("Your cart is empty...\n\nYou may submit your contact info without any\njob information, someone will still contact you.\n\nDo you still want to continue?"))
				return false;
		document.getElementById(target).submit();
		return true;
	},
	
	del : function(id, delRow, refresh){
		var jobs = get_cookie('cart').split(',');
		var jobIndex = array_search(id, jobs);
		if(jobIndex != -1)
		jobs.splice(jobIndex, 1);
		var cookieString = jobs.join(",");
		set_cookie("cart", cookieString);
		this.update();
		if(refresh){
			document.location = document.location;
		}
	},
	
	toggleItem : function(target, jobId) {
		if(this.checkItem(jobId)){//item exists in cart
			this.del(jobId);
			target.src="/img/controls/addtocart.png";//update target image soruce
			target.title="Click to add this job to your cart";
		} else { //item was NOT in cart
			if(this.add(jobId)){//only toggle if add was successful
				target.src="/img/controls/remove.png";//update target image source
				target.title="This job is in your cart... click to remove";
			}
		}
	},
	
	update: function(){
		var cookie = get_cookie('cart');
		var jobs = {};
		if(cookie){
			var jobs = cookie.split(',');
		}
		var target = document.getElementById('cartText');
		if(target) {
			if(jobs.length){
				target.innerHTML = "Your cart contains "+jobs.length+" items";
			} else {
				target.innerHTML = "Your job cart is empty";
			}
		}
	}
};
window.onload=cartManager.update;//when page loads, display cart count

function array_search(needle, haystack)
{
	for(x=0;x<haystack.length;x++)
	{
		if(haystack[x] == needle)return x;
	}
	return -1;
}

function array_double_split(major, minor, target){//splits a string into an associative array assuming a major and minor delimiter
	var output = new Array();
	var majorList = target.split(major);
	for(minorItems in majorList){
		var temp = majorList[minorItems].split(minor);
		output[temp[0]] = temp[1];
	}
	return output;
}

function get_cookie (cookie_name)
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
  if(results)
    return(unescape(results[2]));
  else
    return null;
}

function set_cookie (name, value)
{
	var path = "/";
	var myDate=new Date();
	if(value != ""){ //empty cookies: Don't set date so they expire immediately
		myDate.setDate(myDate.getDate()+30);//set all cookies for 30 days
	}
	var cookie_string = name + "=" + escape ( value );
	cookie_string += "; expires=" + myDate.toGMTString();
	cookie_string += "; path=" + escape ( path );
	//cookie_string += "; domain=" + escape ( domain );
	document.cookie = cookie_string;
}

var formTools = {
	holdopen : function(status) { //opens and closes (boolean status) the overlay 
		document.getElementById('spotSearch').style.display = status?'block':'none';
		document.getElementById('overlay').style.display = status?'block':'none';
	},
	clearForm : function(target) { //resets the searchform to defaults
		var target = document.getElementById(target);
		target.reset();
		this.storeLast(target.id);//clear out form cookie
	},
	confirmClearForm : function(target) {//confirms before clearing data
		if(confirm("Are you sure you want to clear all personal data from this form?")){
			this.clearForm(target);
		}
	},
	storeLast : function(target) {
		var target = document.getElementById(target);
		var lastSearch = new Array();
		children = target.getElementsByTagName('select');
		for(child in children) {
			if(typeof(children[child])=='object'){
				lastSearch.push(children[child].name + "|" + children[child].selectedIndex);
			}
		}
		children = target.getElementsByTagName('textarea');
		for(child in children) {
			if(typeof(children[child])=='object'){
				finder = children[child];
				lastSearch.push(children[child].name + "|" + children[child].value);
			}
		}
		textSearch = target.getElementsByTagName('input');
		for(child in textSearch) {
			if(typeof(textSearch[child])=='object' && textSearch[child].name != 'submit'){
				lastSearch.push(textSearch[child].name + "|" + textSearch[child].value);
			}
		}
		set_cookie(target.id, lastSearch.join(","));
	},
	retrieveLast : function(target) {
		var target = document.getElementById(target);
		var lastSearch = get_cookie(target.id);
		if(lastSearch != null){
			var searchValues = array_double_split(",", "|", lastSearch);
			var children = target.getElementsByTagName('select'); //find all <select> objects
			for(child in children) {
				if(typeof(children[child])=='object'){
					var curObj = children[child].name;
					if(searchValues[curObj] != null)
						children[child].selectedIndex = searchValues[curObj];
				}
			}
			var children = target.getElementsByTagName('textarea'); //find all <textarea> objects
			for(child in children) {
				if(typeof(children[child])=='object'){
					var curObj = children[child].name;
					if(searchValues[curObj] != null)
						children[child].value = searchValues[curObj];
				}
			}
			textSearch = target.getElementsByTagName('input');//find all <input> objects
			for(child in textSearch) {
				if(typeof(textSearch[child])=='object' && textSearch[child].name != 'submit'){
					var curObj = textSearch[child].name;
					if(searchValues[curObj] != null)
						textSearch[child].value = searchValues[curObj];
				}
			}
		}
	},
	validate : function(target) {//validate that each field has a value
		var firstFail = null;
		var target = document.getElementById(target);
		var children = target.getElementsByTagName('select');
		for(child in children) {
			if(typeof(children[child])=='object'){
				if(children[child].selectedIndex < 1){
					if(firstFail == null) firstFail = children[child];//store first failure for scrolling
					this.showErrorState(children[child], 0);
				} else {
					this.showErrorState(children[child], 1);
				}
			}
		}
		var children = target.getElementsByTagName('input');
		for(child in children) {
			if(typeof(children[child])=='object' && children[child].name != 'submit'){
				if(children[child].value.length < 1){
					if(firstFail == null) firstFail = children[child];//store first failure for scrolling
					this.showErrorState(children[child], 0);
				} else {
					this.showErrorState(children[child], 1);
				}
			}
		}
		if(firstFail){
			//this.scrollToError(firstFail); //possible future functionality to scroll up to the missing info
			alert('Some required information is missing...\n\nPlease provide the required information to continue');
			return false;
		}
		return true;
	},
	submit : function(target, required){//"target" and "required" each must be a string element id
		if(!this.validate(required)){
			return false;
		}
		formTools.storeLast(target);
		return cartManager.confirmSend(target);
	},
	showErrorState : function(target, status) {//target must be an object, status is boolean
		target.style.backgroundColor = status?"#FFFFFF":"#FF0000";//illuminate red background on missing input
	}
}