//Gateway Prompt
var fpglobals = {
	baseurl: '',
	cookeDomain: '.bearflagwines.com'
};
fpglobals.gateway = new Gallo_Gateway({
	url: fpglobals.baseurl + 'resources/legal/disclaimer.html',
	cookie: "bfd-com-visited"
});
fpglobals.gateway.init();
function enterSite() {
	$("#ageVerify a").click(function() {
		fpglobals.gateway.ok();
		return false;
	}); 
}

//Check for cookie
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 "";
}


//for parsing query string and separating key value pairs
jQuery.query = function(s) {
	var r = {};
	var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
	q = q.replace(/\&$/, ''); // remove the trailing &
	jQuery.each(q.split('&'), function() {
		var splitted = this.split('=');
		var key = splitted[0];
		var val = splitted[1];
		// convert floats
		if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
 		// ignore empty values
		if (typeof val == 'number' || val.length > 0) r[key] = val;
	});
	return r;
}; 

//Preloading Background Image
var imagePath = "resources/images/";
newImage0 = new Image(2048, 900);
newImage0.src = imagePath + "bg_content.jpg";

//Meta Tags per page
var bearFlag = {};
var MetaTags = function(options) {
	this.config = {
		keywords: "white wine, red wine, table wine, blended wine, value wine, california wine, inexpensive wine, independent winery",
		desc: "Bear Flag is a top notch, affordable and creative line of  California blended wines by Beth and Hillary.",
		pageTitle: "Bear Flag Wines"
	};
	if (options) {
		jQuery.extend(this.config, options);
	};
};
MetaTags.prototype = {
	seoInit: function() {
		var tags = this;
		$(document).ready(function() {
			tags._changeMeta();
		});
	},
	_changeMeta: function() {
		var allMeta = $(document).find("head meta");
		var titleTag = $(document).find("head title");
		for(i = 0; i < allMeta.length; i++) {
			if (allMeta.eq(i).attr("name") == "description") {
				allMeta.eq(i).attr("content" , this.config.desc);
			} else if(allMeta.eq(i).attr("name") == "keywords") {
				allMeta.eq(i).attr("content" , this.config.keywords);
			}
		}
		document.title = this.config.pageTitle;
	}
};
// New Meta tag and title objects per page
bearFlag.findusSeo = new MetaTags({
	keywords: "white wine, red wine, table wine, blended wine, value wine, california wine, inexpensive wine, independent winery, wine retailers, liquor store",
	desc: "Locate a store near you that carries Bear Flag Wine. ",
	pageTitle: "Where to Buy | Bear Flag Wine"
});
bearFlag.contactSeo = new MetaTags({
	keywords: "wine, customer service, email us, contact us",
	desc: "Send in your questions, suggestions, rants and raves.",
	pageTitle: "Get in Touch | Bear Flag Wine"
});
bearFlag.ourartSeo = new MetaTags({
	keywords: "Edward Bertone, creative, graphic design, independent art, unique art, label art, wine labels",
	desc: "We asked eduardo bertone to make our wine labels - check them out!",
	pageTitle: "Label Art by Eduardo Bertone | Bear Flag Wine"
});
bearFlag.ourwineSeo = new MetaTags({
	keywords: "Our super secret wine recipie for the greatest blended red and white wines on the market.",
	desc: "unique qine, blended wine, red wine, white wine, table wine, alternitive wine, hip wine",
	pageTitle: "White and Red Blended Wines | Bear Flag Wine"
});
bearFlag.general = new MetaTags();
//End Meta Tags

//Switching nav images on hover
function switchOver(element) {
	var imageOff = $(element).attr("src");
	var imageOver = imageOff.replace("off", "over");
	$(element).attr("src", imageOver);
}
function switchOff(element) {
	var imageOver = $(element).attr("src");
	var imageOff = imageOver.replace("over", "off");
	$(element).attr("src", imageOff);
}
function navHover() {
	$("#nav ul li").not("#nav ul li.home").hover(function() {
		switchOver($(this).find("a img"));
	}, function() {
		switchOff($(this).find("a img"));
	});
}
function mainIconHover() {
	$("div.page a").hover(function() {
		switchOver($(this).find("img"));
	}, function() {
		switchOff($(this).find("img"));
	});
}
function secondaryHover() {
	//For secondary Icons rollover effects
	$("#secondary_icons a").hover(function() {
		var imgName = $(this).find("img").attr("src");
		if(imgName.match("_off")) {
			switchOver($(this).find("img"));
		}
	}, function() {
		var imgName = $(this).find("img").attr("src");
		if(imgName.match("_over")) {
			switchOff($(this).find("img"));
		}
	});
}

//Dragging effect
//Content div width based on number of pages
function setSiteWidth() {
	var pageCount = $("div.page").size();
	$("#content").width(pageCount*1024+2048);
}
function bgDrag() {
	var cancelArray = new Array("form", "object");
	$("#content").draggable({
		axis: "x",
		scroll: true,
		snap: true,
		stop: function() {
			var currentLeft = $("#content").css("left");
			var leftValue = parseInt(currentLeft.replace("px", ""))*(-1);
			if($("#content").css("left") >= "0px" && $("#content").css("left") <= "512px") {
				pageAnimate(0);
				jumpScrollbar(0);
			} else if($("#content").css("left") > "512px") {
				pageAnimate(-3072);
				jumpScrollbar(-3072);
			} else if(leftValue <= ($("#content").width()-2560) && leftValue >= ($("#content").width()-3072)) {
				pageAnimate(($("#content").width()-3072)*-1);
				jumpScrollbar(($("#content").width()-3072)*-1);
			} else if(leftValue > ($("#content").width()-2560)) {
				pageAnimate(-3072);
				jumpScrollbar(-3072);
			} else {
				jumpScrollbar(leftValue*-1);
			}
		},
		cancel: "form, object"
	});
}

//Set slider width
function scrollWidth() {
	//Left and Right buttons total 33 + Handlebar width of 245 = 278
	var wSlider = $(window).width() - 183;
	$("#slider").width(wSlider);
}
//Main Content Scrollbar
function scrollbar() {
	$("#anchor_left").click(function() {
		pageAnimate(0);
		jumpScrollbar(0);
	});
	$("#anchor_right").click(function() {
		pageAnimate(-7168);
		jumpScrollbar(-7168)
	});
	$("#slider").slider({
		max: 100,
		min: 0,
		value: 0,
		slide: function(event, ui) {
			//ui.value is percentage of handlebar moved relative to page width
			var fullWidth = $("#content").width()-3072;
			var currentPos = (ui.value/100*fullWidth)*-1;
			$("#content").animate({'left': currentPos}, 0);
		}
	});
}
function browserResize() {
	$(window).resize(function(){
		scrollWidth();
		scrollbar();
	});
}

//Load Twitter Feed
function newsUp(bottom) {
	$("#news_feed").animate({ bottom: 77 });
	$("#news_feed a.close").show();
	$("#news_feed a.close").click(function() {
		newsDown(bottom);
	}); 
}
function newsDown(bottom) {
	$("#news_feed").animate({ bottom: bottom });
	$("#news_feed a.close").hide();
}
//Get News Feed Height
function newsFeed() {
	var newsHeight = $("#news_feed").outerHeight();
	var bottom = (newsHeight - 59)*-1;
	$("#news_feed").css("bottom", bottom);
	$("#news_feed").show();
	$("#news_box").toggle(function(){
		newsUp(bottom);
	}, function() {
		newsDown(bottom);
	});
}

//Nav jump-to points
function pageAnimate(leftPos) {
	$("#content").animate({left: leftPos}, 700);
}
function jumpScrollbar(leftPos) {
	var fullWidth = $("#content").width()-3072;
	var scrollPos = (leftPos/fullWidth)*-100;
	$("#slider a").animate({left: scrollPos+"%"}, 500);
}
function pageload(hash) {
	//Check for gateway cookie to display page or disclaimer
	if (fpglobals.gateway.check()) {
		// hash doesn't contain the first # character.
		if(hash) {
			// restore ajax loaded state
			// alert("pageload: " + hash);
			if($.browser.msie) {
				// jquery's $.load() function does't work when hash include special characters like åäö.
				hash = encodeURIComponent(hash);
			}
			switch (hash) {
				case "ourwine":
					pageAnimate(0);
					jumpScrollbar(0);
					autoPopup("our-wine");
					bearFlag.ourwineSeo.seoInit();
					break;
				case "askraul":
					pageAnimate(-1024);
					jumpScrollbar(-1024);
					bearFlag.general.seoInit();
					break;
				case "pairings":
					pageAnimate(-2048);
					jumpScrollbar(-2048);
					autoPopup("wine-pairings");
					bearFlag.general.seoInit();
					break;
				case "home":
					pageAnimate(-3072);
					jumpScrollbar(-3072);
					bearFlag.general.seoInit();
					break;
				case "findus":
					pageAnimate(-4096);
					jumpScrollbar(-4096);
					autoPopup("find-us");
					bearFlag.findusSeo.seoInit();
					break;
				case "findus-results":
					pageAnimate(-4096);
					jumpScrollbar(-4096);
					autoPopup("find-us-results");
					bearFlag.findusSeo.seoInit();
					break;
				case "ourart":
					pageAnimate(-5120);
					jumpScrollbar(-5120);
					autoPopup("our-art");
					bearFlag.ourartSeo.seoInit();
					break;
				case "thumbsup":
					pageAnimate(-6144);
					jumpScrollbar(-6144);
					autoPopup("thumbs-up");
					bearFlag.general.seoInit();
					break;
				case "contact":
					pageAnimate(-7168);
					jumpScrollbar(-7168);
					autoPopup("contact-us");
					bearFlag.contactSeo.seoInit();
					break;
				case "contact-thank-you":
					pageAnimate(-7168);
					jumpScrollbar(-7168);
					autoPopup("contact-thanks");
					bearFlag.contactSeo.seoInit();
					break;
				default:
					pageAnimate(-3072);
					jumpScrollbar(-3072);
					bearFlag.general.seoInit();
					break;
			}
		} else {
			pageAnimate(-3072);
			jumpScrollbar(-3072);
			bearFlag.general.seoInit();
		}
	}
}

function changePage() {
	if(location.hash == "") {
		pageAnimate(-3072);
		jumpScrollbar(-3072);
	}
	$("#nav ul li").click(function() {
		var hash = $(this).find("a").attr("href");
		hash = hash.replace(/#/, "");
		$.historyLoad(hash);
		return true;
	});
}

//Contact Form Validation
function contactValidate() {
	$("form#contact_form").submit(function() {
		return false;
	});
}

//Load SWFs
function refreshContent() {
	$("#dialog").dialog("destroy");
	$("div.page a").show();
	$("#dialog").after("<div id=\"dialog\"></div>");
	$("#dialog").remove();
}
function closePopup() {
	$("#dialog").dialog("close");
	$("#dialog").dialog("destroy");
}
function closeDialog() {
	$("div.ui-widget-overlay").click(function() {
		closePopup();
	});
}
function openDialog(className) {
	newsDown(($("#news_feed").outerHeight() - 59)*-1);
	$("#dialog").dialog({
		modal: true,
		width: 1024,
		position: ['center', 'top'],
		dialogClass: className,
		close: function() {
			refreshContent();
			pageStay();
		},
		open: function() {
			closeDialog();
		}
	});
}
function openPopup(elementID) {
	$("#"+elementID).click(function() {
		var pageName = $(this).attr("href");
		var setClass = "btn_" + elementID;
		$("#dialog").load("resources/popups/"+pageName);
		$(this).hide();
		openDialog(setClass);
		return false;
	});
}
function addClose(currentPage, currentSwf) {
	$(currentPage).show();
	$(currentPage).click(function() {
		swfobject.removeSWF(currentSwf);
		$(currentPage).hide();
		$(currentPage.parents("div.page")).append("<div id=\""+currentSwf+"\"></div>");
	});
}
function loadSwf(elementID, swfID, swfWidth, swfHeight) {
	$("#"+elementID).click(function() {
		embedSwf(swfID, swfWidth, swfHeight);
		addClose($(this).parents("div.page").find("a.close"), swfID)
	});
}

function autoPopup(pageName) {
	var elementID = pageName.replace(/-/, "_");
	var setClass = "btn_" + elementID;
	$("#dialog").load("resources/popups/"+pageName+".html");
	openDialog(setClass);
	$("#"+elementID).hide();
}

//SWF Embeds
function embedSwf(swf, swfWidth, swfHeight, xmlPath) {
	var flashvars = {};
	if(xmlPath != null) {
		flashvars.xmlFilepath = xmlPath;
	}
	var params = {
		wmode: "transparent",
		scale: "noscale"
	};
	var attributes = {};
	swfobject.embedSWF("resources/swf/"+swf+".swf", swf, swfWidth, swfHeight, "9.0.0", "resources/swf/expressInstall.swf", flashvars, params, attributes);
}
function loadIcons() {
	$("#secondary_icons a").click(function() {
		var keyValue = $.query( $(this).attr("href") );
		embedSwf(keyValue["id"], keyValue["width"], keyValue["height"]);
		return false;
	});
	embedSwf("cams1", "100", "60");
	embedSwf("cams2", "100", "100");
	embedSwf("cams3", "150", "100");
	embedSwf("cams3b", "150", "100");
	embedSwf("cams4", "200", "100");
	embedSwf("cams5", "80", "80");
	embedSwf("lamps", "220", "500");
}
//Call this function in the AS
function stopIcon(id) {
	var swfWidth = $("#"+id).width();
	var swfHeight = $("#"+id).height();
	if(id == "shoes" || id == "robotFacade" || id == "corkscrw" || id == "robot") {
		var iconPath = "resources/images/icons/secondary/" + id + "_off.jpg\"";
	} else {
		var iconPath = "resources/images/icons/secondary/" + id + ".jpg\"";
	}
	var hrefStr = id + "?width=" + swfWidth + "&height=" + swfHeight + "&id=" + id;
	var fullAnchor = "<a href=\"" + hrefStr + "\"><img src=\"" + iconPath + "\" alt=\"\" /></a>";
	
	$("#"+id).after("<div id=\"" + id + "\">" + fullAnchor + "</div>");
	swfobject.removeSWF(id);
	$("#"+id).css("visibility", "visible");
	loadIcons();
	secondaryHover();
}

//Footer Popup for legal pages
function footerPopup() {
	$("#footer a").click(function() {
		window.open(this.href, 'legal_popup', 'height='+600+', left='+(screen.width-750)/2+', location=no, resizable=no, scrollbars=yes, status=no, toolbar=no, top='+(screen.height-550)/2+', width='+750);
		return false;
	});
}

//Footer Year
function setFooterYear() {
	theYear = new Date();
	$("#year").html(theYear.getFullYear());
}

//Preventing page down and page up key presses
function pageStay() {
	//Prevents pageup, pagedown, spacebar, arrowup, arrowdown, end keys from moving the page
	$(document).keypress(function(e) {
		if(e.which == 32 || e.which == 33 || e.which == 34 || e.which == 35 || e.which == 38 || e.which == 40) {
			return false;
		}
	});
	$(document).keydown(function(e) {
		if(e.which == 32 || e.which == 33 || e.which == 34 || e.which == 35 || e.which == 38 || e.which == 40) {
			return false;
		}
	});
}

//Disabling an event
function disableEvent(ele, theEvent) {
	$(ele).unbind(theEvent).unbind(theEvent);
}

//Calling all necessary functions on page load
$(document).ready(function() {
	navHover();
	mainIconHover();
	secondaryHover();
	setSiteWidth();
	bgDrag();
	scrollWidth();
	scrollbar();
	browserResize();
	newsFeed();
	$.historyInit(pageload, "/");
	changePage();
	footerPopup();
	setFooterYear();
	contactValidate();
	openPopup("our_wine");
	openPopup("find_us");
	openPopup("thumbs_up");
	openPopup("wine_pairings");
	openPopup("our_art");
	openPopup("contact_us");
	openPopup("game_two");
	loadIcons();
	pageStay();
});
