var mycurrentlocation = window.location.toString();

if(mycurrentlocation.substring(0,11).indexOf("http://www.") == -1) {
	tmpLocation=mycurrentlocation.replace("http://mondial-movers.nl", "http://www.mondial-movers.nl"); 
	window.location = tmpLocation;
	//window.location.replace(tmpLocation);
}


/* Declare a namespace for the site */
var Site = window.Site || {};

/* Create a closure to maintain scope of the '$'
   and remain compatible with other frameworks.  */
(function($) {
	/**
	 * Cookie plugin
	 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
	 * Dual licensed under the MIT and GPL licenses:
	 * http://www.opensource.org/licenses/mit-license.php
	 * http://www.gnu.org/licenses/gpl.html
	 */
	jQuery.cookie = function(name, value, options) {
		if (typeof value != 'undefined') { // name and value given, set cookie
			options = options || {};
			if (value === null) {
				value = '';
				options.expires = -1;
			}
			var expires = '';
			if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				var date;
				if (typeof options.expires == 'number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				} else {
					date = options.expires;
				}
				expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
			}
			// CAUTION: Needed to parenthesize options.path and options.domain
			// in the following expressions, otherwise they evaluate to undefined
			// in the packed version for some reason...
			var path = options.path ? '; path=' + (options.path) : '';
			var domain = options.domain ? '; domain=' + (options.domain) : '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		} else { // only name given, get cookie
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
	};	
	//same as $(document).ready();
	$(function() {
		/* disable no javascript message */
		$("#nojs-warning_container").remove();

		/* Lightbox init */
		$("a.lightbox").fancybox({
			'overlayShow': true,
			'overlayColor': '#ffffff',
			'overlayOpacity': 0.75,
			'autoScale': false,
			'titleShow': false,
			'zoomSpeedIn': 600,
			'zoomSpeedOut': 500
		});
		$("a.lightiframe").fancybox({
			'overlayShow': true,
			'overlayColor': '#ffffff',
			'titleShow': false,
			'overlayOpacity': 0.75,
			'zoomSpeedIn': 600,
			'zoomSpeedOut': 500,
			'frameWidth': 493,
			'frameHeight': 310,
			'hideOnContentClick': false
		});
		// open external and pdfs in new window/tab
		$("a[rel=external]").attr('target', '_blank').addClass('extlink');
		$("a[rel=ext]").attr('target', '_blank').addClass('extlink');
		$("a[rel=exte]").attr('target', '_blank');
		$("a.pdf").attr('target', '_blank');

		// smoothscroll
		// new SmoothScroll({ duration: 800 });
		
	/*	// sliders are deactivated for now
		$('#slider-inner ul').anythingSlider({
			width               : 936,   // if resizeContent is false, this is the default width if panel size is not defined
			height              : 285,   // if resizeContent is false, this is the default height if panel size is not defined
			resizeContents      : true, // If true, solitary images/objects in the panel will expand to fit the viewport
			startStopped        : false,  // If autoPlay is on, this can force it to start stopped
			navigationFormatter : function(index, panel){ // Format navigation labels with text
				return ['1', '2', '3', '4'][index - 1];
			}
		});
	*/
		// hide/show default search text
		$("#sitesearch").click(function() { 
			var default_search_text = "Zoeken";
              if (this.value == default_search_text) {
                this.value = "";
              }
		}).blur(function() { 
			var default_search_text = "Zoeken";
              if (this.value =="" ) {
                this.value = default_search_text;
              }
		});
		
		// harmonica
		$('#accordion li .collapse').hide();
		$('#accordion li:first .collapse').show();
		$('#accordion li h2').click(function() {
			var checkElement = $(this).next();
			if((checkElement.is('.collapse')) && (checkElement.is(':visible'))) {
				return false;
			}
			if((checkElement.is('.collapse')) && (!checkElement.is(':visible'))) {
				$('#accordion .collapse:visible').slideUp('normal');
				checkElement.slideDown('normal');
				return false;
			}
		});
		// nasty but necessary: ie6 detection for topmenu hover
		if($.browser.msie && parseInt($.browser.version) <= 6) {
			// nasty
			$('body').addClass('ie6');
			$('.submenuholder').css('height','91px'); // force dimension
			$('.submenuholder').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});
		}
		$(function() {
			$(".boxes.ta a:first").css("margin-left","0");
			$(".boxes.hi :first").css("margin-left","0");
			$(".wide.actual .box:first").css("margin-left","0");
			$("#footermenu ul li:first").css("border-left","none");
		});
		$('a.print').click(function() {
			window.print()	
		});
		// binds form submission and fields to the validation engine
        $("#contactform").validationEngine();
	});
	function position_bg_image () {
		// position background image
		var body_bg_position = ($(document).width()/2)+28;
		$("body").css("background-position", body_bg_position +"px -27px");	
	}
	function setOrientation() {
		if(window.orientation != undefined) {
			var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait';  
			var inv_orient = orient == 'portrait' ?  'landscape' : 'portrait';
			$(document.body).addClass(orient);
			$(document.body).removeClass(inv_orient);
			//alert(window.orientation);
			//alert(document.body.className);
			if(orient == 'portrait') {
				//$('p.logo a img').remove();
				//$('p.logo a').append('<img src="/core/main/templates/mondial/_/img/logo.png" alt="logo" title="home" />');
			} else {
				//$('p.logo a img').remove();
			}
		}
	}
			
	$(window).load(function() {
		setOrientation();
		position_bg_image();
		$(window).resize(function() {position_bg_image();});
		/* Load references from mondial-movers.nl/tevredenheid */
		$.ajaxSetup ({  
			async:       true,
    		global:      false,
    		cache:       false,
			dataType:    'json',
    		ifModified:  false
			// error:       function(xhr) { console.log("error", arguments); },
			// success:     function() { console.log("success", arguments); }
			// error: function(xhr) { console.log("error", arguments); }
		});  
		if($('div.box.testim').length) {
			// load the testimonials for the brief overview (eg on homepage)
			var number_to_load = 3;
			var testim_url = 'http://www.mondial-movers.nl/tevredenheid/pit/kt/webservice.php?count='+number_to_load + '&' + new Date().getTime();
			$.ajax({
				url: testim_url,
				type: 'get',
				timeout: 500,
				dataType: 'json',
				statusCode: {404: function() {alert('page not found');}},
				success: function(request) {
					var items = [];
					var info = request.info;
					$.each(info, function(key, value) {
						this_avg = info[key].avg;
						/* use this only for the star-rated version
						var stars = 5;
						if(this_avg > 9 && this_avg <= 10) {
							stars   = 5;
							stars_s = '*****';
						} else if(this_avg > 7 && this_avg <= 9) {
							stars   = 4;
							stars_s = '****';
						} else if(this_avg > 5 && this_avg <= 7) {
							stars   = 3;
							stars_s = '***';
						} else if(this_avg > 3 && this_avg <= 5) {
							stars   = 2;
							stars_s = '**';
						} else if(this_avg > 1 && this_avg <= 3) {
							stars   = 1;
							stars_s = '*';
						} else {
							stars   = 0;
							stars_s = '-';	
						}
						*/
						this_avg = Math.round(this_avg*10)/10;
						// items.push('<li><a href="#' + info[key].hash + '" class=""><h3>' + info[key].opmerkingen +'</h3><span class="rated stars' + stars +'">Waardering: ' + stars_s + '</span><hr class="clr" /></a></li>');
						items.push('<li><a href="/content/klanttevredenheid.html#' + info[key].hash + '" class=""><h3>' + info[key].opm_short +'<span class="name">' + info[key].name +'</span></h3><span class="rate-figure"><span>' + this_avg + '</span></span><hr class="clr" /></a></li>');
					});
					$('#box-testim-data').removeClass('loading');
					$('<ul/>', {
						'class': 'list',
						html: items.join('')
					}).appendTo('#box-testim-data');

				},
				error: function(request,error) {
					$('#box-testim-data').removeClass('loading').addClass('error');
					if (error == "timeout") {
						$('#box-testim-data').append("timeout loading data");
					} else {
						$("#box-testim-data").append("ERROR: " + error);
					}
				},
				complete: function() {}
				
			});
		} 
		if($('div#testim-overview').length) {
			// load the testimonials for the overview page
			var number_to_load = 999;
			var page = 0;
			var testim_url = 'http://www.mondial-movers.nl/tevredenheid/pit/kt/webservice.php?count='+number_to_load + '&page=' + page + '&' + new Date().getTime();
			$.ajax({
				url: testim_url,
				type: 'get',
				timeout: 500,
				dataType: 'json',
				statusCode: {404: function() {alert('page not found');}},
				success: function(request) {
					var items = [];
					var info = request.info;
					$.each(info, function(key, value) {
						this_avg = info[key].avg;
						this_avg = Math.round(this_avg*10)/10;
						// items.push('<li><a href="#' + info[key].hash + '" class=""><h3>' + info[key].opmerkingen +'</h3><span class="rated stars' + stars +'">Waardering: ' + stars_s + '</span><hr class="clr" /></a></li>');
						items.push('<li><span class="testim-info"><span class="opm">' + info[key].opmerkingen + '</span><span class="name">' + info[key].name + ', '+ info[key].city + '</span><span class="mover-date"><span class="mover">Met ' + info[key].mover_name + '</span><span class="date"> op: ' + info[key].move_date + '</span></span></span><span class="rate-figure"><span>' + this_avg + '</span></span><hr class="clr" /></li>');
			
					});
					$('#testim-overview').removeClass('loading');
					$('<ul/>', {
						'class': 'list',
						html: items.join('')
					}).appendTo('#testim-overview');
				},
				error: function(request,error) {
					$('#testim-overview').removeClass('loading').addClass('error');
					if (error == "timeout") {
						$('#testim-overview').append("timeout loading data");
					} else {
						$("#testim-overview").append("ERROR: " + error);
					}
				},
				complete: function() {}
			});
		} 
		if($('div#mondial_kt_avg').length) {
			// load the survey averages for all known movers
			var testktavg_url = 'http://www.mondial-movers.nl/tevredenheid/pit/kt/webservice-all.php?mode=build&s_id=1&' + new Date().getTime();
			$.ajax({
				url: testktavg_url,
				type: 'get',
				timeout: 10000,
				dataType: 'json',
				statusCode: {404: function() {alert('page not found');}},
				success: function(request) {
					var items = [];
					var info = request.info;
					$.each(info, function(key, value) {
						this_avg = info[key].mover_avg;
						this_avg = Math.round(this_avg*10)/10;
						items.push('<li id="'+ info[key].mover_id +'"><span class="mover-name">' + info[key].mover_name +'</span><span class="mover-avg">' + this_avg + '</span><span class="mover-cnt"> (' + info[key].mover_cnt + ' enquêtes)</span></li>');
					});
					$('#mondial_kt_avg').removeClass('loading');
					$('<ul/>', {
						'class': 'list',
						html: items.join('')
					}).appendTo('#mondial_kt_avg');
				},
				error: function(request,error) {
					$('#mondial_kt_avg').removeClass('loading').addClass('error');
					if (error == "timeout") {
						$('#mondial_kt_avg').append("timeout loading data");
					} else {
						$("#mondial_kt_avg").append("ERROR: " + error);
					}
				},
				complete: function() {}
			});
		} 
		if($('#pit_tinymenu')) {
			/* ui actions for the Pit Tiny Menu (PTM) */
			// store settings in array and init ptm
			var ptm_settings = new Array();
			ptm_settings['ptm_display'] = "none";
			$('#pit_tinymenu_items').hide();		
			// toggle the PTM based on cookie
			if ($.cookie('ptm_display')) {
				ptm_settings['ptm_display'] = $.cookie('ptm_display');
				if(ptm_settings['ptm_display'] == "none") {
					$('#pit_tinymenu_items').hide();
				} else {
					$('#pit_tinymenu_items').show();
				}
			} else {
				$.cookie('ptm_display', ptm_settings['ptm_display'], { path: '/' });	
			}
			// toggle the PTM (and store state in cookie)
			$('#pit_tinymenu_nav_btn_link').click(function() {
				$('#pit_tinymenu_items').slideToggle('fast', function() {
					ptm_settings['ptm_display'] = ( ptm_settings['ptm_display'] == "none" )? "block" : "none"											
					$.cookie('ptm_display', ptm_settings['ptm_display'], { path: '/' });
				});
			});
		}
	});
	$(window).bind("orientationchange", function() {
		setOrientation();
	});
})(jQuery);
