/* cookies */
function Get_Cookie( check_name )
{
    try
    {
	    var a_all_cookies = document.cookie.split( ';' );
	    var a_temp_cookie = '';
	    var cookie_name = '';
	    var cookie_value = '';
	    var b_cookie_found = false;
	    for ( i = 0; i < a_all_cookies.length; i++ )
	    {
		    a_temp_cookie = a_all_cookies[i].split( '=' );
		    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		    if ( cookie_name == check_name )
		    {
			    b_cookie_found = true;
			    if ( a_temp_cookie.length > 1 )
				    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			    return cookie_value;
			    break;
		    }
		    a_temp_cookie = null;
		    cookie_name = '';
	    }
	    if ( !b_cookie_found )
		    return null;
	}
    catch(ex)
    {
        raiseError("Error in Get_Cookie:"+ex.description);
    }
}

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
    try
    {
        var today = new Date();
        today.setTime( today.getTime() );

        if ( expires )
            expires = expires * 1000 * 60 * 60 * 24;
        var expires_date = new Date( today.getTime() + (expires) );

        document.cookie = name + "=" +escape( value ) +
                ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
                ( ( path ) ? ";path=" + path : "" ) + 
                ( ( domain ) ? ";domain=" + domain : "" ) +
                ( ( secure ) ? ";secure" : "" );
    }
    catch(ex)
    {
        raiseError("Error in Set_Cookie:"+ex.description);
    }
}

function Delete_Cookie( name, path, domain )
{
    try
    {
        if ( Get_Cookie( name ) )
            document.cookie = name + "=" + 
            ( ( path ) ? ";path=" + path : "") +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
    catch(ex)
    {
        raiseError("Error in Delete_Cookie:"+ex.description);
    }
}

/* search on load */
function getArgs()
{ 
    try
    {
        var args = new Object(); 
        var query = location.search.substring(1); 
        var pairs = query.split("&"); 
        for(var i = 0; i < pairs.length; i++)
        { 
            var pos = pairs[i].indexOf('='); 
            if (pos == -1) continue; 
            var argname = pairs[i].substring(0,pos); 
            var value = pairs[i].substring(pos+1); 
            args[argname] = unescape(value); 
        } 
        return args; 
    }
    catch(ex)
    {
        raiseError("Error in getArgs:"+ex.description);
    }
} 

/* MRU */
var MRULENGTH = 6;
function addRecentlyViewed(itemID)
{
    try
    {
        var cookie = Get_Cookie('MRU');
        if (!cookie)
            cookie = "";
        var MRU = cookie.split(',');
        var newMRU = itemID+',';
        var added = 1;
        var i = 0;
        while(i < MRU.length && added < MRULENGTH)
        {
            if (itemID!=MRU[i] && MRU[i]!="")
            {
                newMRU += MRU[i] + ',';
                added++;
            }
            i++;
        }
        Set_Cookie('MRU',newMRU,30,'/',null,null);
    }
    catch(ex)
    {
        raiseError("Error in addRecentlyViewed:"+ex.description);
    }
}

var _lastMRU = "";
function updateRecentlyViewed()
{
    try
    {
        if ($('#MRU').length > 0)
        {
            if (_lastMRU == Get_Cookie('MRU'))
            {
                if (divJS["MRU"]!="")
                    eval(divJS["MRU"]);
                return;
            }
            //$('#MRU').html();
            _searchParams["MRU"] = { SearchType:"MRU", MRU: Get_Cookie('MRU') };
            InitSearch("MRU",$('#MRU'));
        }
    }
    catch(ex)
    {
        raiseError("Error in updateRecentlyViewed:"+ex.description);
    }
}

/* shortlist */
function addToShortlist(itemID)
{
    try
    {
        var cookie = Get_Cookie('Shortlist');
        if (!cookie)
            cookie = "";
        var Shortlist = cookie.split(',');
        var newSL = itemID+',';
        var i = 0;
        var bFound = false;
        while(i < Shortlist.length)
        {
            if (itemID==Shortlist[i])
                bFound = true;
            else if (Shortlist[i]!="")
                newSL += Shortlist[i] + ',';
            i++;
        }
        Set_Cookie('Shortlist',newSL,365,'/',null,null);
        updateShortlistCount();
        try
        {
            if (!bFound)
                showShortlist();
            else
                $('div.load-ajax').hide();
        }
        catch(ex)
        { }
    }
    catch(ex)
    {
        raiseError("Error in addToShortlist:"+ex.description);
    }
}

function removeFromShortlist(itemID)
{
    try
    {
        var cookie = Get_Cookie('Shortlist');
        if (!cookie)
            cookie = "";
        var Shortlist = cookie.split(',');
        var newSL = "";
        var i = 0;
        while(i < Shortlist.length)
        {
            if (itemID!=Shortlist[i] && Shortlist[i]!="")
                newSL += Shortlist[i] + ',';
            i++;
        }
        Set_Cookie('Shortlist',newSL,365,'/',null,null);
        updateShortlistCount();
        try
        {
            showShortlist();
        }
        catch(ex)
        { }
    }
    catch(ex)
    {
        raiseError("Error in removeFromShortlist:"+ex.description);
    }
}

function isShortlisted(item)
{
    try
    {
        var cookie = Get_Cookie('Shortlist');
        if (!cookie)
            cookie = "";
        var Shortlist = cookie.split(',');
        var i = 0;
        while(i < Shortlist.length)
            if (item==Shortlist[i++])
                return true;
        return false;
    }
    catch(ex)
    {
        raiseError("Error in isShortlisted:"+ex.description);
    }
}

function clearShortlist()
{
    try
    {
        var answer = confirm("Are you sure you want to clear your shortlist?");
        if (answer)
        {    
            Set_Cookie('Shortlist','',365,'/',null,null);
            updateShortlistCount();
            try
            {
                $('div.load-ajax').show();
                showShortlist();
            }
            catch(ex)
            { }
        }
    }
    catch(ex)
    {
        raiseError("Error in removeFromShortlist:"+ex.description);
    }
}

function updateShortlistCount()
{
    try
    {
        if ($('.shortlistcount').length>0)
        {
            var cookie = Get_Cookie('Shortlist');
            if (!cookie)
                cookie = "";
            var Shortlist = cookie.split(',');  
            var scount = 0;
            for(var i = 0; i < Shortlist.length; i++)
                  if (Shortlist[i]!="")
                    scount++;
            $('.shortlistcount').html(""+scount);
        }
    }
    catch(ex)
    {
        raiseError("Error in updateShortlistCount:"+ex.description);
    }
}

function shortlist_click(btn,shortlistcode) {
    $('div.load-ajax').show();
    if ($(btn).parent().hasClass('add-shortlist'))
    {        
        addToShortlist(shortlistcode);
        $(btn).parent().removeClass('add-shortlist').addClass('remove-shortlist');
        $(btn).attr('title','Remove from Shortlist').html('Remove from Shortlist');
    }
    else
    {
        removeFromShortlist(shortlistcode);
        $(btn).parent().removeClass('remove-shortlist').addClass('add-shortlist');
        $(btn).attr('title','Add to Shortlist').html('Add to Shortlist');    
    }
    return false;
};

$(document).ready(function(){updateShortlistCount();});

/* other widgets */

function shareLink(link)
{
    prompt("Copy the link below to access this chalet directly:",link);
}

function fbs_click(u,t) {
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&amp;t='+encodeURIComponent(t),'facebook','width=626,height=436');
    return false;
    }
function delicious_click(u,t) {
    window.open('http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(u)+'&amp;title='+encodeURIComponent(t), 'delicious');
    }
function digg_click(u,t) {
    window.open('http://digg.com/submit?url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t)+'&bodytext='+encodeURIComponent(t)+'&media=news&topic=travel_places', 'digg');
    }
function stumble_click(u,t) {
    window.open('http://www.stumbleupon.com/submit?url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t), 'stumble');
    }
function elink_click(o,u,t) {
    $('#spnElinkTitle').html(t);
    $('#txtElinkObject').val(o);
    $('#txtElinkName').val(t);
    $('#txtElinkURL').val(u);
    var value = Get_Cookie('UserFriendsEmail');
    if (value)
        $('#txtElinkTo').val(value)
    value = Get_Cookie('UserName');
    if (value)
        $('#txtElinkFromName').val(value)
    value = Get_Cookie('UserEmail');
    if (value)
        $('#txtElinkFromEmail').val(value)
    }

function getCaptcha()
{    
    var img = new Image();
    $(img).load(function () {$(this).hide();
                            $('#spnCaptcha').html('').append(this);
                            $(this).fadeIn();})
            .attr('src', '/CaptchaImage.aspx?id='+Math.random());
}
    
function sendEmailLink()
{
    try
    {
        var blanks="";
        var filter=/^.+@.+\..{2,3}$/;
        var emailinvalid=!filter.test($('#txtElinkFromEmail').val()) && ($('#txtElinkFromEmail').val()!="");
        var email2invalid = false;
        
        var toemailstr = $('#txtElinkTo').val();
        if (toemailstr.length > 0)
        {
            var toemails = toemailstr.split(',');
            for(var i = 0; i < toemails.length; i++)
                if (!filter.test(toemails[i]))
                    email2invalid = true;
        }
        blanks = $('#txtElinkTo').val()=="" ? "To" : "";
        blanks += $('#txtElinkFromName').val()=="" ? (blanks==""?"":", ") + "Your Name" : "";
        blanks += $('#txtElinkFromEmail').val()=="" ? (blanks==""?"":", ") + "Your Email" : "";
        blanks += $('#txtElinkMessage').val()=="" ? (blanks==""?"":", ") + "Message" : "";
        blanks += $('#txtElinkCaptchaUser').val()=="" ? (blanks==""?"":", ") + "Verification letters/numbers" : "";
        
        if (blanks!="")
        {
            blanks = "Please complete the following before we send your email:\n" + blanks;
            if (emailinvalid)
                blanks += "\nYour supplied email address also appears to be invalid.\n";
            if (email2invalid)
                blanks += "\nPlease also check the email address(es) you requested the email to be sent to.\n"+
                            "Multiple addresses may be specified by using a comma to separate them.";
            if ($('#enquiryresult').length>0)
                $('#enquiryresult').html(blanks);
            else
                alert(blanks);
        }
        else
        {
            if (emailinvalid || email2invalid)
            {
                var msg = "";
                if (emailinvalid)
                    msg = "Your supplied email address appears to be invalid.\n";
                if (email2invalid)
                    msg += "\nPlease check the email address(es) you requested the email to be sent to.\n"+
                            "Multiple addresses may be specified by using a comma to separate them.";
                if ($('#enquiryresult').length>0)
                    $('#enquiryresult').html(msg);
                else
                    alert(msg);
            }
            else
            {
                Set_Cookie('UserName',$('#txtElinkFromName').val(),365,'/',null,null);
                Set_Cookie('UserEmail',$('#txtElinkFromEmail').val(),365,'/',null,null);
                Set_Cookie('UserFriendsEmail',$('#txtElinkTo').val(),365,'/',null,null);
                var params = {  ObjectType:$('#txtElinkObject').val(),ObjectName:encodeURI($('#txtElinkName').val()),ObjectURL:encodeURI($('#txtElinkURL').val()),
                                EmailTo: encodeURI($('#txtElinkTo').val()), EmailFromName: encodeURI($('#txtElinkFromName').val()),
                                EmailFromEmail: encodeURI($('#txtElinkFromEmail').val()), EmailMessage: encodeURI($('#txtElinkMessage').val()),
                                EmailCaptcha: encodeURI($('#txtElinkCaptchaUser').val())
                                };
                $.post("/SendEmailLink.aspx", params, function(data){sendEmailLinkResult(data);});
            }
        }
    }
    catch(ex)
    {
        raiseError("Error in sendEmailLink:"+ex.description);
        var output="Unfortunately our system is unable to send your email at this time. Please try again or contact us by phone for further assistance.";
        if ($('#enquiryresult').length>0)
            $('#enquiryresult').html(output);
        else
            alert(output);
    }
}

function sendEmailLinkResult(data)
{
    try
    {
        var output="";
        var codearray = data.split("<div class='sectionbreaker' />");
        if (codearray.length == 2)
        {
            if (codearray[0].replace(/^\s+|\s+$/g, '') != "")
            {
                if (codearray[0].indexOf("CAPTCHA") > 0)
                    output = "Please check the letters/numbers identified in the verification image.";
                else if (codearray[0].indexOf("The specified string is not in the form required for an e-mail address") > 0)
                    output = "Please check the To and From email addresses.\nMultiple To addresses may be specified using a comma.";
                else
                    output = "Unfortunately our system is unable to send your email at this time. Please try again or contact us by phone for further assistance.";
                raiseError("Ajax call returned error:"+codearray[0]);
            }
            else
            {
                output = codearray[1];
                $('#txtElinkCaptchaUser').val("");
                tb_remove();
            }
        }
        else
        {
            output = "Unfortunately our system is unable to send your email at this time. Please try again or contact us by phone for further assistance.";
            raiseError("Ajax call failed, result:"+data);
        }
        if ($('#enquiryresult').length>0)
            $('#enquiryresult').html(output);
        else
            alert(output);
    }
    catch(ex)
    {
        raiseError("Error in sendEmailLinkResult:"+ex.description);
        var output="Unfortunately our system is unable to send your email at this time. Please try again or contact us by phone for further assistance.";
        if ($('#enquiryresult').length>0)
            $('#enquiryresult').html(output);
        else
            alert(output);
        tb_remove();
    }
}

/* enquiries */
function Enquire()
{
    try
    {
        var blanks="";
        var filter=/^.+@.+\..{2,3}$/;
        var emailinvalid=!filter.test($('#txtEnqEmail').val()) && ($('#txtEnqEmail').val()!="");
        
        blanks = ($('#ddlEnqDate').length>0 && $('#ddlEnqDate').text()=="") ? "Departure Date" : "";
        blanks += $('#ddlEnqTitle').val()=="" ? (blanks==""?"":", ") + "Title" : "";
        blanks += $('#txtEnqFName').val()=="" ? (blanks==""?"":", ") + "First Name" : "";
        blanks += $('#txtEnqSurname').val()=="" ? (blanks==""?"":", ") + "Surname" : "";
        blanks += $('#txtEnqEmail').val()=="" ? (blanks==""?"":", ") + "Email Address" : "";
        blanks += $('#txtEnqAdults').val()=="" ? (blanks==""?"":", ") + "Number of Adults" : "";

        if (blanks!="")
        {
            blanks = "Please complete the following before submitting your enquiry:\n" + blanks;
            if (emailinvalid)
                blanks += "\nThe email address supplied also appears to be invalid.";
            if ($('#enquiryresult').length>0)
                $('#enquiryresult').html(blanks);
            else
                alert(blanks);
        }
        else
        {
            if (emailinvalid)
            {
                var msg = "Please enter a valid email address before submitting your enquiry.";
                if ($('#enquiryresult').length>0)
                    $('#enquiryresult').html(msg);
                else
                    alert(msg);
            }
            else
            {
                $('#btnEnquire').attr('disabled','disabled');
                var datefield = $('#ddlEnqDate option:selected').text();
                var pricefield = "";
                if (datefield.indexOf('(') != -1 && datefield.indexOf(')') != -1)
                {
                    pricefield = datefield.substring(datefield.indexOf('(')+1,datefield.indexOf(')'));
                    datefield = datefield.substr(0,datefield.indexOf('(')-1);
                }
                var SLinfo = "", SLcodes = "";
                $('div#shortlist').find('.shortlistCodes').each(function(){SLcodes+=(SLcodes==""?"":",")+$(this).val();});
   		        if (SLcodes!="")
		        {
		            $('.shortlistAddInfo').each(function(){SLinfo+=(SLinfo==""?"":",")+$(this).val();});
			        SLinfo="Client's original shortlist (do NOT delete):"+SLinfo;
		        }
                var params = { ChaletID: $('#txtEnqChaletID').val(), ChaletName: $('#txtEnqChaletName').val(), 
                               ChaletSleeps: $('#txtEnqChaletSleeps').val(),
                               CountryName: $('#txtEnqCountryName').val(), ResortName: $('#txtEnqResortName').val(),
                               DeptDate: datefield, Price: pricefield,
                               Adults: $('#txtEnqAdults').val(), Children: $('#txtEnqChildren').val(),
                               ChildrenAges: encodeURI($('#txtEnqChildrenAges').val()), MaxBudget: encodeURI($('#txtEnqMaxBudget').val()), 
                               SimilarChalets: $('#chkEnqOtherChalets:checked').val(), SimilarResorts: $('#chkEnqOtherResorts:checked').val(),
                               NumFlight: $('#ddlEnqFlights').val(), NumTrain: $('#ddlEnqTrains').val(), 
                               NumIndTravel: $('#ddlEnqIndTravel').val(), DepartFrom: $('#ddlEnqDepartFrom').val(), 
                               AddInfo: encodeURI(($('#txtEnqAddInfo').val()==$('#txtEnqAddInfo').attr('title')?"":$('#txtEnqAddInfo').val()))+"\n\n"+encodeURI(SLinfo), 
                               Notes: "", BookReady: $('#ddlEnqReadyToBook').val(), 
                               Title: $('#ddlEnqTitle').val(), FirstName: encodeURI($('#txtEnqFName').val()), Surname: encodeURI($('#txtEnqSurname').val()),
                               Email: encodeURI($('#txtEnqEmail').val()), DPA: $('#chkEnqDPA:checked').val(),
                               WorkPhone: encodeURI(($('#txtEnqWorkPhone').val()==$('#txtEnqWorkPhone').attr('title')?"":$('#txtEnqWorkPhone').val())),
                               HomePhone: encodeURI(($('#txtEnqHomePhone').val()==$('#txtEnqHomePhone').attr('title')?"":$('#txtEnqHomePhone').val())),
                               MobilePhone: encodeURI(($('#txtEnqMobilePhone').val()==$('#txtEnqMobilePhone').attr('title')?"":$('#txtEnqMobilePhone').val())),
                               ShortlistCodes: SLcodes
                                };
                $.post("/Enquire.aspx", params, function(data){EnquiryResult(data);});
            }
        }
    }
    catch(ex)
    {
        raiseError("Error in Enquire:"+ex.description);
        var output="Unfortunately our system is unable to submit your enquiry at this time. Please try again or contact us by phone for further assistance.";
        if ($('#enquiryresult').length>0)
            $('#enquiryresult').html(output);
        else
            alert(output);
        $('#btnEnquire').attr('disabled','');
    }
}

function EnquiryResult(data)
{
    try
    {
        var output="";
        var codearray = data.split("<div class='sectionbreaker' />");
        if (codearray.length == 2)
        {
            if (codearray[0].replace(/^\s+|\s+$/g, '') != "")
            {
                output = "Unfortunately our system is unable to take your enquiry at this time. Please try again or contact us by phone for further assistance.";
                raiseError("Ajax call returned error:"+codearray[0]);
            }
            else
            {
                output = codearray[1];
            }
        }
        else
        {
            output = "Unfortunately our system is unable to take your enquiry at this time. Please try again or contact us by phone for further assistance.";
            raiseError("Ajax call failed, result:"+data);
        }
        if ($('#enquiryresult').length>0)
            $('#enquiryresult').html(output);
        else
            alert(output);
        $('#btnEnquire').attr('disabled','');
    }
    catch(ex)
    {
        raiseError("Error in EnquiryResult:"+ex.description);
        var output="Unfortunately our system is unable to accept your enquiry at this time. Please try again or contact us by phone for further assistance.";
        if ($('#enquiryresult').length>0)
            $('#enquiryresult').html(output);
        else
            alert(output);
        $('#btnEnquire').attr('disabled','');
    }
}


/* matt JS */
$.fn.toggleExtraInfo = function() {
	return this.each(function() {
		if(this.selectedIndex > 0)
			$(this).next('div').slideDown(400);
		else if (this.selectedIndex == 0)
			$(this).next('div').slideUp(400).children('select, textarea, input').clearForm();
		
	});
};

$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = 0;
	});
};

    /* Textfield hints */
jQuery.fn.hint = function() {
	return this.each(function(){
		var t = $(this); // get jQuery version of 'this'
		var title = t.attr('title'); // get it once since it won't change			

		if (title) { // only apply logic if the element has the attribute				

			// on focus, set value to blank if current value matches title attr
			t.focus(function(){
				if (t.val() == title) {
					t.val('');
				 	t.removeClass('blur');
				}
			})

			// on blur, set value to title attr if text is blank
			t.blur(function(){
				if (t.val() == '') {
					t.val(title);
					t.addClass('blur');
				}
			})

			// now change all inputs to title
			t.blur();
		}
	})				
}

function initEnquiryForm()
{
    $('input:text, textarea').hint();
	
    $('select').toggleExtraInfo();
	
    $('select').change(function() {
	    $(this).toggleExtraInfo();
    });
}