/**
 * @author al
 */
google.load('search', '1');
cache_image= new Image(100,25); 
cache_image.src="/images/button_fav_over.gif";

var mask = '<div id="mask" style="position:absolute; top: 0px; left:0px; width:100%;height:100%; background-color:#666666; "><div style="position: absolute;top: 50%;left: 50%;margin-left: -20px;margin-top: -20px; overflow:hidden;background-color:#000000; padding:36px;"><img src="/images/ajax-loader.gif" width="32" height="32" /></div></div>';

// Array Remove - By John Resig (MIT Licensed)
//Array.prototype.remove1 = function(from, to) {
//  var rest = this.slice((to || from) + 1 || this.length);
 // this.length = from < 0 ? this.length + from : from;
 // return this.push.apply(this, rest);
//};
// Array Remove - By Al Fleming
//takes either and array or a commaseparate list of indices to be removed from the array

Array.prototype.remove = function(indices) {
	var returnArray = [];
	indices = typeof(indices) == 'array' ?  "," + indices.join() +"," : "," + indices +",";//add the commae for the indeOf function
	for(var i=0; i<this.length; i++){
		if(indices.indexOf("," + i +",")<0){
			returnArray.push(this[i])
		}
	}
	this.length = 0;
	return this.push.apply(this,returnArray);
};



jQuery(document).ready(function($){
	loadingPic= new Image(32,32); 
	loadingPic.src="http://www.cairngorms-park.com/images/ajax-loader.gif";
	$.getScript("/lib/jquery/jquery.jgrowl.js", function(){
	
	});
	$.getScript("/lib/jquery/jquery.hoverbox.min.js", function(){
		$('#fav_help').hoverbox();
		$('.tooltip').hoverbox();
	});
	$.fn.wait = function(time, type) {
		time = time || 20000;
		type = type || "fx";
		return this.queue(type, function() {
			var self = this;
			setTimeout(function() {
				$(self).dequeue();
			}, time);
		});
	};

	$.postJSON = function(url, data, callback) {
		$.post(url, data, callback, "json");
	};
	$("#audio1").jPlayer({
  		ready: function () {
  			$(this).jPlayer("setMedia", {
  				mp3: "/assets/click1.mp3",
  				wav: "/assets/click1.wav"
      		});
    	},
    	swfPath: "/lib/jquery/",
    	solution: "html, flash",
    	preload: "auto"
    });
 
	$("a").mousedown(function(){
		try{
			//document.getElementById("click1").play();
			$("#audio1").jPlayer("play");
		}catch(e){
			
		}
	})
	currArea = '';
	currType = '';
	$(".cnpmap").mouseover(function(e){
		var area = $(this).attr('alt');
		$("#map1-" + area).css("display", "inline");
		switch(area){
			case 'dal':
				$("#map1-legend").html("<strong>Laggan and Dalwhinnie</strong><br />Including Glen Truim");
				currArea = "Laggan";
				break;
			case 'nwt':
				$("#map1-legend").html("<strong>Newtonmore</strong><br />and the surrounding area");
				currArea = "Newtonmore";
				break;
			case 'kgu':
				$("#map1-legend").html("<strong>Kingussie</strong><br />and the surrounding area. Including Glen Tromie");
				currArea = "Kingussie";
				break;
			case 'kcg':
				$("#map1-legend").html("<strong>Kincraig, Feshiebridge and Insh Village</strong><br />Including Glen Feshie");
				currArea = "Kincraig";
				break;
			case 'avm':
				$("#map1-legend").html("<strong>Aviemore</strong><br />including Coylumbridge and Glenmore");
				currArea = "Aviemore";
				break;
			case 'crb':
				$("#map1-legend").html("<strong>Carrbridge</strong><br />and the surrounding area");
				currArea = "Carrbridge";
				break;
			case 'ntb':
				$("#map1-legend").html("<strong>Nethy Bridge</strong><br />and the surrounding area");
				currArea = "Nethy-Bridge";
				break;
			case 'bog':
				$("#map1-legend").html("<strong>Boat-of-Garten</strong><br />and the surrounding area");
				currArea = "Boat-of-Garten";
				break;
			case 'grn':
				$("#map1-legend").html("<strong>Grantown-on-Spey</strong> including Dulnain Bridge<br />");
				currArea = "Grantown-on-Spey";
				break;
			case 'tmt':
				$("#map1-legend").html("<strong>Glenlivet</strong><br />Tomintoul, Strathdon and the surrounding area");
				currArea = "Glenlivet";
				break;
			case 'blt':
				$("#map1-legend").html("<strong>Ballater</strong><br />and Royal Deeside");
				currArea = "Ballater";
				break;
			case 'bmr':
				$("#map1-legend").html("<strong>Braemar</strong>");
				currArea = "Braemar";
				break;
			case 'ang':
				$("#map1-legend").html("<strong>Angus Glens</strong>");
				currArea = "Angus-Glens";
				break;
			case 'hpe':
				$("#map1-legend").html("<strong>Highland Perthshire</strong>");
				currArea = "Highland-Perthshire";
				break;
		}
		
	});
	$(".cnpmap").mouseout(function(e){
		var area = $(this).attr('alt');
		$("#map1-" + area).css("display", "none");
		$("#map1-legend").html('Click on an area to view accomodation<br /><br />');
	});
	$(".cnpmap").click(function(e){
		var tmessage= "<strong>Please choose the type of accommodation you want by clicking on the coloured icon above</strong>";
		if (currType != "" && currType!=null) {
			if (currArea != '') {
				//$('body').append(mask)
				//$('body #mask').fadeTo("fast", 0.5).show();
				document.location.href = "http://www.cairngorms-park.com/search/" + currArea + "/?accomm_type=" + $('#search1 input[name="accomm_type"]').val();
			}
			else {
				$.jGrowl(tmessage);
			}
		}else{
			$.jGrowl(tmessage);
		}
		return false;
	});
	var ajaxFormOptions = { 
		target: '#newsletter-form',   
        beforeSubmit: showRequest1, 
        success: showResponse1, 
		url:"/lib/lasso/contact.lasso"
   	}; 
	function isValidEmail(emailAddress) {
			var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
			return pattern.test(emailAddress);
		}
	$("#newsletter-form").ajaxForm(ajaxFormOptions);
	$("#newsletter-form a").click(function(){
		$("#newsletter-form").ajaxSubmit(ajaxFormOptions);
	});
	function showRequest1(formData, jqForm, options){
		var tcontinue = true;
		if(!isValidEmail(formData[0].value)){
			tcontinue = false;
			$('#newsletter-form input[name="email"]').css('backgroundColor', '#ffaeb4');
		}
		if(tcontinue ==  true){
			$('#newsletter-form').append('<div id="mask" style="position:absolute; top: 0px; left:0px; width:100%;height:100%; background-color:#666666; "></div>')
			$('#newsletter-form #mask').append('<div style="width: 32px;height: 32px;position: absolute;top: 50%;left: 50%;margin-left: -20px;margin-top: -20px; overflow:hidden;background-color:#000000; padding:6px;"><img src="/images/ajax-loader.gif" /></div>');
			$('#newsletter-form #mask').fadeTo("slow", 0.5).show();
		}else{
			return false;
		}
	}
	function showResponse1(responseText, statusText){
		$('#newsletter-form #mask').remove();
	}
	$('#footer ul li a#admin-link').click(function(){
		 $("head").append("<link />");
    		css = $("head").children(":last");
    		css.attr({
     		rel:  "stylesheet",
      		type: "text/css",
     		href: "/lib/jquery/css/smoothness/jquery-ui-1.8.custom.css"
   		 });
		$.getScript("/lib/jquery/jquery-ui-1.8.custom.min.min.js", function(){
			var dHTML = '<div id="dialog" title="Login to Admin?"><img class="logofloatleft" src="/images/easyeditorlogo.png" alt="Easy Editor" /><p>Enter your username/password:</p>';
			dHTML +='<form method="POST" action="#"><fieldset><label for="username">Username</label><input type="text" name="username" id="username" class="text ui-widget-content ui-corner-all" />';
			dHTML +='<label for="password">Password</label><input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" /></fieldset><input type="hidden" name="actions" value="login"></form></div>';
			$('body').append(dHTML);
			$("#dialog").dialog({
				bgiframe: true,
				resizable: false,
				height:400,
				width:400,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					Cancel: function() {$(this).dialog('close')},
					Submit: function() {
						var form = $("#dialog form");
						
						form.attr("action", window.location.href);
					
						form.submit();				
					}
				},
				close: function(event, ui) {$(this).remove();}
			});
		});
		return false;
	});	
	var initial_search_string = "search text...";
	$("#search1").ajaxForm({
		beforeSubmit: function(data, form, options){
			var area = form.find('select[name="area"]').val();
			var accomm_type = form.find('input[name="accomm_type"]').val();
			if(form.find('input[name="search_string"]').val() == initial_search_string){
				form.find('input[name="search_string"]').val('');
			}
			if (area != '') {
				if (accomm_type != '') {
					//$('body').append(mask)
					//$('body #mask').fadeTo("fast", 0.5).show();
					var str = form.serialize();
					window.location.href = "http://www.cairngorms-park.com/search/" + area + "/?" + str;
					return false;
				}else{
					$.jGrowl("<strong>Please choose the type of accommodation you want</strong>");
				}
			}else{
				$.jGrowl("<strong>Please choose an area</strong>");
				return false;
			}
		}
	});
	
	$("#search1 input[name='search_string']").focus(function(){
		if($(this).val() == initial_search_string){
			$(this).val('');
		}
	});
	$("#search1 input[name='search_string']").blur(function(){
		if($(this).val() == ''){
			$(this).val(initial_search_string);
			$(this).css({'color': '#bebebe'})
		}
	});
	$("#search1 input[name='search_string']").keydown(function(){
		$(this).css({'color': 'black'})
	});
	
	$("#search1 a.button_link").click(function(){
		$("#search1").submit();
		return false;
	})
	var ele =  $("#loff-wrapper .loff-content");
	var params = {};
	var nextCount = 1;
	function runIt() {
		ele =  $("#loff-wrapper .loff-content");
		//console.log(params.count)
		if(params.count > -1){
			nextCount++;
			params.count = nextCount;
			
		}
		$(ele).wait(6000).fadeOut(1000, function(){
			$("#loff-wrapper").load("/lib/lasso/offers.lasso", params, function(response, status, xhr){
				if(response.indexOf("No Offers found")>0){ //If no offers left then return to random sequence
					params = {};
					nextCount = 1;
				}
				$(ele).fadeIn(500, function(){
					runIt();
				});
			});
		});
              
    }
	if(typeof(isAdmin)=="undefined" ){//only run offers if wer are not logged into to admin
		 runIt();
	}
   	
	$.fn.nextOffer = function (){
		params = {'functions': 'next', 'count' : nextCount};
		$(this).load("/lib/lasso/offers.lasso", params, function(response, status, xhr){
			if(response.indexOf("No Offers found")>0){ //If no offers left then return to random sequence
				params = {};
				nextCount = 1;
			}
			$(this).fadeIn(500, function(){
				runIt();
			});
		});
	}
	

	


	
	
	//////////////////////// Scripts routine ////////////////////////
	/*loads scripts of type text/plain and evaluates them and, once loaded, 
	 * it evaluates the contents. This means <script> tages can have 
	 * both a src and contents
	 */
	var scripts = $('script[type="text/plain"]'); ///scripts must be text/plain or jQuery/Jaxer will run them on the serverside
	
	
	jQuery.each(scripts, function(i, val){
		var script=this;
		 //if theres actual script rather than just a 
		var scriptText = script.text;
		
		if($(this).attr('src') && $(this).attr('src')!=''){ //this should never happen as Jaxer deals with src scripts
			//console.log(script)
			var parent = $(script).parent();
			//jQuery.get($(this).attr('src'), {}, function(data, textStatus){
				//console.log('loaded')
					//console.log(scriptText);
					//(new Function(data))(eval(scriptText));
					//eval(scriptText);
			//}, "script");
						
			//jQuery.getScript($(this).attr('src'), function(data, textStatus){
				//console.dir(script.parent());
				//console.log(this)
				//console.log(i +" embedded: "+ scriptText)
				//eval(scriptText);
			//});
		}else{
			(new Function(scriptText))();
		}
	});
	/////////////////////////////////////////////////////////////////
	
	$(".property_details .property_thumb").hover(function(){
		//alert($(this).attr('src').replace('thumb', 'large'))
		$(".property_details #property_image").css('backgroundImage', 'url(' + $(this).attr('src').replace('thumb', 'large') + ')');
	});
	$(".property_details .contact").click(function(){
		var block = $(".property_details .contact .further_contact_details");
		if (block.css('display') == 'none') {
			block.css('display', 'block');
		}else{
			block.css('display', 'none');
		}
	});
	$('.overlayImage').overlayImage();
	//Cufon.refresh();
	//$('#type-buttons li').click(function(){
	//	var btype = setPageType($(this).attr('id'))
	//	setAccommType(btype);
	//});
	currType = getAccommType(); //gets current type of accommodation from server session
	if(currType!=null && currType!=""){ //sets ups page to use current type as default
		setPageType(currType);
		$('#search1 input[name="accomm_type"]').val(currType);
	}
	
	$('.menu > li').bind('mouseover', menu_open);
	$('.menu > li').bind('mouseout',  menu_timer);
	$("a[rel^='popup']").click(function(){
		$.getScript("/js/gs-search.js", function(){
			if ($("#gs-search-wrapper").length == 0) {
				var search_wrapper = '<div id="gs-search-wrapper" style="display:none;"><a class="closebutton"><img src="/images/close.png" alt="close" border="0" /></a>';
				search_wrapper += '<form id="gs_list_form"><fieldset id="gs_list_fields"><legend class="title png"><span>Search This Site</span></legend>';
				search_wrapper += '<div style="margin-bottom:12px;"><img style="float:left; margin-right:10px;" src="/images/AccommCairngormslogosmall.png" width="150" height="58" alt="Accommodation Cairngorms" /><div id="gs-search1-form"></div></div>';
				search_wrapper += '<div id="gs-search1"></div><div id="branding"  style="float: left; width:280px;"></div>';
				search_wrapper += '</fieldset></form></div>';
				$("body").append(search_wrapper);
				
				/// start mask funcs ///
				var maskHeight = $(document).height();  
        		var maskWidth = $(window).width();  
      			$('#mask').css({'width':maskWidth,'height':maskHeight});    
        		$('#mask').fadeTo("slow",0.8);
				/// end mask funcs /// 
				
				gsonLoad();
				$('#gs-search-wrapper').animate({
					opacity: 'toggle'
				}, 400).positionCenter({top:150});
				$("#gs-search-wrapper .closebutton, #gs-search-wrapper #close_list").click(function(e){
					e.preventDefault();  
        			$('#mask').hide();  
					$("#gs-search-wrapper").remove();
					return false;
				});
			}
				
		});
		
		return false;
	});
	
});
//function setAccommTypeLocal(b){
	
//}


//window.setTimeout("setAccommTypeLocal();", 1);
function setPageType(btype){
	menu_close();
	currType = btype;
	$('#search1 input[name="accomm_type"]').val(btype);
	if (btype == 1) {
		$('.menu li a#menu-display').html('Hotels');
		$('.menu li a#menu-display').css('background', '#C2BDA9 url(/images/icons/button-hotel-over.png) no-repeat -5px -1px');
		//$("#spot").css('background', 'transparent url(/images/spot.png) no-repeat 0 0');
	}else if (btype == 2) {
		$('.menu li a#menu-display').html('Bed and Breakfasts');
		$('.menu li a#menu-display').css('background', '#C2BDA9 url(/images/icons/button-bb-over.png) no-repeat -5px -1px');
		//$("#spot").css('background', 'transparent url(/images/spot.png) no-repeat 30px 0');
	}else if (btype == 4) {
		$('.menu li a#menu-display').html('Camp/Caravan sites');
		$('.menu li a#menu-display').css('background', '#C2BDA9 url(/images/icons/button-camp-over.png) no-repeat -5px -1px');
		//$("#spot").css('background', 'transparent url(/images/spot.png) no-repeat 60px 0');
	}else if (btype == 5) {
		$('.menu li a#menu-display').html('Hostels/Bunk-houses');
		$('.menu li a#menu-display').css('background', '#C2BDA9 url(/images/icons/button-hostel-over.png) no-repeat -5px -1px');
		//$("#spot").css('background', 'transparent url(/images/spot.png) no-repeat 90px 0');
	}else if (btype == 3) {
		$('.menu li a#menu-display').html('Self-catering');
		$('.menu li a#menu-display').css('background', '#C2BDA9 url(/images/icons/button-sc-over.png) no-repeat -5px -1px');
		//$("#spot").css('background', 'transparent url(/images/spot.png) no-repeat 120px 0');
	}
	return currType;
}
////Accom Type Menu functions////
var timeout         = 200;
var closetimer		= 0;
var ddmenuitem      = 0;
function menu_open(){
	menu_canceltimer();
	menu_close();
	ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');
}
function menu_close(){	
	if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}
	
function menu_timer(){	
	closetimer = window.setTimeout(menu_close, timeout);
}
function menu_canceltimer(){	
	if(closetimer){	
		window.clearTimeout(closetimer);
		closetimer = null;}
}
document.onclick = menu_close;
////End Accom Type Menu functions////
function translate(lang_code){
	javascript:window.location='http://www.google.com/translate_c?hl=en&langpair=en%7C' + lang_code +'&u='+ window.location.href
}
function setItemsPage(num){
	var loc = window.location.href;
	var patt1 = /[\?&]?setItemsPage=[^&]*/g;
	loc = loc.replace(patt1,'');
	window.location.href = loc.indexOf('?')>0 ? loc + '&setItemsPage=' + num :  loc + '?setItemsPage=' + num;
}
function showContactList(property_id){
	if ($("#contact_list").length == 0) {
		var contact_list = '<div id="contact_list" style="display:none;"><a class="closebutton"><img src="/images/close.png" alt="close" border="0" /></a> <form id="contact_list_form"><fieldset id="contact_list_fields"><legend class="title png"><span>Your Favourites List</span></legend>';
		contact_list += '<img style="float:left; margin-right:10px;" src="/images/AccommCairngormslogosmall.png" width="150" height="62" alt="Cairngorm Holiday Cottages" />';
		contact_list += '<br /><p style="font-size:0.9em;">You can add accommodation that you are interested in to this list and then make enquiries to them all with just one click. Just click the "Make Enquiry" button below when you are ready</p>';
		contact_list += '<ul id="current_contact_list"></ul>';
		contact_list += '<a id="del_list" class="button_link" href="#" style="float:right;margin-left:10px;"><span>Delete Selected</span></a>';
		contact_list += '<a id="enquire_list" class="button_link" href="#" style="float:right;"><span>Make Enquiry</span></a>';
		contact_list += '<a id="close_list" class="button_link" href="#" style="clear:both;float: left;margin-left:135px;margin-top:20px;"><span>Continue&nbsp;Browsing</span></a>';
		contact_list += '</fieldset></form></div>';
		$("body").append(contact_list);
		$('#contact_list').animate({opacity: 'toggle'}, 400).positionCenter();
		$("#contact_list .closebutton, #contact_list #close_list").click(function(){
			$("#contact_list").remove();
			return false;
		});
		
		
		$("#contact_list #del_list").click(function(){
			var ary = [];
			var to_delete = $('#contact_list_form input:checkbox[checked]'); //just used on lists to reset bg etc.
			for (var i = 0, len = to_delete.length; i < len; ++i) {
				restoreListItembg(to_delete[i].value);
			}
			var not_delete = $('#contact_list_form input:checkbox:not([checked])'); //this creates an array of UNTICKED checkboxes that will form the new list. i.e. ticked lines are excuded.
			for (var i = 0, len = not_delete.length; i < len; ++i) {
				ary.push(not_delete[i].value)
			}
			$('#contact_list').remove();
			redoContactList(ary);
			return showContactList();
		});
		$("#contact_list #enquire_list").click(function(){
			window.location.href="/enquire-multi/";
			return false;
		});
		if (property_id) {
			var list = saveContact(property_id);
		}else{
			var list = getContactList();
		}
		if (typeof list =="object") {
			for (var i = 0, len = list.length; i < len; ++i) {
				var propName = list[i].name.replace(/ /g, '-')
				$("#contact_list #current_contact_list").append('<li><input type="checkbox" value="' + list[i].property_id + '" /><a href="/accommodation/' + propName + '/">' + list[i].name + ' - ' + list[i].town + '</a></li>');
			}
		}else if(typeof list =="string"){
			$("#contact_list #current_contact_list").append('<li>' + list + '</li>');
		}else{
			$("#contact_list #current_contact_list").append('<li>Your contact list is empty</li>');
		}
		return false;
	}else{
		$("#contact_list").remove();
	}
	return false;
}
function setListItembg(property_id){
	$("#" + property_id).css({"backgroundColor":"#c5ffc6"});
	$("#" + property_id +" .active_corner").addClass("active_corner_selected").removeClass("active_corner");
}
function restoreListItembg(property_id){
	$("#" + property_id).css({"backgroundColor":"white"});
	$("#" + property_id +" .active_corner_selected").addClass("active_corner").removeClass("active_corner_selected");
}
