/**
 * Care Plus
 *
 */

$(function(){
	
	if ($(".nav").length) {
		
		$(".nav").find(".current").prev().addClass("current_prev");
	}
	
	if ($(".catalogue_item").length) {
		
		$(".catalogue_item").each(function() {
			
			var title = $(this).find("span.title");
			
			title
				.clone()
				.appendTo(title.parent())
				.addClass("screen")
				.text("")
				.height(title.height())
			;
		});
	}
	
	var siteLang = $("html").attr("lang");
	
	/**
	 * Lang switch
	 */
	
	// check for langswitch element
	if ($("#langswitch").length) {
		
		var langswitch = $("#langswitch");
		var langMenu = $("#nav_lang");
		var langSelected = langMenu.find(".lang.current");
		var langTimer = 0;
		var timeOut = 400;
		
		// remove the anchor element so the current language is not clickable
		langSelected.find("span").unwrap("a");
		
		// create a paragraph to store the selected language element in
		// before we remove it from the language list
		$("<p />", {
			"id"    : "current_lang",
			"class" : "lang current"
		})
		.html( langSelected.html() )
		.prependTo(langswitch)
		;
		
		langSelected.remove();
		
		function showLangMenu() {
			
			if (langTimer) {
				
				window.clearTimeout(langTimer);
				langTimer = null;
			}
			
			langMenu.slideDown("fast");
		}
		
		function hideLangMenu() {
			
			// set a timeout
			langTimer = window.setTimeout(function() {
				
				langMenu.slideUp("fast");
				
			}, timeOut);
			
		}
		
		// bind the show/hide functions to the langswitch element
		langswitch.hover(
			showLangMenu,
			hideLangMenu
		);
		
		// hide the menu when a new language is selected
		$("body").click(function(e) {
			hideLangMenu();
		})
		
		// hide the language menu
		langMenu.hide();
	}
	
	/**
	*	Langswitch melding in colorbox
	*/
	if ($.cookie('has_visited') != 'true') {
		$('#langswitch').qtip({
			content: {
				text: $("#langmelding").html()
			},
		
			show: {
				when: false,
				ready: true
			},
		
			hide: false,
		
			position: {
				corner: {
					target: "leftMiddle",
					tooltip: "rightTop"
				}
			},
		
			style: {
				width: $("#langmelding").outerWidth() + 30,
				padding: 8,
				background: "#0d6729",
				color: "#ffffff",
				border: {
					width: 2,
					color: "#0d6729"
				},
				tip: true
			},
		
			api: {
				onShow: function() {
				
					$.cookie('has_visited', 'true', {
					   expires: 999,
						path: "/",
						domain: ".careplus.eu"
					});
					
					var counter = 5;
					$("span#melding-countdown").html(counter);

					var interval = setInterval(function() {	
					    counter--;
					
					    if (counter == 0) {
					        // Display a login box
					        clearInterval(interval);
							hideLang();
					    }
					
						$("span#melding-countdown").html(counter);
					}, 1000);	

				//	setTimeout( function() {
				//	}, 5000);
					
				}
			}
		});
	
		$('.qtip a#closebutton').click(function(e) {
			hideLang();
		});
	
		function hideLang() {
			$('#langswitch').qtip('hide'); // Hides the tooltip
		}
	}
	
	$('#langmelding').hide();
	
	
	/**
	 * Product print
	 */
	
	 if ($("#product").length) {
	 	
	 	$("#product #print a").click(function(e) {
	 		
	 		e.preventDefault();
	 		
	 		if (window.print) window.print();
	 	})
	 	
	 	var permalinkBox = $("<div />", {
			id : "permalink_box"
		})
		.hide()
		.appendTo("#tools");
		
		var permalinkBoxClose = $("<span />", {
			"class" : "close"
		})
		.click(function() {
			permalinkBox.hide();
		})
		.text("X")
		.appendTo(permalinkBox);
		
		var permalinkField = $("<input />", {
			type    : "text",
			"id"    : "permalinkField",
			"class" : "textfield",
			value   : window.location
		})
		.appendTo(permalinkBox);
		
	 	
	 	$("#product #permalink a").click(function(e) {
	 		
	 		e.preventDefault();
	 		
	 		if (permalinkBox.is(":hidden")) {
	 			
	 			permalinkBox.show();
	 			permalinkField.focus().select();
	 			
	 			// IE only
	 			if (document.all) {
		 			var range = $("#permalinkField").createTextRange();
		 			r.execCommand('copy');
 				}
	 		}
	 		else {
	 			permalinkBox.hide();
	 		}
	 	})
	 }
	 
	/**
	 * Intro: Read More
	 */
	 
	if ($("#intro").length && $("#intro_more").length) {
		
		var toggleContent     = $("#intro_more");
		var toggleTrigger     = $(".toggle");
		var toggleTriggerMore = $(".toggle_more");
		var toggleTriggerless = $(".toggle_less");
		
		toggleContent.hide();
		toggleTriggerless.hide();
		
		toggleTrigger.toggle(
			function() {
				toggleContent.slideDown(function() {
					toggleTriggerless.show();
					toggleTriggerMore.hide();
				});
				
			},
			function() {
				toggleContent.slideUp(function() {
					toggleTriggerless.hide();
					toggleTriggerMore.show();
				});
				
			}
		)
	}
	
	/**
	 * Rotator
	 */
	 
	if ($(".rotate").length) {
		
		$(".rotate").each(function() {
			
			var rotator      = $(this),
				rotatorNavId = "nav_" + rotator.attr("id")
			;
			
			rotator.after("<div class='nav_rotator_wrapper'><div id='" + rotatorNavId + "' class='nav_rotator'></div>").cycle({ 
				fx      : "scrollLeft", 
				speed   : "fast",
				pause   : 1,
				timeout : 30000, 
				pager   : "#" + rotatorNavId
			});
		});
		
		setTimeout(function() {
			
			$(".nav_rotator").find("a:last").addClass("last");
			
		}, 50);
		
	}
	
	/**
	 * Panels	
	 */
	
	if ($(".panels").length) {
		$(".panels").tabs();
	}
	
	/**
	 * Product	
	 */
	
	if ($("#product").length) {
		
		$("#travel > a").colorbox({
			width : "450px",
			height: "800px",
			iframe: true
		});
		
		if ($("#product .product_image").length) {
		
			$("#product .product_image a").colorbox({
				current: "{current} / {total}"
			});
		}
	}
	
	/**
	 * Tweets homepage
	 * http://apiwiki.twitter.com/Twitter-API-Documentation
	 */
	
	if ($("#panel_tweets").length) {
		
		/*
		 * Twitter function
		 *
		 * - parseUsername : @foo           -> <a href="http://twitter.com/foo/">@foo</a>
		 * - parseURL      : http://foo.bar -> <a href="http://foo.bar">http://foo.bar</a>
		 * - parseHashtag  : #foo           -> <a href="http://search.twitter.com/search?q=foo/">foo</a>
		 
		 * http://www.simonwhatley.co.uk/parsing-twitter-usernames-hashtags-and-urls-with-javascript
		 */
		
		String.prototype.parseUsername = function() {
			return this.replace(/[@]+[A-Za-z0-9-_]+/, function(u) {
				var username = u.replace("@","")
				return u.link("http://twitter.com/"+username);
			});
		};
		
		String.prototype.parseURL = function() {
			return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
				return url.link(url);
			});
		};
		
		String.prototype.parseHashtag = function() {
			return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
				var tag = t.replace("#","%23")
				return t.link("http://search.twitter.com/search?q="+tag);
			});
		};
		
		var screenName;
		
		switch (siteLang) {
			case "nl":
				screenName = "careplusnl";
			break;
			
			case "en":
				screenName = "careplus";
			break;
			
			case "de":
				screenName = "careplus";
			break;
			
			default:
				screenName = "carepluseu";
		}
				
		var numTweets = 1;
		
		var feedUrl = "http://api.twitter.com/1/statuses/user_timeline.json?callback=jsonTwitterApi";
		feedUrl += "&screen_name=" + screenName ;
		feedUrl += "&count=" + numTweets ;
		
		var script_call = document.createElement("script");
		
		script_call.type = "text/javascript";
		script_call.src = feedUrl;
		
		$("head")[0].appendChild(script_call);
		
		jsonTwitterApi = function(response) {
			
			if (!response.length) {
				return;
			}
			
			var tweetsHtml = "";
			tweetsHtml += "<div class='news_items'>";
			
			for (var i=0; i<response.length; i++) {
				
				var entry = response[i];
				var entryPermalink = "http://twitter.com/" + entry.user.screen_name + "/status/" + entry.id_str + "";
				var entryBody = entry.text;
				
				
				entryBody = entryBody.parseURL();
				entryBody = entryBody.parseHashtag();
				entryBody = entryBody.parseUsername();
				
				
				// start composing the entry
				tweetsHtml += "<div class='news_item entry";
				
				// check if the current entry is the last entry
				if (i === response.length-1) {
				 	tweetsHtml += " last";
				}
				
				tweetsHtml += "'>";	
					
					tweetsHtml += "<span class='inner_body'>";
						tweetsHtml += entryBody
					tweetsHtml += "</span>";
					
					tweetsHtml += "<span class='time'>";
							tweetsHtml += "<a href='" + entryPermalink + "' title='"+entry.created_at+"'>";
							//tweetsHtml += "<a href='" + entryPermalink + "'>";
							tweetsHtml += entry.created_at; 
						tweetsHtml += "</a>";
					tweetsHtml += "</span>";
					
				tweetsHtml += "</div>";
			}
			
			tweetsHtml += "</div>";
			tweetsHtml += "\n";
			
			$(tweetsHtml).appendTo("#panel_tweets");
			
			/*
			 * EasyDate
			 * http://easydate.parshap.com/
			 * 
			 * @todo: locale
			 * 
			 */
			 
			$.easydate.locales.nlNL = {
				"future_format": "%s %t", 
				"past_format": "%t %s", 
				"second": "seconde", 
				"seconds": "seconden", 
				"minute": "minuut", 
				"minutes": "minuten", 
				"hour": "uur", 
				"hours": "uur", 
				"day": "dag", 
				"days": "dagen", 
				"week": "week", 
				"weeks": "weken", 
				"month": "maand", 
				"months": "maanden", 
				"year": "jaar", 
				"years": "jaren", 
				"yesterday": "gisteren", 
				"tomorrow": "morgen", 
				"just now": "nu", 
				"ago": "geleden", 
				"in": "over" 
			}
			
			var tweetLocale = "nlNL";
			
			switch(siteLang) {
				
				case "en":
					tweetLocale = "enUS";
				break;
				
				case "nl":
					tweetLocale = "nlNL";
				break;
				
			}
			var locale = "nlN"
			
			$(".entry span.time a").easydate({
				live: true,
				set_title: false,
				//locale: tweetLocale
				locale: $.easydate.locales[tweetLocale]
			});
	
			//var easydateEntry = $("#panel_tweets .entry:first span.time a");
			
			//alert( easydateEntry.html() );
			//alert( easydateEntry.attr("title"));
			//alert( easydateEntry.html() === easydateEntry.attr("title"));
	
		}
	}

	/**
	 * Store locator
	 *
	 */
	
	if ($("#store_locator").length) {
		
		var markers = [];
		var infoWindow;
		
		var bounds = new google.maps.LatLngBounds();
		
		var map = new google.maps.Map(document.getElementById("map"), {
			zoom: 7,
			center: new google.maps.LatLng(52.01903,-0.77043),
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl: false
		});
		
		function clearMarkers() {
			
			if (markers) {
				for (var i in markers) {
					markers[i].setMap(null);
				}
				
				markers.length = 0;
			}
			
			var bounds = new google.maps.LatLngBounds();
			
			if (infoWindow) infoWindow.close();
			
		}
		
		function addMarker(location) {
			
			var point = new google.maps.LatLng(
				parseFloat(location.lat),
				parseFloat(location.lng)
			);
			
			bounds.extend(point);
			
			var marker = new google.maps.Marker({
				position : point,
				title    : location.title,
				icon     : "/careplus/templates/default/images/google_maps_marker.png",
				map      : map
			});
			
			var infoWindowContent = "<strong>" + location.title + "</strong>";
			infoWindowContent += "<address>";
			infoWindowContent += location.body;
			infoWindowContent += "</address>";
			
			google.maps.event.addListener(marker, 'click', function() {
				
				if (infoWindow) infoWindow.close();
				
				infoWindow = new google.maps.InfoWindow({
					content: infoWindowContent
				});

				infoWindow.open(map, marker);
				
				$(".result").each(function() {
						
					if ($(this).data("marker") === marker) {
						
						$(".result").removeClass("selected");
						$(this).addClass("selected");
					}
				});
			});
			
			markers.push(marker);
			
			return marker;
		}
		
		function getLocations(init) {
			
			var searchForm = $("#form_store_search");
			
			$.ajax({
				url      : searchForm.attr("action"),
				type     : "POST",
				data     : searchForm.serialize(),
				dataType : 'json',
				success  : function(locations) {
					
					clearMarkers();
					
					$(".result").remove();
					
					$("#store_results .results_heading").hide();
					$("#num_results").hide()
					
					switch(locations.length) {
						
						case 0:
							$("#store_search_results_heading_none").show();
							
						break;
						
						case 1:
							$("#store_search_results_heading_single").show();
							$("#num_results").text(locations.length).show();
							
						break;
						
						default:
							$("#store_search_results_heading_multiple").show();
							$("#num_results").text(locations.length).show();
							
						break;
						
					}
					
					Cufon.refresh();
					
					$(locations).each(function() {
						
						var marker = addMarker(this);
						
						var resultRow = $("<div>", {
							"class" : "result",
							id      : "result_" + this.id,
							click   : function() {
								google.maps.event.trigger($(this).data("marker"), "click");
							}
						})
						.data("marker", marker)
						.appendTo("#results");
						
						var resultTitle = $("<span>", {
							"class" : "location_title",
							text    : this.title
						})
						.appendTo(resultRow);
						
						var resultCity = $("<span>", {
							"class" : "location_city",
							text    : this.city
						})
						.appendTo(resultRow);
					});
					
					// center to the right country
					if (init === true) {
						if(siteLang === "nl") {
							//The netherlands
							map.setCenter(
								new google.maps.LatLng(52.1326,5.2913)
							);
							
							map.setZoom(7);	
						} else if (siteLang === "de") {
							//germania
							map.setCenter(
								new google.maps.LatLng(51.16569,10.45153)
							);
							
							map.setZoom(7);	
						} else {
							//uk
							map.setCenter(
								new google.maps.LatLng(52.01903,-0.77043)
							);
							
							map.setZoom(7);	
						}
					}
					else {
						
						map.fitBounds(bounds);
						
						map.setZoom(12);
					}
					
					// set my location button
					if (navigator.geolocation) {
						
						$("#geo_location").show().click(function(e) {
							e.preventDefault();
							
							navigator.geolocation.getCurrentPosition(
								function (position) {
								
									log(position.coords.latitude);
									log(position.coords.longitude)
									
									map.setCenter(
										new google.maps.LatLng(
											position.coords.latitude,
											position.coords.longitude
										)
									);
									
									map.setZoom(15);
								},
								// fallback
								function() {
									
								}
							)
						});
					}
					
					if (typeof callback == 'function') {
						callback()
					}
					
				}
			});
		}
		
		$("#form_store_search").validate({
			rules          : formRules[siteLang]["form_store_search"].rules,
			messages       : formRules[siteLang]["form_store_search"].messages,
			errorPlacement : function(error, element) {},
			submitHandler  : getLocations
		});
		
		getLocations(true);
		
		
	}
	
	/**
	 * Contactformulier
	 */
	
	if ($("#google_map").length) {
				
		var point = new google.maps.LatLng(52.360364, 5.26223);
		
		var map = new google.maps.Map(document.getElementById("google_map"), {
			zoom: 15,
			center: point,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl: false
		});
		
		var marker = new google.maps.Marker({
			position : point,
			title    : "Care Plus",
			icon     : "/careplus/templates/default/images/google_maps_marker.png",
			map      : map
		});
		
		var contactInfo  = "<strong>Tropenzog B.V.</strong>";
			contactInfo += "<address>";
			contactInfo += "	Zwenkgrasstraat 5<br />";
			contactInfo += "	1313 LC Almere<br />";
			contactInfo += "	036 5334711<br />";
			contactInfo += "	<a target='_blank' href='http://tropenzorg.nl/'>tropenzorg.nl</a><br />";
			contactInfo += "	<a target='_blank' href='http://maps.google.nl/maps?f=q&source=s_q&hl=nl&geocode=&q=tropenzorg&sll=52.494073,4.848656&sspn=2.418159,7.13562&ie=UTF8&hq=tropenzorg&hnear=&ll=52.387806,5.198593&spn=0.037873,0.111494&z=14&iwloc=B'>Routebeschrijving</a><br />";
			contactInfo += "</address>";
		
		google.maps.event.addListener(marker, 'click', function() {
			var infowindow = new google.maps.InfoWindow({
				content: contactInfo
			});
		
			infowindow.open(map,marker);
		});
	}
	 
	/**
	 * Forms
	 */
	
	$("form").each(function(){
		
		var form = $(this),
			formRulesMessages = formRules[siteLang][form.attr("id")]
		;
		
		if ("undefined" !== typeof formRulesMessages) {
			
			form.validate({	
				rules         : formRulesMessages.rules,
				messages      : formRulesMessages.messages,
				errorPlacement: function(error, element) {
					
				},
				submitHandler: function(form) {
					
					form.submit();
				}
			});
			
		}
	});
	
	/**
	 * Font Replacement
	 */
	
	Cufon.replace("h1");
	Cufon.replace(".heading h4");
	Cufon.replace(".rotator_wrapper h2");
	Cufon.replace("#panel_news .news_item h2");
	Cufon.replace("#block_newsletter h3");
	Cufon.replace("#store_results h3");
	Cufon.replace("#review h4");
	
	
	/**
	 * Error 404
	 */
	 
	/*
	 
	 if ($("#error_404").length) {
	 	
	 	var strReferrer=document.referrer.toLowerCase();
	 	
	 	if (location.href.indexOf("noreferrer=true")>=0) strReferrer="";
	 	
	 	
	 	if (strReferrer.length == 0) {
	 		
	 		//not referred from anything at all, apparently!
			var str='';
			str+='Onze suggestie:</p>';
			str+='<p><a href="http://www.careplus.eu/nl/" title="Ga naar de homepage van Careplus.eu ">Home Page Care Plus&reg<\/a> <\/p>	 ';
			str+='<a href="/nl/anti-insect" title="Bekijk onze Anti-Insect producten">Bekijk onze anti-insect producten<\/a><\/p>';
			str+='<a href="/nl/hygiene-tijdens-de-reis" title="Bekijk Hygiene tijdens de Reis producten">Bekijk onze Hygiene tijdens de reis producten<\/a><\/p>';
			str+='<a href="/nl/eerste-hulp-op-reis" title="Bekijk onze Eerste Hulp (EHBO) op reis producten">Bekijk onze Eerste Hulp op Reis (EHBO) producten<\/a><\/p>';
			str+='<a href="/nl/zonbescherming" title="Bekijk onze Zonnebeschermings producten">Bekijk onze Zonnebescherming producten<\/a><\/p>';
			str+='<a href="/site-map/" title="Bekijk sitemap van careplus.eu">Bekijk de Site Map<\/a><\/p>';
			str+='<hr \/>';
			str+='<p><strong>U kunt deze pagina waarschijnlijk niet vinden omdat:<\/strong><\/p>';
			str+='<ol type="a">';
			str+='  <li>Een <strong>bookmark</strong> niet goed werkt<\/li>';
			str+='  <li>Een zoekmachine linkt naar een <strong>niet bestaande pagina</strong><\/li>';
			str+='  <li>Een <strong>verkeerd ingetypt adres </strong>in uw browser<\/li>';
			str+='<\/ol>';
	 			
	 	}
	 	
	 	var blnSearchReferral = false;
	 	var blnInsiteReferral = false;
	 	var strSite = "";
	 	
	 	if (strReferrer.length != 0) {
	 		
	 		//we have been referred to this page some another web page ...
	 		
	 		if ((strReferrer.indexOf(".looksmart.co")>0) ||
	 			(strReferrer.indexOf(".ifind.freeserve")>0) ||
	 			(strReferrer.indexOf(".ask.co")>0) ||
	 			(strReferrer.indexOf("google.")>0) ||
	 			(strReferrer.indexOf("altavista.co")>0) ||
	 			(strReferrer.indexOf("msn.co")>0)||
	 			(strReferrer.indexOf("yahoo.co")>0)) {
	 				
	 			//we have been referred to from a known search engine
	 				
	 			blnSearchReferral=true;
	 			var arrSite=strReferrer.split("/");
	 			var arrParams=strReferrer.split("?");
	 			var strSearchTerms = arrParams[1];
	 			
	 			arrParams=strSearchTerms.split("&");
	 			strSite=arrSite[2];
	 			
	 			var sQryStr="";
	 			
	 			//define what search terms are in use
				var arrQueryStrings = new Array();
				arrQueryStrings[0]="q=";	//google, altavista, msn
				arrQueryStrings[1]="p=";	//yahoo
				arrQueryStrings[2]="ask=";	//ask jeeves
				arrQueryStrings[3]="key=";	//looksmart
				
				for (i=0;i<arrParams.length;i++) {
					
					//loop through all the parameters in the referring page's URL
					for (q=0;q<arrQueryStrings.length;q++) {
						
						sQryStr = arrQueryStrings[q];
						
						if (arrParams[i].indexOf(sQryStr)==0) {
							
							//we've found a search term!
							strSearchTerms = arrParams[i];
							strSearchTerms = strSearchTerms.split(sQryStr);
							strSearchTerms = strSearchTerms[1];
							strSearchTerms = strSearchTerms.replace("+", " ");

						}
					}
				}
				
				document.write ("<p>U zocht op <strong><a href='" + strReferrer + "' target='_blank'>" + strSite + "</a></strong> naar \"<strong>" + strSearchTerms + "</strong>\". Deze pagina bestaat echter niet</p><h2>wij helpen u</h2><p>Op de volgende pagina vindt u wat u zoekt</p>");
					
				// edit and repeat for all pages you want to match to the search phrases found
	 		}
	 	
	}
	*/
});
