/*
$(function(){
	$("a[href='#']").css({ "outline": "none", "cursor": "default" }).click(function(){ return false; });
});
*/
/*---------------------------------*
 *  sIFR - Flash text replacement
 *---------------------------------*/
 
function init_sIFR(){
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({
			sSelector:"#footer h3.leftalign",
			sFlashSrc:"/img/flash/oporto.swf", 
			sColor:"#000000",
			sWmode: "transparent",
			sCase: "upper"
		}));
		sIFR.replaceElement(named({
			sSelector:"#footer h3",
			sFlashSrc:"/img/flash/oporto.swf", 
			sColor:"#000000",
			sWmode: "transparent",
			sCase: "upper",
			sFlashVars: "textalign=center&offsetLeft=-15"
		}));
		
		/* Popup Headings */
		if( $("body").hasClass("s-info") ){
			sIFR.replaceElement(named({
				sSelector:"h1",
				sFlashSrc:"/img/flash/oporto.swf", 
				sColor:"#FFFFFF",
				sWmode: "transparent",
				sCase: "upper",
				sFlashVars: "textalign=center"
			}));
		
		/* Street Crew Headings */
		} else if( $("body").hasClass("street-crew") ) {
			
			sIFR.replaceElement(named({
				sSelector:".first h2",
				sFlashSrc:"/img/flash/oporto.swf", 
				sColor:"#FFFFFF",
				sWmode: "transparent",
				sCase: "upper"
			}));
			
			sIFR.replaceElement(named({
				sSelector:"h2",
				sFlashSrc:"/img/flash/oporto.swf", 
				sColor:"#000000",
				sWmode: "transparent",
				sCase: "upper"
			}));
			
			
		} else {
			/* Regular Headings */
			sIFR.replaceElement(named({
				sSelector:"h1",
				sFlashSrc:"/img/flash/oporto.swf", 
				sColor:"#000000",
				sWmode: "transparent",
				sCase: "upper"
			}));
		}
		
	};
}
$(function(){
	if(typeof sIFR == "function" && !sIFR.UA.bIsIEMac && (!sIFR.UA.bIsWebKit || sIFR.UA.nWebKitVersion >= 100)){
		sIFR.setup();
		//sIFR.debug();
		if($("body").hasClass("s-info")) { setTimeout(function(){init_sIFR()},200); }
		else { init_sIFR(); }
	};
});




/*------------*
 * Menu Pages
 *------------*/

$(function(){
	// Perform only if on menu page.
	if( $("#menu").size() > 0 ){
				
		// Menu nav click
		$("#menu_nav a").click(function(){
			// Get <li> class
			var menuitem = $(this).parent().attr("class");
			// Split class name at space. (There might be two classes)
			menuitem = menuitem.split(" ");
			// Take only first class, after 'n-'
			menuitem = menuitem[0].substring(2);
			// Get URL from href attribute
			menuurl = $(this).attr("href");
			
			var clickeditem = $(this).text();
			
			// Only trigger if you click a section you arent already in.
			if( $("#content").attr("class") != menuitem ) {
				loadMenuPage(clickeditem, menuitem, menuurl);
			}
			
			// Dont follow href.
			return false;
		});		
	}
});


function changeNavItems(item) {
	// Reset active nav items
	$("#menu_nav li, #menu_nav li a").removeClass("active");
	$("#content").removeClass();
	// Add class to content window to set correct with on nav
	$("#content").addClass(item);
	// Add active classes to nav items to set current items
	$("#menu_nav li.n-" + item).addClass("active").find("a").addClass("active"); 
}

function loadMenuPage(clickeditem, item, url) {
	var curList = $("#menu_nav li.active").text(); // text of currently shown 
	var curListHeight = $("#menu").height();
	
	$("#menu").height(curListHeight);
	
	// rel of what you click on.
	var listID = clickeditem;
	
	
	changeNavItems(item);
	
	if (listID != curList) {
		$("#content").css("background","url('/img/icons/loading.gif') 50% 100px no-repeat");
		$(".menu_pad").fadeOut(300, function() {
		
			$("#menu").load(url + " #menu > div", function(){
				// Remove loading image
				$("#content").css("background","none");
				// Initialize fancybox on the newly loaded content
				init_fancybox();
				// Set Page Title
				var titlePt1;
				if ( $("body").hasClass(".s-locations") ){ titlePt1 = "Oporto - Locations"; }
				else { titlePt1 = "Oporto - Menu"; }
				document.title = titlePt1 + " - " + $("h1","#menu").text();
				$(".menu_pad").hide().fadeIn("slow");
		
				var newHeight = $(".menu_pad").height();
		
				$("#menu").animate({
					height: newHeight
				});
				
			});
	
		});
	}        
}

function changeNav(item) {
	if( $("body").hasClass("s-state") ) {
		fullURL = parent.document.URL;
		item = fullURL.substring(fullURL.indexOf('?')+3, fullURL.length);
	}
	changeNavItems(item);
}


/*-----------*
 * Fancybox
 *-----------*/
 
function init_fancybox() {
	$("p.nutrition a, .popup").fancybox({
		frameWidth: 326,
		frameHeight: 488,
		padding: 0,
		zoomSpeedIn: 300,
		overlayOpacity: 0.9,
		callbackOnShow: function(){
			init_sIFR();
		}
	});
	$("p.nutrition a.big").fancybox({
		frameWidth: 506,
		frameHeight: 488,
		padding: 0,
		zoomSpeedIn: 300,
		overlayOpacity: 0.9,
		callbackOnShow: function(){
			init_sIFR();
		}
	});
	$(".images a").fancybox({
		padding: 5,
		zoomSpeedIn: 300,
		overlayOpacity: 0.9
	});
	
	
	$(".promo .promo_img").fancybox({
		zoomSpeedIn: 300,
		overlayOpacity: 0.9,
		callbackOnStart: function(){
			$("div#fancy_inner").css("background","none");
			$("div#fancy_bg").css("display","none");
			$("div#fancy_close").css("top","23px").css("right","16px");
		}
	});
	
	
	
	
	
}
$(function(){ init_fancybox(); });




/*-------------------*
 * Nutritional Info
 * Popup, tabs etc.
 *-------------------*/

$(function(){
	// Perform only if on info page.
	if( $("body").hasClass("copy") ) { return false; }
	else if( $("body").hasClass("s-info") ){
		// Remove scrollbar fallback
		$("#info").css("overflow","hidden");
		// Add default tab
		$("#tabs a:first").addClass("active");
		// Make tabs scroll
		$("#tabs").localScroll({ target: "#info", speed: "fast" });
				
		// Click a tab...
		$("#tabs a").click(function(){
			$("#tabs a").removeClass("active");
			$(this).addClass("active");
		});
	}
});




/*--------------------*
 * Locations Dropdown
 *--------------------*/

$(function() {
	// Prevent Locations nav clickthrough
	// $("#global_nav > li.n-locations > a").click(function(){ return false; });
	
	// options
	var distance = 40;
	var time = 250;
	var hideDelay = 600;
	
	var hideDelayTimer = null;
	
	// tracker
	var beingShown = false;
	var shown = false;
	
	var trigger = $('#global_nav > li.n-locations');
	var popup = $('#loc_drop').css('opacity', 0);

	// set the mouseover and mouseout on both element
	$([trigger.get(0), popup.get(0)]).mouseover(
		function() {			
			// stops the hide event if we move from the trigger to the popup element
			if (hideDelayTimer) clearTimeout(hideDelayTimer);

			// don't trigger the animation again if we're being shown, or already visible
			if (beingShown || shown) {	
				return;
			} else {
				beingShown = true;
			
				// reset position of popup box
				popup.css({
					top: -20,
					left: -65,
					opacity: 0,
					display: 'block' // brings the popup back in to view
				})		
				// (we're using chaining on the popup) now animate it's opacity and position
				.animate({
						top: '+=' + distance + 'px',
						opacity: 1
					},
					time,
					function() {
						// once the animation is complete, set the tracker variables
						beingShown = false;
						shown = true;
						// IE6 gets a gross border from the opacity. Just get rid of it.
						var isIE6 = ($.browser.msie);
						if (isIE6) { popup.css("opacity","auto"); }
					}
				);
			}
		}
	).mouseout(
		function() {
			// reset the timer if we get fired again - avoids double animations
			if(hideDelayTimer) clearTimeout(hideDelayTimer);
			
			// store the timer so that it can be cleared in the mouseover if required
			hideDelayTimer = setTimeout(
				function() {
					hideDelayTimer = null;
					popup.animate({
							top: '+=' + distance + 'px',
							opacity: 0
						},
						time,
						function() {
							// once the animate is complete, set the tracker variables
							shown = false;
							// hide the popup entirely after the effect (opacity alone doesn't do the job)
							popup.css('display', 'none');
							
						}
					);
				},
				hideDelay
			);
		}
	);
});	


// Trigger expanding down after you type
function expandLocationAjax() {
	$("#loc_complete ul").css({ "height": "100px", "display": "block", "overflow": "hidden" }).parent().animate({ height: "135px" }, { queue: false }, 300);
	$("#loc_drop").css("height","275px");
}




/*----------------*
 * Form Transform
 *----------------*/

$(function() {

	var isIE6 = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 7);
    if( isIE6 == false ) { 
	$(".form").jqTransform();
	}
	//if($.browser.msie){ 
		//$(".i_r .jqTransformInputWrapper",".form").css("width","30px");
	//}

	$(".module").hide();

	// jqTransform zindex issue
	$(".jqTransformSelectWrapper").each(function(){
		var zindex = parseInt( $(this).css("z-index") );
		zindex += 100;
		$(this).css("z-index",zindex);
	});
	// Date control issue
	$("#dcOccurredDate_Reset").click(function(){
		$(".form.jqtransformdone").removeClass("jqtransformdone");
		setTimeout(function(){  if( isIE6 == false ) { $(".form").jqTransform();  }  }, 100);
	});
	
	var numofrows = $(".row").length;
	$("div.row",".form").each(function(i){
		$(this).css("z-index",numofrows - i);
	});
	
	/* Error styling to labels from ilico
	if ($(".errorInput, .errorSelect").size() > 0) { 
		$(".errorInput, .errorSelect").closest(".input_wrap").find("label").addClass("error").parent().siblings(".row_label").addClass("error");
	}*/
	if( $("#errorsummary").size() > 0 ){
		$("label i").parent().addClass("error").parent().siblings(".row_label").addClass("error");;
	}

});

// Hero flash to call this function
function popup(id) {
	$("#" + id).click();
}


function checkEnter(e, fn){ //e is event object passed from function invocation
	var characterCode; // literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	} else {
		e = event;
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		fn();
		return false;
	} else {
		return true;
	}
}

/* Search & Enews Subscription - pressing Enter submits form */
$(document).ready(function() {
	if($.browser.msie){
     
		$("#store-search input.search-postcode").keypress(function(eventObject) { 
			checkEnter(eventObject, function() {
				var cmd = $('#store-search a.btn-search').attr('href').replace('javascript:', '');
				//if (cmd.match(/^__doPostBack\('(.*)\$?([a-zA-Z1-9])+',''\)$/)) {
				  eval($('#store-search a.btn-search').attr('href').replace('javascript:', ''));
				//}
			}); 
		});
		
		$("div[id$=divEDMSignUpForm] input.signup-email").keypress(function(eventObject) { 
			checkEnter(eventObject, function() {
				var cmd = $('div[id$=divEDMSignUpForm] a.btn-signup').attr('href').replace('javascript:', '');
				//if (cmd.match(/^__doPostBack\('(.*)\$?([a-zA-Z1-9])+',''\)$/)) {
				  eval($('div[id$=divEDMSignUpForm] a.btn-signup').attr('href').replace('javascript:', ''));
				//}
			}); 
		});
		
	} else {	  
		
	   var searchButton = $('#store-search a.btn-search');
		if (searchButton.length > 0) {
		   var searchButtonHref = $(searchButton).attr('href').replace('javascript:', '');
		   $("#store-search input.search-postcode").attr('onkeyup', 'if ((event.keyCode || event.which) == 13) ' + searchButtonHref);
		}
		
		var signupButton = $('div[id$=divEDMSignUpForm] a.btn-signup');
		if (signupButton.length > 0) {
		   var signupButtonHref = $(signupButton).attr('href').replace('javascript:', '');
		   $("div[id$=divEDMSignUpForm] input.signup-email").attr('onkeyup', 'if ((event.keyCode || event.which) == 13) ' + signupButtonHref);
		}
		
		
	}
});