var isCounting = false;

var msgRequired = "This field is required!";
var msgNotAnEmail = "Please enter one valid email!";
var msgNotAListOfEmails = "One or more of the email address are invalid or not seperated by a comma!";
var msgMin1Max500Length = "This field must be between 1 and 500 characters long!";

var popup = null;

function hackLogin(url) {
	popup = window.open(url, "popup", "status=0,toolbar=0,width=250,height=250");
	window.setTimeout(hackRefresh, 500);
}
function hackRefresh() {
	popup.close();
	window.location.reload(true);
}

function showPopup(url, width, height) {
	window.open(url, "", "location=1,menubar=0,resizable=1,width=" + width + ",height=" + height);
}

/*
Validates a single form field with the given function and puts the error message after the form element
jq = jQuery select for single form element
fn = dod_is* function to execute for validation
msg = error message to display if failed
*/
function dod_validate(jq, fn, msg) {
	var value = $(jq).val();
	var valid = fn(value); 
	if (valid) {
		$(jq).siblings(".dod_error").hide();
		$(jq).siblings(".dod_error").html("");
	}
	else {
		$(jq).siblings(".dod_error").show();
		$(jq).siblings(".dod_error").html(msg);
	}
	return valid;
}

function dod_isMin1Max500(str) {
	if (!str) return false;
	str = trimString(str);
	return ((str.length > 0) && (str.length <= 500));
}

function dod_isEmail(str) {
	var regex = new RegExp("^[\\w-_\.+]*[\\w-_\.]\@([\\w]+\\.)+[\\w]+[\\w]$");
	return (regex.test(str) && str!=("example@email.com"))
}

function dod_areEmails(str) {
	if (!str) return false;
	str = str.replace(";", ",");
	var strs = str.split(",");
	var regex = new RegExp("^[\\w-_\.+]*[\\w-_\.]\@([\\w]+\\.)+[\\w]+[\\w]$");
	var valid = true;
	for(var i=0;i<strs.length;i++) {
		var str0 = trimString(strs[i]);
		valid &= regex.test(str0);
	}
	return valid;
}

function dod_isNotEmpty(str) {
	if (!str)
		return false;
	else
		return (trimString(str).length > 0);
}

/*
function dod_isNumber(str) {
	return !isNaN(str);
}

function dod_isWholeNumber(str) {
	return (dod_isNumber(str) && (str.indexOf(".") < 0));
}

function dod_isPositiveNumber(str) {
	return (parseInt(str) > -1);
}
*/

/* pass in jQuery selector for input box and selector for length output */
function dod_showCharCount(jqInput, jqCount) {
	var text = $(jqInput).val();
	$(jqCount).html(text.length);
}
//var $ = jQuery.noConflict();
function initEmailForm() {
	
	jQuery("#emailForm #sendFrom").blur(function () { if (this.value.length > 0) validateEmailFriendForm(this.id); });
	jQuery("#emailForm #sendTo").blur(function () { if (this.value.length > 0) validateEmailFriendForm(this.id); });
	//jQuery("#emailForm #message").blur(function () { if (this.value.length > 0) validateEmailFriendForm(this.id); });
	//jQuery("#emailForm #message").blur(function () { dod_showCharCount("#emailForm #message", "#emailForm #messageLength"); });
	//jQuery("#emailForm #message").keypress(function () { dod_showCharCount("#emailForm #message", "#emailForm #messageLength"); });
	//jQuery("#emailForm #message").keyup(function () { dod_showCharCount("#emailForm #message", "#emailForm #messageLength"); });

	//jQuery("#emailOverlay a.send").focus(function() { });
	
	// On Email-Send, show Success
	jQuery("#emailSendButton").click(function() {
		submitEmailFriendForm();
	});
	
	// On success 'okay', reset the form, and hide the success box
	jQuery("#emailOverlay a.okay").click(function() {
		
		jQuery("#emailSuccessBox").hide();
		jQuery("#emailOverlayForm").hide();
		
	});
	
	jQuery("a.email").click(function() { 
		jQuery("#emailForm #sendFrom").focus(); // default focus to first form field on open
		jQuery("#emailForm .dod_error").html(""); // clear out previous/existing error messages
		jQuery("#emailForm #sendTo").val("");
		jQuery("#emailForm #sendTo").val("");
		//jQuery("#emailForm #message").val(defaultText);
		openEmailOverlay();
	});
	
}

function validateEmailFriendForm(field) {
	var control = $("#emailForm #" + field);
	switch (field) {
		case "sendFrom":
			return dod_validate(control, dod_isEmail, msgNotAnEmail);
		case "sendTo":
			return dod_validate(control, dod_areEmails, msgNotAListOfEmails);
		
		default:
			alert("ERROR: Field (" + field + ") not recognized!"); 
			return false;
	}
}

function submitEmailFriendForm() {
	var valid = true;
	valid &= validateEmailFriendForm("sendFrom");
	valid &= validateEmailFriendForm("sendTo");
	//valid &= validateEmailFriendForm("message");
	if (valid) {
		var subject = $('#sendFrom').val() + " recommends "+ $('#emailProductName').val();
		$('#emailSubject').val(subject)
		submitFormAJAX("#emailForm", resultEmailFriendForm);
	}
}

function resultEmailFriendForm(data) {
	// Copy email address to confirmation window
	
	var toStr = $('#sendTo').val();
	var addrArray = new Array();
	addrArray = toStr.split(",");
	var emailConfirmTextContent = "<ul style='list-style-type:disc;'>";
	for (a in addrArray ) {
 		emailConfirmTextContent = emailConfirmTextContent + "<li>"+addrArray[a]+"</li>"
	}
	emailConfirmTextContent = emailConfirmTextContent + "</ul>";
	
	$('#emailToSuccess').html(emailConfirmTextContent);
	
	
	
	//$('#emailToSuccess').text($('#emailForm #sendTo').val());
	
	// Hide Form
	$("#emailOverlay div.emailForm").hide();
	// Show Success
	$("#emailOverlay div.emailSuccess").show();
}

function clickTrackOmniture(city, action) {
	var s_265 = s_gi(g_om_account);
	s_265.linkTrackVars='prop16';
	s_265.prop16=city;
	s_265.tl(this,'o',action);  
}

function validateSubscribeForm() {
	if (dod_isEmail($("#subscribeForm #email").val()) && locationSelected()) return true;
	$("#subscribeFormError").fadeIn("slow"); // show error
	return false;
}

function locationSelected() {
	var index = document.getElementById("contactListId").selectedIndex;
	var location = document.getElementById("contactListId").options[index].value;
	return (location != "");
}

function locationSelected2() {
	var index = document.getElementById("contactListId2").selectedIndex;
	var location = document.getElementById("contactListId2").options[index].value;
	return (location != "");
}
function submitSubscribeForm() {
	if (validateSubscribeForm()) {
		setCookie("firstTimeCookie", "firstTimeCookie", "30");
		$("#subscribeFormError").hide();
		$("#subscribeFormSuccess").fadeIn("slow");
		window.setTimeout('$("#subscribeFormSuccess").fadeOut("slow")', 5000);
		submitFormAJAX("#subscribeForm", resultSubscribeForm);
		clickTrackOmniture($("#subscribeForm #contactListId option:selected").text(), 'subscribe - top nav');                                  
	}
}
                             
function resultSubscribeForm(data) {        
}

function validateSubscribeForm2() {
	if (dod_isEmail($("#subscribeForm2 #email2").val()) && locationSelected2()) return true;
	$("#subscribeForm2 #subscribeFormError2").fadeIn("slow"); // show error
	return false;
}

function submitSubscribeForm2() { submitSubscribeForm2('other'); }
function submitSubscribeForm2(where) {
	if (validateSubscribeForm2()) {
		$("#subscribeForm2 #subscribeFormError2").hide();
		$("#subscribeForm2 #subscribeFormSuccess2").fadeIn("slow"); 
		window.setTimeout('$("#subscribeForm2 #subscribeFormSuccess2").fadeOut("slow")', 5000);
		submitFormAJAX("#subscribeForm2", resultSubscribeForm2);
		clickTrackOmniture($("#subscribeForm2 #contactListId2 option:selected").text(), 'subscribe - ' + where);
	}
}

function resultSubscribeForm2(data) {
}


function submitForm(formID) {
	$(formID).submit();
}

function submitFormAJAX(formID, resultFunction) {
	var action = $(formID).attr("action");
		if (!resultFunction) resultFunction = resultFormAJAX;
		$.post(action, $(formID).serialize(), function (data) { resultFunction(data); }, "JSON");
		
		/*
		$.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				url: action,
				data: $(formID).serialize(),
				dataType: "json",
				success: function (data) { resultFunction(data); },
				error : function (data) { emailErrorFunction(data);}
		});
		
		*/
}
function resultFormAJAX() {
	alert("DEFAULT AJAX RESPONSE: " + data);
}

var secondsLeft = 0; //(9 * 24 * 60 * 60) + (0 * 60 * 60) + (0 * 60);

function showTimeLeft() {
	isCounting = true; // set global flag to prevent duplicates
	if (secondsLeft > 0) {		
        var days = Math.floor(secondsLeft / 60 / 60 / 24);
        var hours = Math.floor((secondsLeft / 60 / 60) % 24);
        var mins = Math.floor((secondsLeft / 60) % 60);
        var secs = Math.floor((secondsLeft % 60));

        var text = "";
		if (days > 0) {
			text += addUnitText("day", days);
			text += " " + addUnitText("hr", hours);
		} else if (hours > 0) {
			text += addUnitText("hr", hours);
			text += " " + addUnitText("min", mins);
		} else {
			text += addUnitText("min", mins);
			text += " " + addUnitText("sec", secs);
		}

        $("#timeLeft").html(text);
        
        secondsLeft = secondsLeft - 1;
        window.setTimeout("javascript:showTimeLeft();", 1000);
    } else {
		$("#timeLeft").html("Expired!");
		$("#product-detail").addClass("expired");
    }
}

function addUnitText(unit, value) {
	if (value == 0)
		return "";
	else if (value == 1)
		return value + " " + unit;
	else
		return value + " " + unit + "s";
}


// Check server side error
function getServerError(data) {
    var serverErrorHash = [];
    var serverError = "";
    if (data._ERROR_MESSAGE_LIST_ != undefined) {
        serverErrorHash = data._ERROR_MESSAGE_LIST_;
        serverErrorHash.each(function(error) {
            serverError += error.message;
        });
    }
    if (data._ERROR_MESSAGE_ != undefined) {
        serverError = data._ERROR_MESSAGE_;
    }
    return serverError;
}


function serialize(_obj)
{
   // Let Gecko browsers do this the easy way
   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined')
   {
      return _obj.toSource();
   }

   // Other browsers must do it the hard way
   switch (typeof _obj)
   {
      // numbers, booleans, and functions are trivial:
      // just return the object itself since its default .toString()
      // gives us exactly what we want
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;

      // for JSON format, strings need to be wrapped in quotes
      case 'string':
         return '\'' + _obj + '\'';
         break;

      case 'object':
         var str;
         if (_obj.constructor === Array || typeof _obj.callee !== 'undefined')
         {
            str = '[';
            var i, len = _obj.length;
            for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
            str += serialize(_obj[i]) + ']';
         }
         else
         {
            str = '{';
            var key;
            for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
            str = str.replace(/\,$/, '') + '}';
         }
         return str;
         break;

      default:
         return 'UNKNOWN';
         break;
   }
}

function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
		    c_start=c_start + c_name.length+1;
		    c_end=document.cookie.indexOf(";",c_start);
		    if (c_end==-1) 
		    	c_end=document.cookie.length;
		    return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	
	return "";
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

var printwindow;
function popprintwindow(url)
{
	printwindow=window.open(url,'printcoupon','height=900,width=700,resizable=yes,status=yes,scrollbars=yes');
	if (window.focus) {printwindow.focus()}
}


function trimString(sString)
{
while (sString.substring(0,1) == ' ')
{
sString = sString.substring(1, sString.length);
}
while (sString.substring(sString.length-1, sString.length) == ' ')
{
sString = sString.substring(0,sString.length-1);
}
return sString;
} 

/* OVERLAYS --------------------------------------------------------------------------------------------------------- */
$(document).ready(function(){
	overlayOpen = false;				
	$(window).resize(function() {
		if (overlayOpen == true) {
			posx = $("body").width();
				posx = Math.round(posx/2) - ($(".overlay").width()/2);
		$(".overlay").css("left",posx);
		}
		else {
			return false;
		}
	});
	
	
	// On success 'okay', reset the form, and hide the success box
	$("#emailOverlay a.okay").click(function() {
		
		$("#emailSuccess").hide();
		//$("#emailForm").reset();
//		$("#emailOverlay div.emailSuccess").hide(function() {
//			// Reset it to open the form when you click the email link
//			$("#emailOverlay div.emailForm").show();
//		});
		overlayOpen = false;
	});
	

	// Close the mask Options
	$(".close").live("click", function() {
		closeLightbox();
		overlayOpen = false;
	});
});
	// Trigger the Email Overlay
	function openEmailOverlay()
	{
		overlayOpen = true;
		//$("#emailCapture").hide();
		$("#emailSuccess").hide();
		$(".overlay").before("<div id='exposeMask'></div>");
		$("#exposeMask").fadeIn(function() {
			posx = $("body").width();
				posx = Math.round(posx/2) - ($(".overlay").width()/2);						
			$(".overlay").show().css("left",posx);
		});
		$("#emailOverlayForm").show();
		
	}
	// On ReSize, change the overlay placement 	
	
	
	function closeLightbox() {
		$(".overlay").fadeOut(300, function() {
			$("#exposeMask").fadeOut(300).remove();
		});
		$("#emailOverlay div.emailSuccess").hide(function() {
			// Reset it to open the form when you click the email link
			$("#emailOverlay div.emailForm").show();
		});
		$("#giftOverlay div.giftSuccess").hide(function() {
			// Reset it to open the form when you click the email link
			$("#giftOverlay div.giftForm").show();
		});
	}


