$(document).ready(function() {	

	
	doMainNav();
	
	checkLayout();
	
	doHours();
	
	$("#holiday-hours-link").live("click", function(evt) {
		evt.preventDefault();
		
		$.blockUI({
			css: {
				padding: 0, 
				margin: 0, 
				top: "50%",
				left: "50%",
				position: "absolute",
				marginLeft: "-340px",
				marginTop: "-340px",
				border: "none",
				backgroundColor: "transparent"
			},
			message: "<div class=\"closeImage\" title=\"Click to close.\" style=\"opacity:0.88;\"></div><img src=\"/media/images/holiday-hours.png\" alt=\"Click to close.\" title=\"Click to close.\" height=\"680\" width=\"680\" style=\"cursor:pointer;\" class=\"largeImageView\" />", 
			fadeIn: 250, 
			fadeOut: 250, 
			onBlock: function() {
				var left = ($(".largeImageView").width()-34);
				$(".closeImage").css("top", "4px").css("left", left+"px");
				$(".closeImage, .largeImageView").live("click", function(evt) {
					$.unblockUI();
				});
			}
		});
	});
	
	// init newsletter form validation
	if ($('#frmEnews').length > 0) {
		//$('#frmEnews').ketchup();
		// validate firstname
		$("#firstname").live("blur", function(evt) {
			var field = evt.target.id;
			
			if (!$(this).val()) {
				//console.log(field+" is a required field.");
				$("label[for="+field+"]").addClass("required");
				return false;
			} else {
				$("label[for="+field+"]").removeClass("required");
				return true;
			}
			
		});
		
		// validate lastname
		$("#lastname").live("blur", function(evt) {
			var field = evt.target.id;
			
			if (!$(this).val()) {
				//console.log(field+" is a required field.");
				$("label[for="+field+"]").addClass("required");
				return false;
			} else {
				$("label[for="+field+"]").removeClass("required");
				return true;
			}
			
		});
		
		// validate email address
		$("#email").live("blur", function(evt) {
			var field = evt.target.id;
			
			if (!$(this).val()) {
				//console.log(field+" is a required field.");
				$("label[for="+field+"]").addClass("required");
				return false;
			} else if (!isValidEmail($(this).val())) {
				//console.log(field+" is not a valid email address.");
				$("label[for="+field+"]").addClass("required");
				return false;
			} else {
				$("label[for="+field+"]").removeClass("required");
				return true;
			}
			
		});
		
		// validate postal code
		$("#postalcode").live("blur", function(evt) {
			var field = evt.target.id;
			
			if (!$(this).val() || !validateCPC($(this).val())) {
				//console.log(field+" is a required field.");
				$("label[for="+field+"]").addClass("required");
				return false;
			} else {
				$("label[for="+field+"]").removeClass("required");
				return true;
			}
			
		});
		
	}
	
	
	
	
	
	
	/* STORE SEARCH */
	// search query field, clear default valueon focus  if init val
	$("#frmSearch #searchField #query").live("focus", function(evt) {
		var val = $(this).val();
		var valAlt = $(this).attr("alt");
		if (val == valAlt) { $(this).val(""); }
	});
	// search query field, repopulate init val if left blank
	$("#frmSearch #searchField #query").live("blur", function(evt) {
		var val = $(this).val();
		var valAlt = $(this).attr("alt");
		if (val == "") { $(this).val(valAlt); }
	});
	// listen for enter key event, submit query if not blank
	$("#frmSearch #searchField #query").keyup(function(evt) {
		//alert(evt.keyCode);
		if (evt.keyCode == 13) {
			var val = $(this).val();
			var valAlt = $(this).attr("alt");
			if (val != "" && val != valAlt) { doStoreSearch(val); }
		}
	});
	// search button click event handler
	$("#frmSearch #searchButton #store-search").live("click", function(evt) {
		evt.preventDefault();
		var val = $("#frmSearch #searchField #query").val();
		var valAlt = $("#frmSearch #searchField #query").attr("alt");
		if (val != "" && val != valAlt) { doStoreSearch(val); }
	});
	

	
	// reset page posistion on resize
	$(window).bind("resize", checkLayout);
	
	
});

function doHours() {
	
	$.ajax({
		url: "/data/hours.xml?currTime=" + getTimeForURL(),
		type: "GET",
		dataType: "xml", 
		success: function(xml) {
			var returnString = "";
			var regularTitle = $(xml).find("regular").attr("title");
			var regularHours = $(xml).find("regular").text();
			var holidayTitle = $(xml).find("holiday").attr("title");
			var holidayHours = $(xml).find("holiday").text();
			
			if (regularHours != "") {
				returnString += "<div id=\"regularHours\">\n";
				returnString += "\t<div class=\"title\">"+regularTitle+"</div>\n";
				returnString += "\t<div class=\"hours\">"+regularHours+"</div>\n";
				returnString += "</div>\n";
			}
			
			if (holidayHours != "") {
				returnString += "<div id=\"holidayHours\">\n";
				returnString += "\t<div class=\"title\">"+holidayTitle+"</div>\n";
				returnString += "\t<div class=\"hours\">"+holidayHours+"</div>\n";
				returnString += "</div>\n";
			}
			
			$("#hours .hoursBlock").append(returnString);
		}
		
	});
	
	// mall hours over/out event handler
	$("#hours .titleBar").live("mouseover", function(evt) {
		$("#hours .titleBar").addClass("titleBarOver");
		$("#hours .hoursBlock").stop(true, true).slideDown("fast");
	});
	$("#hours").live("mouseleave", function(evt) {
		$("#hours .hoursBlock").stop(true, true).slideUp("fast", function() {
			$("#hours .titleBar").removeClass("titleBarOver");
		});
	});
	
	
}


// do store serach
function doStoreSearch(q) {
	//console.log("doStoreSearch('"+q+"')");
	var query = q;
	query = query.replace(/[^a-zA-Z 0-9]+/g, "");
	if (query) {
		window.location.href = "directory_results.php?q="+q;
	}
}


// check layout, if viewport smaller than site min-w/min-h set appropriate css...
// this is a workaround to deal with using absolute positioning and the 
// site falling outside of the viewport with no scrollbars...
function checkLayout() {
	var cssObj;
	var wrapper = $("#wrapper");
	var divW = wrapper.width();
	var divH = wrapper.height();
	var winW = $(window).width();
	var winH = $(window).height();
	
	// calculate widths, if viewport less than
	if (winW <= divW) {
		cssObj = {
			"left": "0", 
			"margin-left": "0"
		}
		wrapper.css(cssObj);
	} 
	
	// calculate heights, if viewport less than
	if (winH <= divH) {
		cssObj = {
			"top": "0", 
			"margin-top": "0"
		}
		wrapper.css(cssObj);
	}
	
	// calculate widths/heights, if viewport more than
	if (winW > divW && winH > divH) {
		cssObj = {
			"left": "50%", 
			"top": "50%", 
			"margin-left": "-"+divW/2+"px", 
			"margin-top": "-"+divH/2+"px"
		}
		wrapper.css(cssObj);
	}
	
	setOxfordPos();
}


function setOxfordPos() {
	var wrapperPos = $("#wrapper").offset();
	var wrapperHei = $("#wrapper").height();
	//console.log("left: "+wrapperPos.left+"\ntop: "+wrapperPos.top+"\nheight: "+wrapperHei);
	
	var cssObj = {
		"position": "absolute", 
		"left": wrapperPos.left, 
		"top": (wrapperPos.top + wrapperHei + 12)
	}
	$("#oxford").css(cssObj);
}


// transition all content into view
function bringItIn() {
	fadeItIn("#header", "normal");
	fadeItIn("#mainBG", "normal");
	fadeItIn("#fauxBG", "normal");
	fadeItIn("#content", "normal");
	fadeItIn("#galleryBar", "normal");
}


// set init content opacity to 0, setup for transition in
function hideItAll() {
	fadeItOut("#header", 0);
	fadeItOut("#mainBG", 0);
	fadeItOut("#fauxBG", 0);
	fadeItOut("#content", 0);
	fadeItOut("#galleryBar", 0);
}


function fadeItOut(el, speed) {
	if ($(el).length > 0) {
		$(el).fadeOut(speed);
	}
}


function fadeItIn(el, speed) {
	if ($(el).length > 0) {
		$(el).fadeIn(speed);
	}
}


function openBrWindow(theURL,winName,features) {
	window.open(theURL,winName,features);
}


function isValidEmail(strEmail){
	validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
	// search email text for regular exp matches
	if (strEmail.search(validRegExp) == -1) {
		//alert('A valid e-mail address is required.\nPlease amend and retry');
		return false;
	} 
	return true; 
}

function htmlentities(string, quote_style) {
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}



