﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />


var hotel = function(title, address, phone, email, lati, longi, link) {
	this.title = title;
	this.address = address;
	this.phone = phone;
	this.email = email;
	this.lat = lati;
	this.long = longi,
	this.link = link;
	this.html = makeHtml(this);
}

function makeHtml(o) {
	var temp = $(document.createElement("div"));
	var title = $(document.createElement("h2")).html(o.title).appendTo(temp);
	var address = $(document.createElement("p")).html(o.address).addClass("hotelMapInfo");
	var phone = $(document.createElement("span")).html("Phone: " + o.phone).appendTo(address);
	var email = $(document.createElement("a")).html("Email: " + o.email).attr("href", "mailto:" + o.email).appendTo(address);
	var link = $(document.createElement("a")).html("View more information for " + o.title).attr("href","/" + o.link).appendTo(address);
	address.appendTo(temp);
	return temp.html();
};

// object with data for all hotels, used for google map reference
var hotels = [];
hotels[0] = new hotel("Best Western Bolholt Hotel", "Walshaw Road, Bury, Greater Manchester, BL8 1PU", "+44 (0)161 762 4000", "bolholt@lavenderhotels.co.uk", 53.601995, -2.326248,"Bolholt");
hotels[1] = new hotel("Best Western Park Hall Hotel", "Park Hall Road, Charnock Richard, Chorley, Nr Preston, Lancashire, PR7 5LP", "+44 (0)1257 45 5000", "parkhall@lavenderhotels.co.uk", 53.634662, -2.695810,"Park-Hall");
hotels[2] = new hotel("Best Western Everglades Park Hotel", "Derby Road, Widnes, Cheshire, WA8 3UJ", "+44 (0)151 495 5500", "everglades@lavenderhotels.co.uk", 53.385393, -2.712170,"Everglades-Park");
hotels[3] = new hotel("The Oaks Hotel", "Colne Road, Reedley, Burnley, Lancashire, BB10 2LF", "+44 (0)1282 41 41 41", "oaks@lavenderhotels.co.uk", 53.816440, -2.235506,"Oaks");
hotels[4] = new hotel("Best Western Higher Trapp Hotel", "Trapp Lane, Simonstone, Nr Burnley, Lancashire, BB12 7QW", "+44 (0)1282 77 27 81", "highertrapp@lavenderhotels.co.uk", 53.816504, -2.340003,"Higher-Trapp");
hotels[5] = new hotel("The Old Mill Hotel", "Springwood, Ramsbottom, Bury, BL0 9DS", "+44 (0)1706 82 29 91", "oldmill@lavenderhotels.co.uk", 53.650342, -2.323278,"The-Old-Mill");

/// <reference path="jquery-1.3.2-vsdoc2.js" />

String.format = function(text) {
	//check if there are two arguments in the arguments list
	if (arguments.length <= 1) {
		//if there are not 2 or more arguments there's nothing to replace
		//just return the original text
		return text;
	}

	//decrement to move to the second argument in the array
	var tokenCount = arguments.length - 2;
	for (var token = 0; token <= tokenCount; token++) {
		//iterate through the tokens and replace their placeholders from the original text in order
		text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
												arguments[token + 1]);
	}
	return text;
};

function checkCallBack(namefield, phonefield) {

	namevalue = namefield.value;
	phonevalue = phonefield.value;

	if (namevalue != '' && namevalue != 'Your name...' && phonevalue != '' && phonevalue != 'Your phone...') {
		return true
	}
	else {
		alert('Please enter your name and your phone number.');
		return false
	}

}

Date.Difference = function(firstDate, compareDate) {
	var selectDate = Date.fromUKFormat(firstDate);
	var todayDate = compareDate;
	var one_day = 1000 * 60 * 60 * 24

	return Math.ceil((selectDate.getTime() - todayDate.getTime()) / (one_day));
}


Date.fromUKFormat = function(sUK) {
	var A = sUK.split(/[\\\/]/);
	A = [A[1], A[0], A[2]];
	return new Date(Date.parse(A.join('/')));
}

///Prepares the CTA Booking controls with the added scripting they need
function prepareCTARooms(prefix, nightsControlID, roomControlID, checkboxID, advPurchaseDays, HotelControlID, ADPControlID) {
	var dateDiff = Date.Difference($(nightsControlID).parent().siblings(".datepicker").val(), new Date());
	if (dateDiff > advPurchaseDays) {
		$(nightsControlID).parent().siblings(".advPurchase").toggleClass("notValid", false);
		$(checkboxID).attr("disabled", false);
	}
	else {
		$(nightsControlID).parent().siblings(".advPurchase").toggleClass("notValid", true);
		$(checkboxID).attr("disabled", true);
	}

	$(HotelControlID).change(function () {

	    HotelAllowsADP($(HotelControlID).val(), ADPControlID);

	});

	// -- add a datepicker to the CTA
	$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy', minDate: (0), maxDate: (+365),
	    onSelect: function (dateText, inst) {
	        var dateDiff = Date.Difference(dateText, new Date());

	        if (dateDiff > advPurchaseDays) {
            
	            $(this).siblings(".advPurchase").toggleClass("notValid", false);
	            $(checkboxID).attr("disabled", false);
	        }
	        else {
	            $(this).siblings(".advPurchase").toggleClass("notValid", true);
	            $(checkboxID).attr("disabled", true);
	        }
	    }
	});

	$(".calendar").click(function() {

		$(this).siblings(".datepicker").datepicker("show");

	});


	//    // -- add a slider to the number of nights control
	//    $(dateSel).slider({
	//        range: "min", value: 1,	min: 1,	max: 7, slide: function(event, ui) {
	//        $(nightsControlID).val(ui.value);
	//        }
	//    });
	//    
	//    if ($(nightsControlID).val() == "")
	//        $(nightsControlID).val($(dateSel).slider("value"));
	//    else
	//        $(dateSel).slider("option", "value", $(nightsControlID).val() ); 

	// -- add a slider to the number of rooms control with a special function on stop slide
	//    $(roomSel).slider({
	//        range: "min", value: 1,	min: 1,	max: 5, 
	//        slide: function(event, ui) {
	//            $(roomControlID).val(ui.value);
	//        },  
	//        stop: function(event, ui) { 
	//            // -- activates the room occupants changer

	//        }
	//    });
	//    
	//    if ($(roomControlID).val() == "")
	//        $(roomControlID).val($(roomSel).slider("value")); 
	//    else
	//    {
	//        $(roomSel).slider("option", "value", $(roomControlID).val() ); 
	//        

	//    }

	// -- auto set the number of rooms
	changeRoomOccupants(prefix, $(roomControlID).val())

	$(roomControlID).change(function() {

		changeRoomOccupants(prefix, $(roomControlID).val())

	});

}


function HotelAllowsADP(hotelUID, ADPControlID) {

    // -- function to return all Hotel by searching on the Name field
        var o = new Object();
        var objArray = new Array(1);
        o = $.ajax({
            type: "POST",
            url: "/Services/WDS.asmx/HotelAllowsADP",
            data: "{ HotelUID: '" + hotelUID + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (msg, status, err) {
                $(".outputMsg").html("your search was invalid");
            },
            success: function (msg) {
                // -- Loop through all results    						    

                if (msg.d == false) {
                    $(ADPControlID).css("display", "none");
                }
                else {
                    $(ADPControlID).css("display", "block");
                }
            }
        });
        
}


/// -- Function to change the number of room occupatn controls in the room finder CTA
function changeRoomOccupants(prefix, NewNoRooms) {
	// -- function here to add or remove the number of occupant boxes
	var hidPrefix = "#" + prefix + "_roomOcc_";
	var noRooms = $("#uiHidNoRooms").val();

	var occStore = "" + $(".occStore").val() + "";

	var occArray = occStore.split("|");

	$(".occupants .copiedOcc").remove();

	if (occArray.length >= (1))
		$(hidPrefix + "0 select.adult").val(occArray[0])

	if (occArray.length >= (2))
		$(hidPrefix + "0 select.child").val(occArray[1])

	for (var i = 1; i < parseInt(NewNoRooms); i++) {
		// -- the starting position of the previous value array
		// -- multiply the iterator by two to get the right placing
		var occStart = i * 2;
				

		// -- removes any already copied
		if ($(hidPrefix + i) != null)
			$(hidPrefix + i).remove();

		var ctrlID = $(hidPrefix + "0 select.adult").attr("name");
		ctrlID = ctrlID.split("uiSelRoom_")[0];

		$(hidPrefix + "0").clone().attr("id", hidPrefix.replace("#", "") + i).attr("class", "copiedOcc").appendTo($(hidPrefix + "0").parent());

		$("" + hidPrefix + i + " select.adult").attr("name", (ctrlID + "uiSelRoom_" + i + "_adults"));
		if (occArray.length >= (occStart))
			$("" + hidPrefix + i + " select.adult").val(occArray[occStart])

		$("" + hidPrefix + i + " select.child").attr("name", (ctrlID + "uiSelRoom_" + i + "_children"));
		if (occArray.length >= (occStart + 1))
			$("" + hidPrefix + (i) + " select.child").val(occArray[occStart + 1])
	}

	// -- set the current number on exit
	$("#uiHidNoRooms").val(NewNoRooms);

}


///Prepares the CTA Meetings Booking controls with the added scripting they need
function prepareCTAMeeting(daysControlID, PersonsControlID) {
	// -- add a datepicker to the CTA
	$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy', minDate: (0), maxDate: (+365) });

	// -- add a slider to the number of nights control
//	$(".daySlider").slider({
//		range: "min", value: 1, min: 1, max: 7, slide: function(event, ui) {
//			$(daysControlID).val(ui.value);
//		}
//	});

//	if ($(daysControlID).val() == "")
//		$(daysControlID).val($(".daySlider").slider("value"));
//	else
//		$(".daySlider").slider("option", "value", $(daysControlID).val());

//	// -- add a slider to the number of rooms control with a special function on stop slide
//	$(".personsSlider").slider({
//		range: "min", value: 1, min: 1, max: 50,
//		slide: function(event, ui) {
//			$(PersonsControlID).val(ui.value);
//		}
//	});

//	if ($(PersonsControlID).val() == "")
//		$(PersonsControlID).val($(".personsSlider").slider("value"));
//	else
//		$(".personsSlider").slider("option", "value", $(PersonsControlID).val());
}

// Permalinks option
function flashPutHref(href) { location.href = href; }



function homepageFlash() {
	// SWFObject embed
	var flashvars = {
		paramXMLPath: "/flash/param.xml",
		initialURL: escape(document.location)
	}
	var params = {
		base: ".",
		quality: "best",
		bgcolor: "#5C2C56",
		allowfullscreen: "false",
		wmode: "transparent"
	}
	var attributes = {}

	swfobject.embedSWF("/flash/slideshowpro.swf", "gallery", "710", "375", "9.0.0", false, flashvars, params, attributes);
}

function showAccommodation(prefix) {
	$(".peopleAttending").blur(function() {

		// -- any non-numeric chars get reset to zero
		if (isNaN($(this).val()))
			$(this).val(1);
		else {
			// -- check the outer limits to avoid errors            
			if (parseInt($(this).val()) <= 0)
				$(this).val(1);
		}

	});

	if ($(".accommodation").hasClass("isOn")) {

		// -- fire the event to add booking boxes for the amount of people attending the event
		changeRoomOccupants(prefix, $("#" + prefix + "_uiDdlRooms").val());
	}

	$(".accommodateCheck").change(function() {

		if ($(".accommodation").hasClass("isOn"))
			$(".accommodation").removeClass("isOn");
		else {
			$(".accommodation").addClass("isOn");

			// -- fire the event to add booking boxes for the amount of people attending the event
			changeRoomOccupants(prefix, $("#" + prefix + "_uiDdlRooms").val());

			//            
			//            roomsBox.val(Math.round(parseInt($(".peopleAttending").val())/2));

		}
	});
}

function showAdvPurchasePrice(percentageOff) {
	var show = $(".showAdvance input:checked").length;
	if ($(".showAdvance input:checked").length != 0) {
	    changeAdvPurchase(true, percentageOff);

	    changeAllPrices();
	}	

	$(".showAdvance").change(function() {

		if ($(".showAdvance").hasClass("showing")) {
			changeAdvPurchase(false, percentageOff);
		}
		else {
			changeAdvPurchase(true, percentageOff);
		}

		changeAllPrices()
    });
}

function changeAdvPurchase(onSwitch, percentageOff) {
	if (!onSwitch) {
		$(".showAdvance").removeClass("showing");

		$(".specialPrice").remove();

		$(".oldPrice").each(function (index) {
		    $(this).html($(this).html().replace("Was: ", ""));

		    var nightsStaying = $(this).parents("div.room").children("input.hidNightsStay").val();

		    var changedPrice = parseFloat(($(this).html().replace("From £", ""))).toFixed(2);

		    if (isNaN(changedPrice))
		        changedPrice = 0.00;

		    $(this).siblings("input:hidden").val(changedPrice * nightsStaying);
		});

		$(".priceLabel").removeClass("oldPrice");


	}
	else {
		$(".showAdvance").addClass("showing");

		var $collection = $(".priceLabel");

		for (var i = 0; i < $collection.length; i++) {
			var c = $collection[i];

			var newPrice = parseFloat($(c).html().replace("From £", ""));
			var nightsStaying = $(c).parents("div.room").children("input.hidNightsStay").val();

            // -- oaks condition for no single rooms
			if (isNaN(newPrice)) {
			    newPrice = parseFloat($(c).siblings("input:hidden").val()) / nightsStaying;
			}

			newPrice = (newPrice / 100 * (100 - percentageOff));
            
			$(c).addClass("oldPrice");
			$(c).html("Was: " + $(c).html());
			$(c).clone().removeClass("oldPrice").addClass("specialPrice").html(String.format("Now: From £{0}", newPrice.toFixed(2))).insertAfter($($collection[i]));
			$(c).siblings("input:hidden").val(newPrice.toFixed(2) * nightsStaying);
		}
	}

}


function priceAdjuster(topClass, wrap) {

	var show = $(".showAdvance input:checked").length;
	var wrapSel = $(".priceChanger_" + wrap);

	if ($(".showAdvance input:checked").length != 0) {
		var nightsStaying = wrapSel.parents("div.room").children("input.hidNightsStay").val();
		totalPriceChanger(nightsStaying, topClass, wrapSel);
	}

	wrapSel.change(function() {

		var nightsStaying = $(this).parents("div.room").children("input.hidNightsStay").val();
		totalPriceChanger(nightsStaying, topClass, $(this));
	});
}



function changeAllPrices() {
	$("div.room").each(function() {

		var totPrice = $(this).find(".totPrice");
		var nightsStaying = $(this).children("input.hidNightsStay").val();
		var totalPrice = parseFloat(($(this).find("input:checked").parent().siblings("input:hidden").val()));

		totPrice.html(String.format("&pound;{0}", totalPrice.toFixed(2)));

	});
}

function totalPriceChanger(nights, topClass, wrapObj) {

    var totalPrice = parseFloat(wrapObj.siblings("input:hidden").val());

    if (totalPrice > 0) {
        var selector = topClass + " > h4 > .totPrice";
        $(selector).html(String.format("&pound;{0}", totalPrice.toFixed(2)));
    }
}

function makeGoogleMap(mapID) {
	var myOptions = {
		zoom: 12,
		//center: new google.maps.LatLng(hotels[hotelID].lat, hotels[hotelID].long),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: false
	}
	document.getElementById(mapID).style.display = "block";
	$("#" + mapID).animate({
		"width": "400px",
		"height": "400px"
	}, function() {
		$(this).css({ "border": "1px solid #56284F" });
		var map = new google.maps.Map(document.getElementById(mapID), myOptions);
		makeMarkers(map, mapID);
	});
};

function hideGoogleMap(mapID) {
	$("#" + mapID).animate({
		"width": "0px",
		"height": "0px"
	}, function() {
	    document.getElementById(mapID).style.display = "none";
		$(this).css({ "border": "none"});
		$(this).html('');
	});
};

function makeMarkers(map, mapID) {
	var shape = {
		coord: [1, 1, 1, 20, 18, 20, 18, 1],
		type: 'poly'
	};

	var bounds = new google.maps.LatLngBounds();

	for (var i = 0; i < hotels.length; i++) {
		var hotel = hotels[i];
		var image = new google.maps.MarkerImage('http://google-maps-icons.googlecode.com/files/red0' + (i + 1) + '.png')

		var myLatLng = new google.maps.LatLng(hotel.lat, hotel.long);

		var marker = new google.maps.Marker({
			position: myLatLng,
			map: map,
			icon: image,
			shape: shape,
			title: hotel.title,
			html: hotel.html,
			zIndex: 9999
		});

		bounds.extend(myLatLng);
		map.fitBounds(bounds);

		var contentString = "";

		var infowindow = new google.maps.InfoWindow({
			content: contentString
		});
		
		google.maps.event.addListener(marker, "click", function() {
			infowindow.setContent(this.html);
			infowindow.open(map, this);
		});
	}

	setTimeout(function() {
		var closeOuter = $(document.createElement("div")).addClass("closeMap-outer");
		var closeInner = $(document.createElement("div")).addClass("closeMap-inner").text("Close").appendTo(closeOuter);
		$("#" + mapID).append(closeOuter);

		closeOuter.click(function() {
			hideGoogleMap(mapID)
		});
	}, 500);
	
};

// -- facebook link highlighting

$(function(){

    var classAttribute = (function(){
        var ie7 = /MSIE 7.0/g.test(navigator.userAgent),
        ie6 = /MSIE 6.0/g.test(navigator.userAgent),
        docMode = document.documentMode ? document.documentMode.toString() : "",
        classAttr = "class";
        if(docMode === "7" || docMode === "5") {
	        classAttr = "className";
        } else if(docMode === "") {
	        classAttr = (ie7 || ie6) ? "className" : "class";
        };
        return classAttr;
    })();

    (function(subnav){    
        if(subnav) {

            var links = subnav.getElementsByTagName("a"),
            i = links.length;
            while(i--) {
                var link = links[i],
                tgt = link.target,
                href = link.href;
                if(tgt === "_blank" && /facebook/.test(href)) {
                    link.setAttribute(classAttribute,"fbLink");
                };
            };

        };    
    })(document.getElementById("sideNav"));

});
