
/////////////////////// Search request ///////////////////
function ClearLast() {

    if ($('lastmemberID')) {
        //if ($('showpage').value != '1') {
        $('lastmemberID').value = '';
        //}
    }
}

function SearchResults() {

    /* ### StopWatch timer ###
    var _StopWatch = new StopWatch();
    _StopWatch.start();
    $('load_time').innerHTML = '';
    */

    Effect.ScrollTo('cottagesearch');

    changeHashValue($('showpage').value);

    var p = $('showpage2').value;

    if ($('showpage').value > parseInt(p) + 1) {
        $('lastmemberID').value = '';
    }

    var data = 'file=results'
    data += '&sleeps=' + escape($('sleeps').value)
    //data += '&bedrooms='+escape($('bedrooms').value)
    data += '&startdate=' + escape($('startdate').value)
    //data += '&enddate='+escape($('enddate').value)	
    data += '&numbernights=' + escape($('numbernights').value)
    data += '&datevar=' + escape($('datevar').value)
    data += '&showpage=' + escape($('showpage').value)
    data += '&variableID=' + escape($('variableID').value)
    data += '&area=' + escape($('region').value)
    data += '&viewmap=' + escape($('viewmap').value)
    data += '&propertyname=' + escape($('propertyname').value)
    data += '&pets=' + escape($('pets').value)
    data += '&childfriendly=' + escape($('childfriendly').value)
    data += '&accessible=' + escape($('accessible').value)
    data += '&largegroups=' + escape($('largegroups').value)
    data += '&internet=' + escape($('internet').value)
    data += '&pool=' + escape($('pool').value)
    data += '&greentourism=' + escape($('greentourism').value)
    data += '&d=0'
    data += '&rnd982g=' + Math.random()

    if ($('lastmemberID')) {
        data += '&lastmemberID=' + escape($('lastmemberID').value)
    }

    // Set cookies
    Set_Cookie('pc_cookie', '1', '', '/', '', '');
    Set_Cookie('pc_sleeps', $('sleeps').value, '', '/', '', '');
    Set_Cookie('pc_bedrooms', $('variableID_chk_5845').value, '', '/', '', '');
    Set_Cookie('pc_startdate', $('startdate').value, '', '/', '', '');
    Set_Cookie('pc_numbernights', $('numbernights').value, '', '/', '', '');
    Set_Cookie('pc_datevar', $('datevar').value, '', '/', '', '');
    Set_Cookie('pc_showpage', $('showpage').value, '', '/', '', '');
    Set_Cookie('pc_variableID', $('variableID').value, '', '/', '', '');
    Set_Cookie('pc_region', $('region').value, '', '/', '', '');
    Set_Cookie('pc_viewmap', $('viewmap').value, '', '/', '', '');
    Set_Cookie('pc_propertyname', $('propertyname').value, '', '/', '', '');
    Set_Cookie('pc_auto_search', $('auto_search').value, '', '/', '', '');

    // New variables
    Set_Cookie('pc_pets', $('pets').value, '', '/', '', '');
    Set_Cookie('pc_childfriendly', $('childfriendly').value, '', '/', '', '');
    Set_Cookie('pc_accessible', $('accessible').value, '', '/', '', '');
    Set_Cookie('pc_largegroups', $('largegroups').value, '', '/', '', '');
    Set_Cookie('pc_internet', $('internet').value, '', '/', '', '');
    Set_Cookie('pc_pool', $('pool').value, '', '/', '', '');
    Set_Cookie('pc_greentourism', $('greentourism').value, '', '/', '', '');

    var ajax = new Ajax.Updater('search_results', '/scavailability/proxy.aspx', {
        method: 'get',
        evalScripts: true,
        parameters: data,
        onLoading: ajaxLoading(),
        onComplete: function() { /* ### StopWatch timer ### _StopWatch.stop(); $('load_time').innerHTML = _StopWatch.duration(); ### */ }
    });
}

/////////////////////// Refine results progress spinner ///////////////////

function ajaxLoading() {
    $('search_button').disabled = true;
    //$('search_results').innerHTML = '<div align="center"><img src="images/ajax-loader.gif" /></div>';
    //popup('popUpDiv');
    $('search_results').innerHTML = '<div id="search-loading"><img src="/scavailability/images/ajax-loader.gif" /><br/><br/>Please wait - searching.</div>';
}

function ajaxLoadingStop() {
    $('search_button').disabled = false;
    //$('search_results').innerHTML = '<div align="center"><img src="images/ajax-loader.gif" /></div>';
    //popup('popUpDiv');
}

/////////////////////// Process Ajax response ///////////////////

function getResponse(oReq) {
    $('search_results').innerHTML = oReq.responseText;
    $('search_button').disabled = false;
    //popup('popUpDiv');
}

/////////////////////// Build the variableID hidden form field ///////////////////

function SearchVariablesOld() {

    var chk_var = '';

    if (document.aspnetForm.variableID_chk.length != undefined) {
        for (var i = 0; i < document.aspnetForm.variableID_chk.length; i++) {
            if (document.aspnetForm.variableID_chk[i].checked) {
                if (chk_var == '') {
                    chk_var = chk_var + document.aspnetForm.variableID_chk[i].value;
                }
                else {
                    chk_var = chk_var + ',' + document.aspnetForm.variableID_chk[i].value;
                }
            }
        }
    }
    else {


        if (document.aspnetForm.variableID_chk.checked) {
            chk_var = chk_var + document.aspnetForm.variableID_chk.value;
        }
    }

    //alert(chk_var);
    $('variableID').value = chk_var;
    $('showpage').value = '1';
}

function SearchVariables() {

    var chk_var = '';

    if ($('oCount')) {

        var i = 0;
        for (i = 0; i <= $('oCount').value; i++) {

            if ($('variableID_chk_' + i)) {

                if ($('variableID_chk_' + i).type == 'checkbox') {

                    if ($('variableID_chk_' + i).checked) {
                        if (chk_var == '') {
                            chk_var += $('variableID_chk_' + i).value;
                        } else {
                            chk_var += ',' + $('variableID_chk_' + i).value;
                        }
                    }
                }
                else {
                    // Select boxes
                    if ($('variableID_chk_' + i).type.match(/select/i)) {
                        objName = $('variableID_chk_' + i).name;
                        if (objName.indexOf("variableID_chk_") != -1) {
                            objName = objName.replace(/variableID_chk_/i, '');
                            objValue = $('variableID_chk_' + i).value;
                            if (objValue != '0') {
                                if (chk_var == '') {
                                    chk_var += objName + '-' + objValue;
                                } else {
                                    chk_var += ',' + objName + '-' + objValue;
                                }
                            }
                        }

                    }

                }

            }

        }
    }

    // Get checkbox values
    //    if (document.aspnetForm != undefined) {
    //		if ($('variableID_chk_0')) {
    //           for (var i = 0; i < document.aspnetForm.variableID_chk.length; i++) {
    //                if (document.aspnetForm.variableID_chk[i].checked) {
    //                    if (chk_var == '') {
    //                        chk_var += document.aspnetForm.variableID_chk[i].value;
    //                    } else {
    //                        chk_var += ',' + document.aspnetForm.variableID_chk[i].value;
    //                    }
    //                }
    //            }
    //        } else {
    //            if (document.aspnetForm.variableID_chk.checked) {
    //                chk_var += document.aspnetForm.variableID_chk.value;
    //            }
    //       }
    //   }

    // Get selectbox values
    // bedrooms in cottage search
    //var bedrooms = document.getElementById('variableID_chk_5845').value;
    //if (bedrooms != '0') {
    //    if (chk_var == '') {
    //        chk_var += '5845' + '-' + bedrooms;
    //    } else {
    //        chk_var += ',5845-' + bedrooms;
    //    }
    //}

    //    if (document.aspnetForm != undefined) {
    //        var control = document.aspnetForm.elements;
    //        for (var i = 0; i < control.length; i++) {
    //            if (control[i].type.match(/select/i)) {
    //                objName = control[i].name;
    //                if (objName.indexOf("variableID_chk_") != -1) {
    //                    objName = objName.replace(/variableID_chk_/i, '');
    //                    objValue = control[i].value;
    //                    if (objValue != '0') {
    //                        if (chk_var == '') {
    //                            chk_var += objName + '-' + objValue;
    //                        } else {
    //                            chk_var += ',' + objName + '-' + objValue;
    //                        }
    //                   }
    //                }
    //            }
    //        }
    //    }

    $('variableID').value = chk_var;
    $('showpage').value = '1';
}

/////////////////////// Search form validation ///////////////////

function validate(theForm) {
    var startDateString = document.searchform.startdate_cal.value;
    var endDateString = document.searchform.enddate_cal.value;

    var startDate = new Date(Date.parse(startDateString.replace(/-/g, ' ')))
    var endDate = new Date(Date.parse(endDateString.replace(/-/g, ' ')))
    var today = new Date();
    today.setHours(0, 0, 0, 0)
    if (startDate < today) {
        alert('Start date cannot be in the past');
        return false;
    }
    if (endDate < today) {
        alert('End date cannot be in the past');
        return false;
    }
    if (startDate > endDate) {
        alert('Start date cannot be greater than end date');
        return false;
    }

    if (startDate == endDate) {
        alert('End date must be greater than start date');
        return false;
    }

    return true
}


/////////////////////// Regions & towns ///////////////////
function ShowChange() {
    $('showchange').value = '1';
}

function UpdateEndDate() {

    var startArray = $('startdate_cal').value.split('-');
    var nights = parseInt($('numbernights').value);

    var day1 = startArray[2];
    var month1 = startArray[1];
    var year1 = startArray[0];

    var d1 = new Date();
    d1.setYear(year1);
    d1.setMonth(month1 - 1);
    d1.setDate(day1);

    d1.setDate(d1.getDate() + nights);

    var month1 = d1.getMonth() + 1;

    var nowStr = d1.getFullYear().toString() + "-" +
    (month1 < 10 ? "0" + month1 : month1) + "-" +
    (d1.getDate() < 10 ? "0" + d1.getDate().toString() : d1.getDate().toString());

    $('enddate_cal').value = nowStr;

}

function UpdateNumberNights() {

    var startArray = $('startdate_cal').value.split('-');

    var startDay = startArray[2];
    var startMonth = startArray[1];
    var startYear = startArray[0];

    var startDate = new Date();
    startDate.setYear(startYear);
    startDate.setMonth(startMonth - 1);
    startDate.setDate(startDay);

    var endArray = $('enddate_cal').value.split('-');

    var endDay = endArray[2];
    var endMonth = endArray[1];
    var endYear = endArray[0];

    var endDate = new Date();
    endDate.setYear(endYear);
    endDate.setMonth(endMonth - 1);
    endDate.setDate(endDay);

    dateDiff = Math.round((endDate - startDate) / (24 * 60 * 60 * 1000))

    $('numbernights').value = dateDiff;

}

// Cookie Functions
/*
Script Name: Javascript Cookie Script
Author: Public Domain, with some modifications
Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.1.2
Last Update: 5 November 2009

Changes:
1.1.2 explicitly declares i in Get_Cookie with var
1.1.1 fixes a problem with Get_Cookie that did not correctly handle case
where cookie is initialized but it has no "=" and thus no value, the 
Get_Cookie function generates a NULL exception. This was pointed out by olivier, thanks
1.1.0 fixes a problem with Get_Cookie that did not correctly handle
cases where multiple cookies might test as the same, like: site1, site
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
*/

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    var i = '';

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());
    // if the expires variable is set, make the correct expires time, the
    // current script below will set it for x number of days, to make it
    // for hours, delete * 24, for minutes, delete * 60 * 24
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
    var expires_date = new Date(today.getTime() + (expires));
    //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

    document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

