$(function(){
	//EXTERNAL SITE LINKS
	eLinks();

	//IFRAME TRANSPARENT BACKGROUNDS
	if($('iframe').length > 0){
		$('iframe').each(function(i){
			$(this).attr("allowTransparency", "true");
		});
	}
	
	//CENTRE MAP HOVERING
	if($('.map').length > 0){
		$('.map').maphilight({
			fillColor: '00acec',
			fillOpacity: 1,
			stroke: true,
			strokeColor: 'ffffff',
			strokeWidth: 2
		});
		
		$('#storeFinderAlphabet a').click(function(e){
			e.preventDefault();
			letter = $(this).text();
			$('#storeFinderAlphabet a.selected').removeClass('selected');
			$(this).addClass('selected');
			
			$.ajax({
				url : "http://merrioncentre.co.uk/index.php/centre-map/stores-list",
				type : "POST",
				data : "letter="+letter,
				success : function(data){
					$('#storeFinderStoreList').html(data);
					linkShowLocation();
				}
			});
		});
		
		linkShowLocation();
		
		$('#mapLevels area').click(function(e){
			e.preventDefault();
			$('.window').hide();
			var id = $('#profileWindow');
			var eID = $(this).attr('rel');
		
			$.ajax({
				url: 'http://merrioncentre.co.uk/index.php/store-directory/profile/'+eID,
				success: function(html){
					$('#profileWindow').html(html);
									
					//ALIGN IMAGE/TEXT
					//Store Logo image Alignment
					logoAlign();
					
					//Mask Function
					mask(id);
				}
			});			 
		});
	}
	
	//PRETTYPHOTO GALLERY
	if($("a[rel^='prettyPhoto']").length > 0){
		$("a[rel^='prettyPhoto']").prettyPhoto();
	}
	
	//GALLERIES
	if ($('.gallerySlider').length > 0) {
		$('.gallerySlider').cycle({
			speed: 1000,
			timeout: 0
		});
		
		$('ul.gallery-thumb-images').find('a').live('click', function () {
			var link = $(this),
				list = link.parents('ul.gallery-thumb-images'),
				slider = list.prev(),
				slideNum = (link.data('slide') - 1);
				
			slider.cycle(slideNum);
			
			list.find('a.activeSlide').removeClass('activeSlide');
			link.addClass('activeSlide');
			
			return false;
		});
	}
	
	//MAILCHIMP SIGNUP FORM LIGHTBOX
	$('#enewsSignupLink').click(function(e) {
		e.preventDefault();
		$('.window').hide();
		var id = $('#signupWindow');
					
		//SHOW MASK AND ALIGN
		var docH = $(document).height();
		var docW = $(document).width();
		var winH = $(window).height();
		var winW = $(window).width();
		
		$('#mask').css({'width': docW,'height': docH });		
		$('#mask').fadeTo("slow",0.3);	
		
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);
		$(id).fadeIn(1000);
		
		$('#signupClose').click(function(e) {
			e.preventDefault();
			$('#mask').fadeOut(600);
			$('.window').fadeOut(300);
		});		
		$('#mask').click(function() {
			$(this).fadeOut(600);
			$('.window').fadeOut(300);
		});			 
	});
	
	//FIND US GOOGLE MAP
	if($("#map").length > 0){
		//GMAPS CREATE
		directionsDisplay = new google.maps.DirectionsRenderer();
	  	var latlng = new google.maps.LatLng(53.80174,-1.544134);
		var myOptions = {
			zoom: 15,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("map"), myOptions);
		
		//MARKERS
		var point = new google.maps.LatLng(53.80174,-1.544134);
		var marker = createMarker(point,'<b>The Merrion Centre,<\/b><br \/>Leeds,<br \/>West Yorkshire,<br \/>LS2 8NG', map);	
	}
	
	
	//DIRECTIONS SLIDER
	if($('.directionsLink').length > 0){
		$('.directionsLink').click(function(){
			var span = $(this).children('.arrow');
			if(span.hasClass('downArrow')){
				$('.upArrow').parent().parent().next('div').slideUp(500);
				$('.upArrow').addClass('downArrow').removeClass('upArrow');
				span.removeClass('downArrow').addClass('upArrow');
				$(this).parent().next('div').slideDown(500);
			} else {
				span.removeClass('upArrow').addClass('downArrow');
				$(this).parent().next('div').slideUp(500);
			}
			return false;
		});
	}
	
	//CONTACT FORM VALIDATION
	//Form Processing
	if($('contactForm').length > 0){
		$('#contactForm').validate({
			rules: {
				name: {
					required: true,
					minlength: 3
				},
				question: {
					minlength: 5,
					required: true
				},
				email: {
					required: true
				}
			},
			messages: {
			    name: {
					required: "Please enter your name",
			    	minlength: "Please enter 3 or more characters"
				},
				question: {
					minlength: "Please enter 5 or more characters",
					required: "Please enter a question"
				},
				email: {
					required: "Please enter your email"
				}
			},
			submitHandler: function() {
				$('#contactForm').ajaxSubmit({
					url: 'http://merrioncentre.co.uk/scripts/formProcess.php',
					success: function(response) {
	                    $('#response p').html(response);
	                    $('#response').fadeIn(500);
	                } 	
	           	});
			}
		});
	}
	
	//STORE DIRECTORY
	if($('.stores').length > 0){
		//ALIGN STORE IMAGES
		$('.stores li').each(function(i){
			if($(this).children().children('img').length > 0){
				var img = $(this).children().children('img');
				//var imgH = img.attr("height");
				var imgH = parseFloat(img.css("height"));
				var imgW = parseFloat(img.css("width"));
				var topH = Math.round((235-imgH)/2);
				var leftW = Math.round((235-imgW)/2);
				img.css({
					"top" : topH,
					"left" : leftW
				});
			} else {
				var par = $(this).children().children('.storeListName');
				//var parH = par.height();
				var parH = 16;
				var topH = Math.round((235-parH)/2);
				par.css({
					"margin-top" : topH
				});
			}
		});
		
		//STORE CATEGORY SLIDER
		$('.storeCategoryLink').click(function(){
			var span = $(this).children('.arrow');
			if(span.hasClass('downArrow')){
				$('.upArrow').parent().parent().next('ul').slideUp(500);
				$('.upArrow').addClass('downArrow').removeClass('upArrow');
				span.removeClass('downArrow').addClass('upArrow');
				$(this).parent().next('ul').slideDown(500);
			} else {
				span.removeClass('upArrow').addClass('downArrow');
				$(this).parent().next('ul').slideUp(500);
			}
			return false;
		});	
	}
	
	if($('a.storeLogoLink').length > 0){
		//AJAX STORE PROFILES
		$('a.storeLogoLink').click(function(e) {
			e.preventDefault();
			$('.window').hide();
			var id = $('#profileWindow');
			var eID = $(this).attr('rel');
			
			$.ajax({
				url: 'http://merrioncentre.co.uk/index.php/store-directory/profile/'+eID,
				success: function(html){
					$('#profileWindow').html(html);
									
					//ALIGN IMAGE/TEXT
					//Store Logo image Alignment
					logoAlign();
					
					//Mask Function
					mask();
				}
			});			 
		});
	}
	
	//FRONTPAGE SLIDER
	if($('#frontSlider').length > 0){
		$('#frontSlider').cycle({
			'fx' : 'fade',
			'timeout' : 4000,
			'speed' : 1000,
			'next' : '#navRight',
			'prev' : '#navLeft',
			'pager' : '#slideNav'
		});
	}
	
	//FAQS SLIDER
	if($('.faqsLink').length > 0){
		$('.faqsLink').click(function(){
			var span = $(this).children('.arrow');
			if(span.hasClass('downArrow')){
				$('.upArrow').parent().parent().next('div').slideUp(500);
				$('.upArrow').addClass('downArrow').removeClass('upArrow');
				span.removeClass('downArrow').addClass('upArrow');
				$(this).parent().next('div').slideDown(500);
			} else {
				span.removeClass('upArrow').addClass('downArrow');
				$(this).parent().next('div').slideUp(500);
			}
			return false;
		});
	}

	//OFFICES SLIDESHOWS
	if($('.imageSlider').length > 0){
		$('.imageSlider').each(function(i){
			$(this).after('<ul id="nav'+i+'" class="officeNav">').cycle({
				timeout: 0,
				speed: 500,
				pager: '#nav'+i,
				pagerAnchorBuilder: function(idx, slide){ 
	        		return '<li><a href="#"><img src="' + slide.src + '" width="108" /></a></li>'; 
	    		}
			});
		});
	}
     		
	//MAILCHIMP
	var options = { 
		errorClass: 'mce_inline_error', 
		errorElement: 'div', 
		errorStyle: err_style, 
		onkeyup: function(){}, 
		onfocusout:function(){}, 
		onblur:function(){}  
	};
	var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
  	options = { 
  		url: 'http://merrioncentre.us1.list-manage.com/subscribe/post-json?u=903bf5112af406f2c37180083&id=c698bf56c0&c=?', 
  		type: 'GET', 
  		dataType: 'json', 
  		contentType: "application/json; charset=utf-8",
        beforeSubmit: function(){
	        $('#mce_tmp_error_msg').remove();
	        $('.datefield','#mc_embed_signup').each(
	            function(){
	                var txt = 'filled';
	                var fields = new Array();
	                var i = 0;
	                $(':text', this).each(
	                    function(){
	                        fields[i] = this;
	                        i++;
	                    });
	                $(':hidden', this).each(
	                    function(){
	                    	if ( fields[0].value=='MM' && fields[1].value=='DD' && fields[2].value=='YYYY' ){
	                    		this.value = '';
							} else if ( fields[0].value=='' && fields[1].value=='' && fields[2].value=='' ){
	                    		this.value = '';
							} else {
	                            this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
	                        }
	                    });
	            });
	        return mce_validator.form();
	    }, 
	    success: mce_success_cb
	};
  	$('#mc-embedded-subscribe-form').ajaxForm(options);
});


Cufon.replace("#navigation a, #enewsSignupLink, .storeCategoryLink, a.offerAdLink", {hover: 'true'});
Cufon.replace("h1 a", { hover: true });
Cufon.replace("#signupWindow legend, #signupWindow #mc-embedded-subscribe, #signupClose, #contactForm #contactSubmit, #response p, #formInstruction, #profileLogo p, #profileClose, span.adText, h1, h2, h3, h4, h5, h6");

//GMAPS MARKER FUNCTION
function createMarker(point,html,map) {
	var marker = new google.maps.Marker({
			position: point, 
			map: map,
			icon: 'http://merrioncentre.co.uk/images/merrion-map-pointer.png'
	});
	
	var infowindow = new google.maps.InfoWindow({
		content: html
	});

	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map,marker);
	});
} 

function backGrad(){
	$("html, body").css({'height' : ($(document).height())+100});
}

//MAILCHIMP FUNCTIONS
var fnames = new Array(); 
	var ftypes = new Array();
	fnames[1]='FNAME';
	ftypes[1]='text';
	fnames[2]='LNAME';
	ftypes[2]='text';
	fnames[0]='EMAIL';
	ftypes[0]='email';
	var err_style = '';
	
	try{
	    err_style = mc_custom_error_style;
	} catch(e){
	    err_style = 'margin: 1em 0 0 0; padding: 1em 0.5em 0.5em 0.5em; background: ERROR_BGCOLOR none repeat scroll 0% 0%; font-weight: bold; float: left; z-index: 1; width: 80%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: ERROR_COLOR;';
	}

function mce_success_cb(resp){
    $('#mce-success-response').hide();
    $('#mce-error-response').hide();
    if (resp.result=="success"){
        $('#mce-'+resp.result+'-response').show();
        $('#mce-'+resp.result+'-response').html(resp.msg);
        $('#mc-embedded-subscribe-form').each(function(){
            this.reset();
    	});
    } else {
        var index = -1;
        var msg;
        try {
            var parts = resp.msg.split(' - ',2);
            if (parts[1]==undefined){
                msg = resp.msg;
            } else {
                i = parseInt(parts[0]);
                if (i.toString() == parts[0]){
                    index = parts[0];
                    msg = parts[1];
                } else {
                    index = -1;
                    msg = resp.msg;
                }
            }
        } catch(e){
            index = -1;
            msg = resp.msg;
        }
        try{
            if (index== -1){
                $('#mce-'+resp.result+'-response').show();
                $('#mce-'+resp.result+'-response').html(msg);            
            } else {
                err_id = 'mce_tmp_error_msg';
                html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
                
                var input_id = '#mc_embed_signup';
                var f = $(input_id);
                if (ftypes[index]=='address'){
                    input_id = '#mce-'+fnames[index]+'-addr1';
                    f = $(input_id).parent().parent().get(0);
                } else if (ftypes[index]=='date'){
                    input_id = '#mce-'+fnames[index]+'-month';
                    f = $(input_id).parent().parent().get(0);
                } else {
                    input_id = '#mce-'+fnames[index];
                    f = $().parent(input_id).get(0);
                }
                if (f){
                    $(f).append(html);
                    $(input_id).focus();
                } else {
                    $('#mce-'+resp.result+'-response').show();
                    $('#mce-'+resp.result+'-response').html(msg);
                }
            }
        } catch(e){
            $('#mce-'+resp.result+'-response').show();
            $('#mce-'+resp.result+'-response').html(msg);
        }
    }
}

//EXTERNAL SITE LINKS
function eLinks(){
	var a = new RegExp('/' + window.location.host + '/');
	$('a').each(function() {
   		if (!a.test(this.href)) {
       		$(this).attr("target", "_blank");
   		}
	});
}

function logoAlign(){
	var windowHeight = $("#profileWindow").height();
	$('#profileLogo').height(windowHeight);
	
	if($('#profileLogo').children('img').length > 0){
		var img = $('#profileLogo').children('img');
		var imgH = parseFloat(img.css("height"));
		var imgW = parseFloat(img.css("width"));
		var topH = Math.round((windowHeight-imgH)/2);
		var leftW = Math.round((220-imgW)/2);
		img.css({
			"left" : leftW,
			"top" : topH
		});
	} else {
		var par = $('#profileLogo').children('.storeListName');
		var parH = par.height();
		var topH = Math.round((windowHeight-parH)/2);
		par.css({
			"top" : topH
		});
	}
}

//Mask Functions
function mask(id){
	//SHOW MASK AND ALIGN
	var docH = $(document).height();
	var docW = $(document).width();
	var winH = $(window).height();
	var winW = $(window).width();
	
	$('#mask').css({'width': docW,'height': docH });		
	$('#mask').fadeTo("slow",0.3);	
	
	$('#profileWindow').css({
		'top' : winH/2-$(id).height()/2,
		'left' : winW/2-$(id).width()/2,
		'position' : 'fixed'				
	}).fadeIn(1000);
	
	$('#profileClose').click(function(e) {
		e.preventDefault();
		$('#mask').fadeOut(600);
		$('.window').fadeOut(300);
	});		
	$('#mask').click(function() {
		$(this).fadeOut(600);
		$('.window').fadeOut(300);
	});	
	eLinks();
}

//HOVER OVER STORE LINKS TO SHOW MAP LOCATION
function linkShowLocation(){
	$('#storeFinderStoreList a').mouseover(function(e){
		var entry = $(this).next().val();
	    $('#'+entry).mouseover();
	}).mouseout(function(e) {
		var entry = $(this).next().val();
	    $('#'+entry).mouseout();
	}).click(function(e) { 
		$('.window').hide();
		var id = $('#profileWindow');
		var eID = $(this).attr('rel');
		
		$.ajax({
			url: 'http://merrioncentre.co.uk/index.php/store-directory/profile/'+eID,
			success: function(html){
				$('#profileWindow').html(html);
								
				//ALIGN IMAGE/TEXT
				//Store Logo image Alignment
				logoAlign();
				
				//Mask Function
				mask(id);
			}
		});			 
		e.preventDefault(); 
	});
}
