/*********** HERO IMAGE NONSENSE **********/

HMIHeroFix = {}

HMIHeroFix.init = function(list) {
	for (var i = 0; i < list.length; i++) {
		HMIHeroFix.unhide(list[i]);
	}
}

HMIHeroFix.unhide = function(link) {
	for (var i = 0; i < link.childNodes.length; i++) {
		var node = link.childNodes[i];
		if (node.tagName == 'IMG') {
			if (!node.complete || (typeof node.naturalWidth != "undefined" && node.naturalWidth == 0)) {
				node.onload = HMIHeroFix.show;
			} else {
				HMIHeroFix.show(node);
			}
		}
	}
}
	

HMIHeroFix.show = function(img_node) {
	img_node = (img_node.tagName == 'IMG') ? img_node : this;
	img_node.setAttribute('class', 'firstIckyImage');
	img_node.setAttribute('className', 'firstIckyImage');
}

HMIHeroFix.start = function() {
	var img_one = document.getElementById('hero_image_0');
	if (img_one != null && (!img_one.complete || (typeof img_one.naturalWidth != "undefined" && img_one.naturalWidth == 0))) {
		setTimeout("HMIHeroFix.start();", 500);
	} else {
		$('#s1')
					.after('<div id="s1_nav"></div>')
					.cycle({
						fx:     'scrollLeft',
						speed:   300,
						timeout: 3000,
						pager: '#s1_nav'
		});
		HMIHeroFix.init($('.jsFunkyFix'));
	}
}


/*** JS FOR THE SITE NAV ***/

SiteNav = {
  map: [],
  anchors: ['dashboardDemographicReportsList', 'dashboardCallTrackingList', 'dashboardJobsList', 'dashboardAccountList' ]
}

SiteNav.openLocalDiv = function(target) {
		
  if (target.id == undefined) {
  	return;
  }
  var parts = target.id.split('_');  
  SiteNav.openDiv(document.getElementById(parts[0]), parts);
}

SiteNav.closeLocalDiv = function(target) {		
  if (target.id == undefined) {
  	return;
  }
  var parts = target.id.split('_');  
  SiteNav.closeDiv(document.getElementById(parts[0]), parts);
}

SiteNav.checkOpenness = function() {
  var parts = document.location.toString().split('#');
	SiteNav.openThings(parts);

}

SiteNav.openThings = function(parts) {

	var drc_id = [];
	var ctc_id = [];
	var ac_id = [];
  if (parts[1] == undefined) {
  	return;
  }

  if (parts[1] == SiteNav.anchors[0]) {
  	drc_id[0] = 'demographicReportsContainer';
  	SiteNav.openDiv(document.getElementById(drc_id), drc_id);
  }
  if (parts[1] == SiteNav.anchors[1]) {
  	ctc_id[0] = 'callTrackingContainer';
  	SiteNav.openDiv(document.getElementById('callTrackingContainer'), ctc_id);
  }
  if (parts[1] == SiteNav.anchors[3]) {
  	ac_id[0] = 'accountContainer';
  	SiteNav.openDiv(document.getElementById('accountContainer'), ac_id);
  }
}

SiteNav.linkOpen = function(link) {
  var parts = link.href.toString().split('#');
	SiteNav.openThings(parts);
}

SiteNav.openDiv = function(divEl, parts) {
	var tohide = document.getElementById(parts[0]+"_Show");
	var toshow = document.getElementById(parts[0]+"_Hide");	
  if (divEl != undefined) {
		divEl.style.display = 'block';	
		tohide.style.display = 'none';
		toshow.style.display = 'inline';
		
  }
}

SiteNav.closeDiv = function(divEl, parts) {
	var tohide = document.getElementById(parts[0]+"_Show");
	var toshow = document.getElementById(parts[0]+"_Hide");	
  if (divEl != undefined) {
		divEl.style.display = 'none';	
		tohide.style.display = 'inline';
		toshow.style.display = 'none';
		
  }
}

	
/***** JS FOR THE ACCOUNT PICKER IN THE DASHBOARD *******/
	
AccountPicker = {
	form: null
}

AccountPicker.init = function() {
  AccountPicker.form = document.forms.AccountPickerForm;
  var submie = document.getElementById('jsButtonClientGoSubmit');
  if (submie != undefined) {
  	submie.setAttribute('class', 'goneSubmit');
  	submie.setAttribute('className', 'goneSubmit');
  
  	seli = document.getElementById('client_id');
  	seli.onchange = AccountPicker.formSubmission;
  }
}
	
AccountPicker.formSubmission = function() {
  url = AccountPicker.form.action + '/' + this.name + '/' + this.value;
  window.location = url;
}


/************* JS FOR THE PRODUCT SEARCH ON PRODUCT PAGES **************/

ProductSearch = {
	value: ''
}

ProductSearch.init = function() {
  var searchForm = document.getElementById('ProductSearchForm');
  searchForm.onsubmit = ProductSearch.checkForm;
}

ProductSearch.checkForm = function() {
  ProductSearch.value = this.search.value;
  if (ProductSearch.value.length > 1) {
  	$.getJSON(
  		this.action + '/search/' + this.search.value + '/ajax/1',
  		ProductSearch.handleResponse
      );
  } else {
  	alert('Please enter a value to search against');
  }

  return false;
}

ProductSearch.handleResponse = function(data, status) {
  if (data) {
  	window.location = '/products/detail/id/' + ProductSearch.value;
  } else {
  	alert(ProductSearch.value + ' is not a valid job number');
  }
}


/************ FOR THE ROLL OVERS ON THE PRODUCT PAGES *************/

ImageSwitch = {
	mainImage: ''
}

ImageSwitch.init = function() {
  var wrapper = document.getElementById('frontBackView');
  ImageSwitch.mainImage = document.getElementById('jsShowProductImage');
  for (var i = 0; i < wrapper.childNodes.length; i++) {
  	var node = wrapper.childNodes[i];
  	if (node.tagName == 'A' && (node.getAttribute('class') == 'jsFrontBackLink' || node.getAttribute('className') == 'jsFrontBackLink')) {
  		node.onclick = ImageSwitch.swapImage;
  	}
  }
}

ImageSwitch.swapImage = function() {
  var from_link = this;
  var from_image = ImageSwitch.getImage(this);
  
  var to_link = ImageSwitch.mainImage;
  var to_image = ImageSwitch.getImage(ImageSwitch.mainImage);

  var new_href = from_link.href.replace('mimages', 'limages');
  var new_src = from_image.src.replace('timages', 'mimages');

  to_link.setAttribute('href', new_href);
  to_image.setAttribute('src', new_src);

  return false;
}

ImageSwitch.getImage = function(someLink) {
  for (i = 0; i < someLink.childNodes.length; i++) {
  	node = someLink.childNodes[i];
  	if (node.tagName == 'IMG') {
  		return node;
  	}
  }
}

/*************** FOR ADDING / DELETING ITEMS FROM THE LIGHTBOX *****************/

Lightbox = {
		toDelete: null,
		toAdd: null
}

Lightbox.remove = function() {
  Lightbox.toDelete = this.parentNode;
  $.getJSON(
  	this.href,
  	Lightbox.handleRemoveResponse
  );
  return false;
}

Lightbox.handleRemoveResponse = function(data, status) {
  if (data) {
  	Lightbox.toDelete.parentNode.removeChild(Lightbox.toDelete);
  } else {
  	alert('Unable to delete from lightbox.');
  }
}

Lightbox.add = function() {
  Lightbox.toAdd = this;
  $.getJSON(
  	this.href,
  	Lightbox.handleAddResponse
  );
  return false;
}

Lightbox.handleAddResponse = function(data, status) {
  if (data) {
  	Lightbox.toAdd.parentNode.removeChild(Lightbox.toAdd);
  	alert('Added to lightbox');
  }
}
	
/************** FOR THE PRODUCT BROWSING NORGIES (LEFT NAVIGATION ON PRODUCT PAGES) ***************/

ProductBrowse = {
	selected: null
}

ProductBrowse.init = function() {
	// on page load
  // assign all class jsLevelOneLinkActive's onclick to deflate
  // css has already set this to be "open, aka active"
	$('.jsLevelOneLinkActive').click(ProductBrowse.deflate);  

  // assign all class jsLevelOneLink'onclick to expand 
	$('.jsLevelOneLink').click(ProductBrowse.expand);
	
}

/**
* deflate will change the clicked on anchor tag css to look closed and hide the anchor tag's sibling UL
* 
* @date 05/04/09
* @author gbh 
*/

ProductBrowse.deflate = function() {

	// assign class name of THIS anchor just clicked on "active" to "not active"
	ProductBrowse.setClassName(this, 'jsLevelOneLink');

	// assign class name of THIS anchor just clicked on "active" anchor's enclosing li to "not active"
	// is there any reason to do this?
	ProductBrowse.setClassName(this.parentNode, 'levelOne');

	// assign the classname of THIS just clicked on's UL to one that is hidden so it disappears when the link is deflated	
	var childList = ProductBrowse.getChildListFromLink(this);

	ProductBrowse.setClassName(childList, 'browseListCategory');

	/**
	* at this point we have deflated the "active" link, 
	* jQuery click ADDs to the click event so it does deflate, then expand so, we need to unbind any previous assigned click events
	*
	* @date 05/01/09
	* @author gbh 
	*/
	
	$('.jsLevelOneLink').unbind('click');
	$('.jsLevelOneLink').click(ProductBrowse.expand);
	
	return false;
}

ProductBrowse.expand = function() {

	// when the expand function is called, we first want to close all 

	if (this.className == 'jsLevelOneLinkActive') {
	// just close it
		ProductBrowse.setClassName(this, 'jsLevelOneLink');	
//		ProductBrowse.setClassName(this.parentNode, 'levelOne');
		var subchildList = ProductBrowse.getChildListFromLink(this);
		ProductBrowse.setClassName(subchildList, 'browseListCategory');				
	
	} else {

		var browselist = document.getElementById('browselist_holder');
		var browselistlinks= browselist.getElementsByTagName('a');
	
		for (i=0; i<browselistlinks.length; i++) {
			if (browselistlinks[i].className == 'jsLevelOneLinkActive') {
				ProductBrowse.setClassName(browselistlinks[i], 'jsLevelOneLink');	
//				ProductBrowse.setClassName(browselistlinks[i].parentNode, 'levelOne');
				var subchildList = ProductBrowse.getChildListFromLink(browselistlinks[i]);
				ProductBrowse.setClassName(subchildList, 'browseListCategory');	
				// do we also need to go through the subchildlist, then though the LI's to the anchors to explicitly set the visibility on the anchors?			
			}	
		}
	
	
	
		// set class name of THIS just clicked on "non-active " anchor to "active"
		ProductBrowse.setClassName(this, 'jsLevelOneLinkActive');
	
		// set class name of THIS just clicked on's "non-active" anchor's enclosing li to "active"
//		ProductBrowse.setClassName(this.parentNode, 'levelOneActive');
	
		// set the classname of THIS just clicked on's UL to one that is visible so it appears	
		var childList = ProductBrowse.getChildListFromLink(this);
		ProductBrowse.setClassName(childList, 'browseListCategorySelected');
		
		// at this point we have an expanded an "active" link
		// set this link to have the expand function onlick again
		$('.jsLevelOneLinkActive').unbind('click');	
		$('.jsLevelOneLinkActive').click(ProductBrowse.expand);

	}
	
	return false;
}



ProductBrowse.getLinkFromLI = function(liEl) {
	for (var idx in liEl.childNodes) {
		var currNode = liEl.childNodes[idx];
		if (currNode.tagName == 'A') {
			return currNode;
		}
	}
	return false;
}

ProductBrowse.getChildListFromLink = function(linkEl) {
	if (linkEl.parentNode.tagName == 'LI') {
		for (var idx in linkEl.parentNode.childNodes) {
			var currNode = linkEl.parentNode.childNodes[idx];			
			if (currNode.tagName == 'UL') {
				return currNode;
			}
		}
	}
	return false;
}

ProductBrowse.setClassName = function(el, className) {
	el.setAttribute('class', className);
	el.setAttribute('className', className);
}

	
/***************** SEARCH BY THEME FUNCTIONALITY ***************/

ThemeSearch = {}
	
ThemeSearch.getTheme = function() {
  var parent = this.parentNode;

  while (true) {
  	if (parent.tagName == 'FORM') {
  		parent.submit();
  		return;
  	} else {
  		parent = parent.parentNode;
  		continue;
  	}
  }
}
	
ThemeSearch.hideGo = function() {
	this.setAttribute('class', 'goneSubmit');
	this.setAttribute('className', 'goneSubmit'); 
}
	
PerPage = {}
	
PerPage.setPerPage = ThemeSearch.getTheme;	
	
$(document).ready(function() {
	$('.jsThemeSelector').change(ThemeSearch.getTheme);
	$('.jsPerPageSelector').change(PerPage.setPerPage);

});	

/******************** Some stuff for the lite admin *********************/

SimpleEmail = {}

SimpleEmail.adminShowAndIn = function() {
//	alert('get id\'s of list of checked boxes');

	var thelist = document.getElementById('thelist');
	
	var checked_list = new Array();
	//loop through the list to get all the checked boxes and put them in an array
  for (i=0; i<thelist.elements.length; i++) {
		var checker = thelist.elements[i];

		if (checker.type == 'checkbox') {
  		if (checker.checked == true) {				
				checked_list.push(checker.value+" ");
			}
		}
	}
	//once you have the list of checked items, put it into the WHERE clause
	var andin = document.getElementById('andin');
	andin.innerHTML = checked_list;
}


SimpleEmail.checkboxWatcher = function() {	
//	alert('sit here and do nothing until any box in the thelist div is checked or unchecked then run adminShowAndIn');
	$('.emaillist').change(SimpleEmail.adminShowAndIn);
}		


SimpleEmail.testEmailWatcher = function() {
	// assign a function to the button
	$('#send_test').click(SimpleEmail.sendTestEmail);
}

SimpleEmail.sendTestEmail = function () {
//alert('hereh');
	// get the value of the input box
	var to_field = document.getElementById('alt_to');
	
	// this will go to the submitted form\'s action
	$("#ajaxtest").ajaxForm(function() {
			alert('You sent a test email.');
	});	

}


/***** JS FOR THE THEME PICKER IN THE JOB REQUEST FORM *******/

ThemePicker = {
	form: null
}

ThemePicker.init = function() {
		
	$('#product_type_id').change(ThemePicker.typeSelectChange);
	
}

	/*
	 *  run a function based on the incoming product id that gets all the themes from php and
	 *  puts it into a JSON object that can be set BACK into the select
	 *
	 */

ThemePicker.typeSelectChange = function() {

	// remove all the current option tags
	$("#theme").find('option').remove();
		
	$.getJSON(
		'/dashboard/requestajaxtheme',
		{productTypeId: this.value},
		ThemePicker.handleResponse
	);
}

ThemePicker.handleResponse = function(data, status) {

  if (data) {		
		$.each(data, function(key, value) {
			
			// set the theme selector with new values
			var themeselect = document.getElementById('theme');
			var counter=0;
			themeselect.options[counter] = new Option('None', 'none');
			$.each(data, function(key, val) {
				counter++;
				themeselect.options[counter] = new Option(key, val);
			});
		});

  } else {
  	alert('Nothing returned');
  }
}

/************ FOR THE NAVIGATION FROM AN ACTION TO A NAMED ANCHOR *************/

AnchorJump = {
	
}

AnchorJump.init = function(name) {
	window.location.hash = name;
}


