/**
 * @author al
 */
// 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($){
	Cufon.now();
	$.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");
	};
	var currArea = '';
	$(".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){
		if(currArea!='') document.location.href = "http://www.cairngormsholidaycottages.com/search/" + currArea + "/";
		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(){
		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();
			if(form.find('input[name="search_string"]').val() == initial_search_string){
				form.find('input[name="search_string"]').val('');
			}
			if (area != '') {
				var str = form.serialize();
				window.location.href = "http://www.cairngormsholidaycottages.com/search/" + area + "/?" + str;
				return false;
			}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();
	})
	var ele =  $("#loff-wrapper .loff-content");
	function runIt() {
		ele =  $("#loff-wrapper .loff-content");
		$(ele).wait(10000).fadeOut(3000, function(){
			$("#loff-wrapper").load("/lib/lasso/offers.lasso", function(){
				$(ele).fadeIn(500, function(){
					runIt();
				});
			});
		});
              
    }
    runIt();
	$.fn.nextOffer = function (){
		$(this).load("/lib/lasso/offers.lasso", function(){
			$(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
			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();
	$('#fav_help').hoverbox();
});
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 (property_id) {
		var list = saveContact(property_id);
	}else{
		var list = getContactList();
	}
	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/CHC_small_logo.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 += '<h2>Your Contact List</h2>';
		contact_list += '<ul>';
		if (typeof list =="array") {
			for (var i = 0, len = list.length; i < len; ++i) {
				contact_list += '<li><input type="checkbox" value="' + list[i].property_id + '" />' + list[i].name + ' - ' + list[i].town + '</li>';
			}
		}else if(typeof list =="string"){
			contact_list += '<li>' + list + '</li>';
		}else{
			contact_list += '<li>Your contact list is empty</li>';
		}
		contact_list += '</ul><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();
		});
		$("#contact_list #del_list").click(function(){
			var ary = [];
			var to_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 = to_delete.length; i < len; ++i) {
				ary.push(to_delete[i].value)
			}
			$('#contact_list').remove();
			redoContactList(ary);
			return showContactList();
		});
		$("#contact_list #enquire_list").click(function(){
			window.location.href="/enquire-multi/";
			return false;
		});
		return false;
	}else{
		$("#contact_list").remove();
	}
	return false;
}
