// This function only runs the slideshow. It takes the slides (HTML list items), 
// piles them on top of each other, and then moves through them.
// Speed is controlled through JS, but dimensions are controlled through CSS.
var switchSlide;
var pauseTime = 5000;	// Default speeds
var fadeTime = 1000;
function slideSwitch($nextSlide){
	jQuery('.slideshow').each(function(i){
		if ($(this).children().size() > 1) {
			var $active = $(this).children('li.active');
			if ($nextSlide)
				var $next = $nextSlide;
			else
				var $next = ($active.next().length) ? $active.next() : $(this).children('li:first');
		   
			$active.addClass('last-active');
			$next.css({opacity: 0.0})
				.addClass('active')
				.animate({opacity: 1.0}, fadeTime, function() {
					$active.removeClass('active last-active');
				});
		}
	});
}
jQuery(document).ready( function($) {
    // Make slideshow active if JS is enabled
    $('.gallery').addClass('slideshow');
	$('.slideshow').each(function(i){
		$(this).children('li:first').addClass('active');
	});
    switchSlide = setInterval( "slideSwitch(0)", pauseTime );
	
	// Navigation fix for IE6 and JS effects
	$("ul.nav ul.slide").addClass("jshide");
	$('ul.nav li').hover(function() {
		if ($(this).is('.current_page_item')) {
			$(this).removeClass('current_page_item');
			$(this).data('current', 'current_page_item')
		}
		$(this).addClass('hover');
		//$(this).children("ul.transition").fadeIn();
	}, function() {
		$(this).removeClass('hover');
		$(this).addClass($(this).data('current'));
		//$(this).children("ul.transition").fadeOut();
	});
	
	// Pop up Share form.
	$('div#main ul.snippets li a.emailshare').click(function(){
		$('div#share_email').show();
		$('div#share_email').parent().css('zIndex', 300);
		this.blur();
		return false;
	});
	$('div#share_email').click(function(){
		$('div#share_email').show();
	});
	$(document).bind('click', function(e){
		var $clicked = $(e.target);
		if (!($clicked.is('#share_email') || $clicked.parents().is('#share_email'))) {
			$('div#share_email').hide();
		}
	}); 

	$('div#share_email form input:text').focus(textFocus);
	$('div#share_email form input:text').blur(textBlur);

	// Added for gift certificates
	$('p.expander span').css('cursor', 'pointer').click(function(){
		$(this).parent().next('.expandable').slideToggle();
	});
	$('.expandable').hide();

	// Suggestions (Catalog)
	if ($('div.review-suggestions ul.menu li a').length != 0) { /* UPDATED 091228 */
		var selectedOption;
		$('div.review-suggestions ul.menu li a.selected').each(function(i){
			selectedOption = this.hash;
		});
		$('div.review-suggestions').children('.option').hide().filter(selectedOption).show();
		$('div.review-suggestions ul.menu li a').click(function(){
			$('div.review-suggestions ul.menu li a').removeClass('selected');
			$(this).addClass('selected');
			
			$('div.review-suggestions .option').hide().filter(this.hash).show();//.animate({opacity: 1.0}, 1000);
			
			$(this).blur();
			return false;
		});
	}/* UPDATED 091228 */

	/*$('div.suggestions').children('a.details-pop').hover(function() {
		$('div.suggestions').children('.view-details').show();
	}, function() {
		$('div.suggestions').children('.view-details').hide();
	}).*/
	$('div.option a.details-pop').hover(function() {
		$(this).parent().parent().children('.view-details').show();
		$(this).parent().parent().css('z-index',500);
	}, function() {
		$(this).parent().parent().children('.view-details').hide();
		$(this).parent().parent().css('z-index',0);
	}).click(function(){
		$(this).blur();
		return false;
	});
	
	// Open all images in colorbox
	$("a").filter(function(){
		//return($(this).find('img').length); // find out if anchor contents is an image
		if ($(this).attr('href')) {
			return $(this).attr('href').match(/\.(?:jpe?g|gif|png)\b/i); // find out if anchor link is an image
		}
	}).colorbox({rel:$(this).attr("id"), maxWidth:"100%", maxHeight:"100%"});
});

function textFocus(){
	$(this).addClass("active");
	if($(this).attr("value") == $(this).attr("title") || !$(this).attr("title")){
		$(this).attr("title", $(this).val());
		$(this).attr("value", "");
	}
};
function textBlur(){
	$(this).removeClass("active");
	if($(this).attr("value") == "") $(this).attr("value", $(this).attr("title"));
};

// Email Obfuscator
window.onload = emailUnobsfuscate;
function emailUnobsfuscate() 
{
	// find all links in HTML
	var link = document.getElementsByTagName && document.getElementsByTagName("a");
	var email, i;
	
	// examine all links
	for (i = 0; link && i < link.length; i++) {
		// does the link have use a class named "email"
		if ((" "+link[i].className+" ").indexOf(" email ") >= 0) {
			// get the obfuscated email address
			email = link[i].firstChild.nodeValue || "";
			
			// transform into real email address
			email = email.replace(/dot/ig, ".");
			email = email.replace(/\(at\)/ig, "@");
			email = email.replace(/\s/g, "").toLowerCase();
			
			// is email valid?
			if (/^[^@]+@[a-z0-9]+([_\.\-]{0,1}[a-z0-9]+)*([\.]{1}[a-z0-9]+)+$/.test(email)) {
				// change into a real mailto link
				link[i].href  = "mailto:" + email;
				link[i].firstChild.nodeValue = email;
			}
		}
	}
};




function shareFormSubmit() {
	WAValidateEM(document.getElementById('share_email_form').email_to,document.getElementById('share_email_form').email_to.value,'- Invalid to email address',document.getElementById('share_email_form').email_to,0,true);
	WAValidateEM(document.getElementById('share_email_form').email_from,document.getElementById('share_email_form').email_from.value,'- Invalid from email address',document.getElementById('share_email_form').email_from,0,true);
	WAAlertErrors('The following errors were found','Correct invalid entries to continue',true,false,false);
	if (document.MM_returnValue) {
		tForm = document.getElementById('share_email_form');
		var postForm = "email_to=" + tForm.email_to.value + "&email_from=" + tForm.email_from.value + "&page_location=" + tForm.page_location.value + "&test_var=" + tForm.test_var.value;
		var http = new XMLHttpRequest();
		http.open("POST", tForm.sub_location.value, false);
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", postForm.length);
		http.setRequestHeader("Connection", "close");
		http.send(postForm);
		if (http.responseText) {
			var tResponse = http.responseText.replace(/^\s*/, "").replace(/\s*$/, "");
			if (tResponse != "sent") {
				alert(tResponse);
				return false;
			}
			else {
				$('div#share_email').hide();
				alert("Email has been sent!");
				return true;
			}
		}
	}
	return false;
}

function WAAddError(formElement,errorMsg,focusIt,stopIt)  {
  if (document.WAFV_Error)  {
	  document.WAFV_Error += "\n" + errorMsg;
  }
  else  {
    document.WAFV_Error = errorMsg;
  }
  if (!document.WAFV_InvalidArray)  {
    document.WAFV_InvalidArray = new Array();
  }
  document.WAFV_InvalidArray[document.WAFV_InvalidArray.length] = formElement;
  if (focusIt && !document.WAFV_Focus)  {
	document.WAFV_Focus = focusIt;
  }

  if (stopIt == 1)  {
	document.WAFV_Stop = true;
  }
  else if (stopIt == 2)  {
	formElement.WAFV_Continue = true;
  }
  else if (stopIt == 3)  {
	formElement.WAFV_Stop = true;
	formElement.WAFV_Continue = false;
  }
}

function WAValidateEM(formElement,value,errorMsg,focusIt,stopIt,required) {
  var isValid = true;
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    value = value.toLowerCase();
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/i;
    var emailPat = /^(.+)@(.+)$/i;
    var accepted = "\[^\\s\\(\\)><@,;:\\\\\\\"\\.\\[\\]\]+";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/i;
    var section = "(" + accepted + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + section + "(\\." + section + ")*$");
    var domainPat = new RegExp("^" + accepted + "(\\." + accepted +")*$");
    var theMatch = value.match(emailPat);
    var acceptedPat = new RegExp("^" + accepted + "$");
    var userName = "";
    var domainName = "";
    if (theMatch==null) {
      isValid = false;
    }
    else  {
      userName = theMatch[1];
      domainName = theMatch[2];
	  var domArr = domainName.split(".");
	  var IPArray = domainName.match(ipDomainPat);
      for (x=0; x < userName.length; x++) {
        if ((userName.charCodeAt(x) > 127 && userName.charCodeAt(x) < 192) || userName.charCodeAt(x) > 255) {
          isValid = false;
        }
      }
      for (x=0; x < domainName.length; x++) {
        if ((domainName.charCodeAt(x) > 127 && domainName.charCodeAt(x) < 192) || domainName.charCodeAt(x) > 255) {
          isValid = false;
        }
      }
      if (userName.match(userPat) == null) {
        isValid = false;
      }
      if (IPArray != null) {
        for (var x=1; x<=4; x++) {
          if (IPArray[x] > 255) {
            isValid = false;
          }
        }
      }
      for (x=0; x < domArr.length; x++) {
        if (domArr[x].search(acceptedPat) == -1 || domArr[x].length == 0 || (domArr[x].length < 2 && x >= domArr.length-2  && x > 0)) {
          isValid = false;
        }
      }
      if (domArr[domArr.length-1].length !=2 && domArr[domArr.length-1].search(knownDomsPat) == -1) {
        isValid = false;
      }
      if (domArr.length < 2) {
        isValid = false;
      }
    }
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}
function WAAlertErrors(errorHead,errorFoot,setFocus,submitForm,allowOverride)  { 
  if (!document.WAFV_StopAlert)  { 
	  document.WAFV_StopAlert = true;
	  if (document.WAFV_InvalidArray)  {  
	    document.WAFV_Stop = true;
        var errorMsg = document.WAFV_Error;
	    if (errorHead!="")
		  errorMsg = errorHead + "\n" + errorMsg;
		if (errorFoot!="")
		  errorMsg += "\n" + errorFoot;
		document.MM_returnValue = false;
		if (document.WAFV_Error!="")  {
		  if (allowOverride) {
		    if (confirm(errorMsg.replace(/&quot;/g,'"'))) {
			  document.MM_returnValue = true;
			  return;
			}
		  }
		  else {
		    alert(errorMsg.replace(/&quot;/g,'"'));
		  }
		}
		else if (submitForm)
		  submitForm.submit();
	    if (setFocus && document.WAFV_Focus)  {
		  if (document.getElementById(document.WAFV_Focus.name+"___Config") && document.WAFV_Focus.type.toLowerCase() == "hidden")  {
	        var theEditor = FCKeditorAPI.GetInstance(document.WAFV_Focus.name);
		    theEditor.EditorWindow.focus();
			setTimeout("setTimeout('document.WAFV_Stop = false;document.WAFV_StopAlert = false;',1)",1); 
		  }
		  else  {
		    document.tempFocus = document.WAFV_Focus;
			setTimeout("document.tempFocus.focus();setTimeout('document.WAFV_Stop = false;document.WAFV_StopAlert = false;',1)",1); 
		  }
        }
        else {
          document.WAFV_Stop = false;
          document.WAFV_StopAlert = false;
        }
        for (var x=0; x<document.WAFV_InvalidArray.length; x++)  {
	      document.WAFV_InvalidArray[x].WAFV_Stop = false;
	    }
	  }
	  else  {
        document.WAFV_Stop = false;
        document.WAFV_StopAlert = false;
	    if (submitForm)  {
	      submitForm.submit();
	    }
	    document.MM_returnValue = true;
	  }
      document.WAFV_Focus = false;
	  document.WAFV_Error = false;
	  document.WAFV_InvalidArray = false;
  }
}
