/**
 * @author author
 */

/* ::Enable Javascript-enabled stylesheet */
var head_css = $('<link rel="stylesheet" href="presentation/css/js-enabled.css" type="text/css" media="screen" />').appendTo($('head')[0]);

/* -------------------------------------- */


/* ::Global Vars */
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var geocoder;

/*
 * configuration
 * 
 */
config = {
	
	markerTitleAuto		 : true,								// marker title attr
	markerTitle	 	 	 : 'other title',						// Only used when markerTitleAuto is false
	infoWindowAutoOpen	 : true,								// if true infowindow opens on load
	infoWindowMaxWidth	 : 140									// max width of info window, value must be real width - 16 - 24 (-40)
}	


/* -------------------------------------- */


/* ::Document Ready function Callers  */
$(document).ready(function(){
	
	//FnSocialButtons.init();
	FnCEdropdown.init();	
	FnPromoSlider.init();
	FnInputFocus.init();
	FnFixLegend.init();	
	FnDirections.init();
	FnDirForm.init();
	FnFancyBox.init();
	FnFancyFix.init();
	FnTimer.init();
	FnMaillistVal.init();
	
	
});
/* -------------------------------------- */

/* ::Default Functions */
FnDefault = {
	init:function() {}	
	
	
	/* -------------------------------------- */
}

/* ::Maillist validation Functions */
FnMaillistVal = {
	init:function() {
		//FnMaillistVal.checkField();		
		FnMaillistVal.formSubmit();		
	
	},
	checkField:function() {
		
		$('#frm-maillist :input').blur(function() {
			//alert('oi');
			$('#frm-maillist').removeClass('warning');
			$('.error-message').remove();
			if ($(this).is('#txt-ml-email')) {
				if (this.value == '') {
					//alert('error');
					var errormessage = 'This is a required field';
					$('<span></span>')
						.addClass('error-message')
						.text(errormessage)
						.appendTo('#page-content');
					$('#frm-maillist').addClass('warning');
				} else {
					if (this.value != '' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)) {
						var errormessage = 'Please enter a valid email';
						$('<span></span>')
							.addClass('error-message')
							.text(errormessage)
							.appendTo('#page-content');
						$('#frm-maillist').addClass('warning');
					}
				}
			} 			
		});
	},
	formSubmit:function() {
		$('#frm-maillist').submit(function() {
			FnMaillistVal.checkField();
			$('#txt-ml-email').trigger('blur');
			var numWarnings = $('.warning').length;
				if (numWarnings) {
					return false;
				} else {
					$('<span></span>')
						.addClass('error-message')
						.html('<img src="presentation/images/icons/loading.gif" alt="Loading..." />')
						.appendTo('#page-content');
					$('#frm-maillist').addClass('warning');
					
					var dataString = 'email=' + $('input#txt-ml-email').val();
					
					$.ajax({
						type: 'POST',
						url: 'maillist.php',
						data: dataString,
						dataType : 'html',
						success: function(data) {
							$('#frm-maillist').removeClass('warning');
							$('.error-message').remove();
							
							$('<span></span>')
								.addClass('error-message')
								.html(data)
								.appendTo('#page-content');
							$('#frm-maillist').addClass('warning');
							
							$('input#txt-ml-email').val('');
						},
						error:function (xhr, ajaxOptions, thrownError) {
							//alert(xhr.status + ',' + xhr.statusText);
							
							$('#frm-maillist').removeClass('warning');
							$('.error-message').remove();
							
							var errormessage = 'An error has occurred.';
							$('<span></span>')
								.addClass('error-message')
								.text(errormessage)
								.appendTo('#page-content');
							$('#frm-maillist').addClass('warning');
						}  
					});
					
					return false;
				}
		});	
	}
	/* -------------------------------------- */
}

function stopLoop() {
	clearInterval(promoLoop);
}

function resumeLoop() {
	FnTimer.init();
}

/* ::Default Functions */
FnTimer = {
	init:function() {
		promoLoop = window.setInterval(function() {
		 FnPromoRotate.init();
		}, 5000);
	}	
	/* -------------------------------------- */
}
/* ::Rotate Functions */
FnPromoRotate = {
	init:function() {
		maxval = (numslides-1)*-258;
		if (leftPos <= maxval) {
			leftPos = 0;
			$('.slidescontainer').css('left',leftPos);
			slidenum = 1;
			$('.slide-num').text(slidenum + ' of ' + numslides);			
			return false;
		} else {
			slidenum = slidenum+1;
			$('.slide-num').text(slidenum + ' of ' + numslides);				
			leftPos = leftPos-258;
			$('.slidescontainer').animate({'left':leftPos}, 'slow');
			return false;
		}		
	}	
	/* -------------------------------------- */
}


/* ::CE logo Dropdown Functions */
FnCEdropdown = {
	init:function() {
		$('#logo-ce').click(function(){
			$('#ce-dropdown').show();
			return false;
		});
		
		$('body').click(function() {
		 //Hide the menus if visible
			 $('#ce-dropdown').hide();
		 });
		
		$('#ce-dropdown').click(function(event){
		     event.stopPropagation();
		 });		 
		

	}		
	
	/* -------------------------------------- */
}

/* ::Show Dirform Functions */
FnDirForm = {
	init:function() {
		$('#getdir').click(function() {
			$(this).addClass('hide');
			$('.directions-form').removeClass('hide');
			$('#directionsPanel').removeClass('hide');	
			$('.directions-form a.close').click(function() {
				$('.directions-form').addClass('hide');
				$('#directionsPanel').addClass('hide');				
				$('#getdir').removeClass('hide');
				return false;
			});
			
			return false;
		});	
	}	
	/* -------------------------------------- */
}



/* ::Social btns Functions */
FnSocialButtons= {
	init:function() {
	
		FnSocialButtons.facebook();
		FnSocialButtons.twitter();		
	},
	facebook:function() {
		$('<li><a class="facebook" href="#" type="icon" name="fb_share">facebook</a></li>')
			.appendTo('.utilities');
	},	
	twitter:function() {
		$('<li><a class="twitter" href="#">Tweet this</a></li>')
			.appendTo('.utilities');
		$('a.twitter').click(function(){
			TwitThis.pop();	
		});		
	}
	
	/* -------------------------------------- */
}

/* ::Slider Functions */
FnPromoSlider = {
	init:function() {
		leftPos = 0;		
		slidenum = 1;
		FnPromoSlider.createSlider();
	},
	createSlider:function() {
		$('<div class="promos slider"></div>')
			.html('<div class="slidescontainer"></div>')
			.insertAfter('#promos');
		
		$('<span class="triangle png_bg"></span>')
			.insertBefore('.slider');
		
		$('<span class="terms">Terms &amp; Conditions Apply</span>')
			.appendTo('.slider');
			
		FnPromoSlider.getContentFromXML();	
	},
	getContentFromXML:function() {
		//alert('oi');
		$.ajax({
	         type: "GET",
	         url: "content/promos.xml",
	         dataType: "xml",
	         success: function(xml) {
	             $(xml).find('promo').each(function(){
	                 //var id_text = $(this).attr('id')
	                 //var name_text = $(this).find('name').text()
	                 var content_text = $(this).find('content').text()
	                 var image_name = $(this).find('image').text()	                 	                 
	
	                 $('<div class="slide"></div>')
	                     .html('<img src="presentation/images/logos/'+image_name+'" /><p>'+content_text+'</p>')
	                     .appendTo('.slidescontainer');
	             }); //close each(
       	     FnPromoSlider.createControls();
	         }
	     });
	},
	createControls:function() {
//	alert(slidenum);
		numslides = $('.slide').length;
		$('<div class="slider-controls"></div>')		
		.html('<a href="#" class="prev">Previous</a><span class="slide-num">'+slidenum+' of '+numslides+'</span><a href="#" class="next">Next</a>')
		.insertAfter('.slidescontainer');
		
		
		FnPromoSlider.prevSlide();
		FnPromoSlider.nextSlide();	
		//FnPromoSlider.disablePrev();
	},
	prevSlide:function() {
		$('.slider .prev').click(function(){
		stopLoop();
			if (leftPos >= 0) {
				//FnPromoSlider.disablePrev();
				return false;
			} else {
				slidenum = slidenum-1;
				$('.slide-num').text(slidenum + ' of ' + numslides);
				leftPos = leftPos+258;
				$('.slidescontainer').animate({'left':leftPos}, 'slow');
//				FnPromoSlider.disablePrev();				
				//FnPromoSlider.disableNext();								
				return false;			
			}
		});		
	},
	nextSlide:function() {
		$('.slider .next').click(function(){
			stopLoop();
			maxval = (numslides-1)*-258;
//			alert(leftPos);
			if (leftPos <= maxval) {
//				FnPromoSlider.disableNext();
				return false;
			} else {
				slidenum = slidenum+1;
				$('.slide-num').text(slidenum + ' of ' + numslides);				
				leftPos = leftPos-258;
				$('.slidescontainer').animate({'left':leftPos}, 'slow');
//				FnPromoSlider.disablePrev();
				//FnPromoSlider.disableNext();							
				return false;
			}			
		});		
	},
	disablePrev:function(event) {		
		if (leftPos >= 0) {	
			$('.slider .prev').hide();
		} else {
			$('.slider .prev').show();
		}						
	},
	disableNext:function(event) {		
		if (leftPos <= maxval) {	
			$('.slider .next').hide();
		} else {
			$('.slider .next').show();
		}						
	}	
	/* -------------------------------------- */
}

/* FnInputFocus */
/* :: remove and replace text field example content */
FnInputFocus = {
	init:function() {
		
	// when text field gets clicked
	$(':input.example').focus(function() {
		// if not empty and if class example get value
		if ($ (this) .is('.example') && !(this.value == ''))  {
			// store value
			exampleValue = this.value;
			// empty value
			$(this).attr({'value' : ''})
			// remove class example
			$(this).removeClass('example');
		};
	}).blur(function() {
		// if empty: replace example value
		if (this.value == '') {
			$(this).addClass('example')
			$(this).attr({'value' : exampleValue})
		};
	});
	}
	
	/* -------------------------------------- */
}

/* ::GM Directions Functions */
FnDirections = {

	

	init:function() {
		// initialize 
//		FnDirections.title = "test"; ?
		numCards = $('.vcard').length;
		//alert(numCards);
		
		if (numCards == 1) {
			geocoder = new google.maps.Geocoder();		
			FnDirections.getToAddr();
		} else {		
			FnDirections.multipleCards();
		}

		//FnDirections.getToAddr();
		FnDirections.selectChange();		
		FnDirections.formSubmit();
		
	},
	multipleCards:function()
	{
		//alert('oi');
		geocoder = new google.maps.Geocoder();
		// geocode country of first card
		//toCountryCenter = $('.vcard:eq(1) .country-name').text();
		toCountryCenter = $('.vcard:eq(0) .locality').text();
		//toCountryCenter = "hallo";
//		alert(toCountryCenter);
		if (geocoder) 
		{
		  geocoder.geocode( { 'address': toCountryCenter}, function(results, status) 
		  {
		    if (status == google.maps.GeocoderStatus.OK) 
		    {
		    	CountrycentrePlaceLatLng = results[0].geometry.location;
		    	//FnDirections.makeMap(centrePlaceLatLng);
		    	
		    	Countrylat = CountrycentrePlaceLatLng.lat();
    			Countrylng = CountrycentrePlaceLatLng.lng();
    			
    			//alert(Countrylat);
    			
    			var CountrycentrePlace = new google.maps.LatLng(Countrylat, Countrylng);
    				var myOptions = 
    				{
	    			  zoom:11,
	    			  mapTypeId: google.maps.MapTypeId.ROADMAP,
	    			  navigationControl: true,
	    			  scaleControl: false,
	    			  mapTypeControl: false,
	    			  scrollwheel: false,
	    			  center: CountrycentrePlace
    				}
    			map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    			
    			directionsDisplay = new google.maps.DirectionsRenderer();    
    			directionsDisplay.setMap(map);
    			directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    			
		    	getlocs();
		    	
		    } else 
		    	{
		      		alert("Geocode was not successful for the following reason: " + status);
		    	} 
		  });
		}// end if geododer
	function getlocs() 
		{
			$('.vcard').each(function() 
			{
				geocoder = new google.maps.Geocoder();
	
			    var hcard = $(this);
				//FnDirections.getToAddr(hcard);
				numwindow = 0;
				
				// get addresses, geocode
				toStreet = hcard.find('.street-address').text();
				toPlace = hcard.find('.locality').text();		
				toCountry = hcard.find('.country-name').text();		
				
				toAddress = toStreet + ", " + toPlace + ", " + toCountry;
				
				// geocode for markers
				if (geocoder) {
				  geocoder.geocode( { 'address': toAddress}, function(results, status) {
				    if (status == google.maps.GeocoderStatus.OK) {
				    	thisLocLatLng = results[0].geometry.location;
				    	//FnDirections.makeMap(centrePlaceLatLng);
//				    	thisMarker();
				    	thisinfoWindow();				    	
				    } else {
				      alert("Geocode was not successful for the following reason: " + status);
				    }
				  });
				  function thisinfoWindow() {
			  			var placeName = hcard.find('h3 a').text();
						numwindow = numwindow + 1;
				  		var contentString = '<div class="infowindow">' +
				  		'<h3><a class="fn org url" href="#">'+placeName+'</a></h3>' +
				  		//'<div class="adr">' +
				  		//'<p class="street-address">'+toStreet+'</p>'+
				  		//'<p><span class="locality">'+toPlace+'</span>, <abbr class="country-name" title="'+toCountry+'">'+toCountry+'</abbr></p>'+
				  		//'<p class="postal-code">'+toPostcode+'</p></div>'+
				  		'</div>';
				  		
				  		
				  		infowindow = new google.maps.InfoWindow({
				  			content: contentString,
				  			maxWidth: config.infoWindowMaxWidth
				  		});
				  		
				    	thisMarker();
				  }
				  function thisMarker() {
				  
//				  alert(numwindow);
				  
					thisTitle = hcard.find('h3 a').text();
					
					thislat = thisLocLatLng.lat();
					thislng = thisLocLatLng.lng();

//					alert(thislat);					

					var thismarkerPos = new google.maps.LatLng(thislat, thislng);    	
					
					var placeMarker = new google.maps.Marker({
						position: thismarkerPos,
						map: map,
						//icon: companyImage,
						//shadow: companyShadow,
						//title:"Høgenhaug",
						title: thisTitle,
						num: numwindow,
						zIndex: 3});
						
						//thisinfoWindow();
						
						google.maps.event.addListener(placeMarker, 'click', function() {

								//alert(this.num);
								var addrNum = this.num-1;
								
								var placeName = $('.vcard:eq('+addrNum+') h3 a').text();
								var toStreet = $('.vcard:eq('+addrNum+') .street-address').text();								
								var placeURL = $('.vcard:eq('+addrNum+') h3 a').attr('href');
								var toPostcode = $('.vcard:eq('+addrNum+') .postal-code').text();
								var logourl = $('.vcard:eq('+addrNum+') .logo').attr('src');
								var logowidth = $('.vcard:eq('+addrNum+') .logo').attr('width');
								var logoheight = $('.vcard:eq('+addrNum+') .logo').attr('height');
								
								//alert(placeName);
								
								var newcontent = '<div class="infowindow">' +
								'<h3><a class="fn org url" href="'+placeURL+'">'+placeName+'</a></h3>' +
								'<div class="adr">' +
								'<p class="street-address">'+toStreet+'</p>'+
								'<p class="postal-code">'+toPostcode+' <span class="locality">'+toPlace+'</span></p></div>'+					
								'</div>';
								
								toAddress = toStreet + ", " + toPlace + ", " + toCountry;
								
								$('#dirto').attr('value', toAddress);
								
								infowindow.setContent(newcontent);
								
								infowindow.open(map,placeMarker);								
								
							});
						
					
				  }// end thisMarker
				  
				  
				  
				}// end if geocoder		
				
				
								
			});//end each
			//map.centerAndZoomOnBounds(0,0);
			//getcenter = map.getCenter();
			//alert(getcenter);
			

			
		} // end getlocs
		
	},
	getToAddr:function(){

		toStreet = $('.vcard .street-address').text();
		toPlace = $('.vcard .locality').text();		
		toCountry = $('.vcard .country-name').text();		
		
		toAddress = toStreet + ", " + toPlace + ", " + toCountry;
		
		$('#dirto').attr('value', toAddress);		
		
		FnDirections.getGeoCode();
	},	
	getGeoCode:function(){
		if (geocoder) {
		  geocoder.geocode( { 'address': toAddress}, function(results, status) {
		    if (status == google.maps.GeocoderStatus.OK) {
		    	centrePlaceLatLng = results[0].geometry.location;
		    	FnDirections.makeMap(centrePlaceLatLng);
		    } else {
		      alert("Geocode was not successful for the following reason: " + status);
		    }
		  });
		}
		
	},	
	makeMap:function(centrePlaceLatLng){
		lat = centrePlaceLatLng.lat();
		lng = centrePlaceLatLng.lng();
//TODO: make optons variable, vars on top of this file		
		var centrePlace = new google.maps.LatLng(lat, lng);
			var myOptions = {
		  zoom:13,
		  mapTypeId: google.maps.MapTypeId.ROADMAP,
		  navigationControl: true,
		  scaleControl: false,
		  mapTypeControl: false,
		  center: centrePlace
		}
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		
		directionsDisplay = new google.maps.DirectionsRenderer();    
		directionsDisplay.setMap(map);
		directionsDisplay.setPanel(document.getElementById("directionsPanel"));
		
		
		FnDirections.createInfoWindow();
		//FnDirections.createCusInfoWindow();
	},
	createInfoWindow:function(){
		//var contentString = $('.vcard').html();
		//var contentString = contentString.replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, '');
		//var contentString = $.trim(contentString);
		
		// get vars from vcard
//		var placeName = hcard.find('h3 a').text();
		var placeName = $('.vcard h3 a').text();
		var placeURL = $('.vcard h3 a').attr('href');
		var toPostcode = $('.vcard .postal-code').text();
		var logourl = $('.vcard .logo').attr('src');
		var logowidth = $('.vcard .logo').attr('width');
		var logoheight = $('.vcard .logo').attr('height');
						
		var contentString = '<div class="infowindow">' +
		'<h3><a class="fn org url" href="'+placeURL+'">'+placeName+'</a></h3>' +
		'<div class="adr">' +
		'<p class="street-address">'+toStreet+'</p>'+
		'<p class="locality">'+toPlace+' <span class="postal-code">'+toPostcode+'</span></p></div>'+					
		'</div>';
		
		
		infowindow = new google.maps.InfoWindow({
			content: contentString,
			maxWidth: config.infoWindowMaxWidth
		});
		
		google.maps.event.addListener(infowindow, 'domready', function() {
			//alert('oioioi');
			//$('.gmnoprint .adr').parent().addClass('infowindow');
		});

		FnDirections.createMarker();
		
	},
	createMarker:function(){
		if (config.markerTitleAuto == true) {
			config.markerTitle = $('.vcard h3').text();
		} else {
			config.markerTitle = config.markerTitle;
		}
	
		var markerPos = new google.maps.LatLng(lat, lng);    	
		
		var placeMarker = new google.maps.Marker({
			position: markerPos,
			map: map,
			title: config.markerTitle,
			zIndex: 3});
		
		google.maps.event.addListener(placeMarker, 'click', function() {
			infowindow.open(map,placeMarker);
		});
		
		if (config.infoWindowAutoOpen == true && numCards < 2) {
			infowindow.open(map,placeMarker);
		}
		
		
	},
	selectChange:function(){
		$('#mode').change(function() {
			// test for empty values			
			$('#dirform').submit();
		});
	
	},	
	calcRoute:function(){
		  var start = document.getElementById("dirfrom").value;
		  var end = document.getElementById("dirto").value;
		  
		//  alert(end);
		var selectedMode = document.getElementById("mode").value;
		  
		  var request = {
		      origin:start, 
		      destination:end,
		      //travelMode: google.maps.DirectionsTravelMode.DRIVING
		      travelMode: google.maps.DirectionsTravelMode[selectedMode]
		  };
		  directionsService.route(request, function(response, status) {
		    if (status == google.maps.DirectionsStatus.OK) {
		      directionsDisplay.setDirections(response);
		    } else {
		    	//alert(status);
		    	if (status == 'NOT_FOUND') {
		    		alert('One or more addresses might be missing');
		    	}
		    }
		  });
		  
		  // TODO: error handling
		
	},
	createForm:function(){
		//alert('oi');
		$('<div id="dirformcontainer"></div>')
			.insertAfter('#themap');
			
		$('<form id="dirform"><legend>Get Directions</legend><fieldset><ul></ul></fieldset></form>')	
			.appendTo('#dirformcontainer');

		$('<li><label for="fromAddress">From:</label><input type="text" id="fromAddress" name="fromAddress" /></li>')	
			.appendTo('#dirform ul');			

		$('<li><label for="toAddress">To:</label><input type="text" id="toAddress" name="toAddress" /></li>')	
			.appendTo('#dirform ul');
			
		$('<li><input type="submit" id="btnDirSubmit" name="btnDirSubmit" value="Get Directions" /></li>')	
			.appendTo('#dirform ul');			
		
		$('#toAddress').attr('value', toAddr);	
		//alert(toAddr);		

	},
	formSubmit:function(){
		$('#dirform').submit(function(event) {
			event.preventDefault();
			infowindow.close();
			FnDirections.calcRoute();

		});
	}	
	
	
	/* -------------------------------------- */
}

/* ::Function to replace legend elem with h2 */
FnFixLegend = {
	init:function() {
	
		$('legend').each(function() {
			// get text
			var thisLegendText = $(this).text();
			// create h2 with text
			$('<h2 class="legend"></h2>')
				.text(thisLegendText)
				.insertAfter(this);
			$(this).remove();
		});
	}	
	
	
	/* -------------------------------------- */
}

		/* ::Fancybox Functions */
FnFancyBox = {
	init:function() {
	
		$("a.thumb").fancybox(
			{
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
			'speedIn'		:	600, 
			'speedOut'		:	200, 
			'overlayShow'	:	true
			}
		);
		 
		$("a#getoutlets").fancybox({
				'hideOnContentClick': false,
				'autoDimensions': false,
				'width': 705,
				'height': 377,
				//'overlayColor': '#000',
				//'overlayOpacity': 0.8,
				'padding': 10,
				'onClosed': function() { 
				   resetFancyBox();
				  } 
			});
	}	
	/* -------------------------------------- */
}

function resetFancyBox() {
	$('#fancybox-outer').removeClass('fancyfix');
}

/* ::Default Functions */
FnFancyFix = {
	init:function() {
		$("a#getoutlets").click(function() {	
			$('#fancybox-outer').addClass('fancyfix');
		});
	}	
	/* -------------------------------------- */
}

