$$defaults = {'destination': 'destination:1', 'arrival': 0, 'departure':0, 'price': 'price:50-3000+','sleeps':'sleeps:3'};

$(document).ready( function() {

    function runAjaxSearch(loc) {
        d = new Date();
        $('#search-results')
        .html('<div class="span-24"><div class="loading"><p>Loading search results...</p></div></div>')
        .load('/search/ajax/'+d.getTime()+'/'+loc,
            function(data) {

                $('#search-results ul li:first-child').addClass('first-child');
                if(typeof iframeResizePipe == 'function') {
                    
                    iframeResizePipe();
                   
                }
                //_typeface_js.renderDocument();
            });
    }


    if(window.location.href.match(/\.[a-z]{1,4}\/search\/?/)) {
        loc = window.location.hash.substr(2);

        opts = loc.match(/\/([^\:][^\/]+)/g);
        
        if(opts) {

            var str = $$defaults;
            len = opts.length;
            for(i=0;i<len;i++) {

                p = opts[i].substr(1);

                if(p) {
                    p=p.split(':');
                    if(p[1]) {
                        str[p[0]]=opts[i];
                    }

                    if (p[0]) {

                        if(p[0]=='price' && p[1].indexOf('-')>-1) {
                            o = p[1].split('-');
                            $("#input-price-lo").val(o[0]);
                            $("#input-price-hi").val(o[1]);

                        } else if(p[0]=='arrival'|| p[0]=='departure') {
                            $('#input-'+p[0]).val(p[1]);
                            $d = new Date(p[1]*1000);
                            $('#'+p[0]).val(datestring($d));

                        } else {
                            q = $('#input-'+p[0]);
                            if(q) q.val(p[1]);

                        }
                    }
                }

            }
            $$defaults = str;

            runAjaxSearch(loc);
        }
    }


    var now = new Date();
    mon = ['01','02','03','04','05','06','07','08','09','10','11','12'];

datepicker = {
	format:'b d, Y',
	date: $('#input-arrival').val() ? new Date( $('#input-arrival').val() *1000): '',
        current: now,
        starts: 0,
        //mode: 'range',
        onShow: function(el) {
            $(el).find('.datepickerSelected a').trigger('focus');
        },
	onChange: function(formatted, dates, el, dblclick) {
           /* if(formatted[0]==formatted[1]) {
                if(dblclick) {
                    // set the field to the value we double-clicked
                    $(this).val(formatted[0]);
                    $(this).trigger('change');
                    $(this).DatePickerHide();
                }
            } */
            $input = $(this).attr('id');
            $('#input-'+$input).val(dates.valueOf()/1000);
            $(this).val(formatted);
            if($('#input-arrival').val() >= $('#input-departure').val()) {

                $('#input-arrival').val(dates.valueOf()/1000);
                $('#arrival').val(formatted);
                if(typeof $$book_dates == 'undefined') {
                    next_day = dates;
                    next_day.setDate(dates.getDate()+1);
                    $('#input-departure').val(next_day.valueOf()/1000);
                    $('#departure').val(datestring(next_day));
                } else {
                    //$d=dates;
                    $d=Date.parse(dates);
                    $add=0;
                    for(i=0;i<$$book_dates.count.nights;i++) {
                        if(( ($d > $$book_dates.nights[i][0]) && ($d < $$book_dates.nights[i][1]) ) ) {
                           $add= $$book_dates.nights[i][2];
                           break;
                        }
                    }
                    $d=$d+(86400000*$add);
                    $d = new Date($d);


                    $('#input-departure').val($d.valueOf()/1000);
                    $('#departure').val(datestring($d));
                }
            }

            $(this).trigger('change');
            $(this).DatePickerHide();
            return true;
	},
        calendars : 2

};

preventDefault = function(e) {
    e.preventDefault();
}
dp1 = $('#arrival').keypress(preventDefault).focus(function(){$(this).trigger('click');}).DatePicker($.extend({},datepicker,{
    onBeforeShow: function(){
        $(this).DatePickerSetDate( new Date($('#input-arrival').val()*1000), true);
    },
    onRender: function(date) {
            $disabled=(date.valueOf() < now.valueOf());
            $className='';
            if(!$disabled && (typeof $$book_dates != 'undefined')) {
                $d = date.valueOf();
                
                $morning=$d ;//+ (11*60*1000);
                $evening=$d + 86400000;//+ (15*60*1000);

                // verify turn day
                day = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday'];
                for(i=0;i<$$book_dates.count.turnday;i++) {
                    if(( ($evening > $$book_dates.turnday[i][0]) && ($evening < $$book_dates.turnday[i][1]) ) ) {
                        td=new Date($d-86400000);
                        $$td = td.getDay();

                        //if($$td==0) $$td=7;
                        if($$td!=$$book_dates.turnday[i][2]) {
                            $disabled=true;
                            $className='invalid-check-in';
                            //console.log('disabling '+ date +"("+$$td+")");
                            //alert("You must check in on a "+day[$$book_dates.turnday[i][2]]+" for the dates you have selected.");
                            break;
                        }
                    }
                }

                for(i=0;i<$$book_dates.count.exclude;i++) {
                    if(( ($morning > $$book_dates.exclude[i][1]) || ($evening < $$book_dates.exclude[i][0]) ) ) {
                        //if(($$book_dates.exclude[i][0]-$evening ) < 86400000 && ($$book_dates.exclude[i][0]-$morning ) > 0) {
                        //  $className += 'bottom-scratch ';
                       // }
                       //console.log(date + ' -- ' + $$book_dates.exclude[i][1]);
                    } else {
                        if(($$book_dates.exclude[i][1] -$morning) < 86400000) {
                          $className += 'bottom-scratch';
                          $disabled = 2;
                        } else if (($evening - $$book_dates.exclude[i][0]) <86400000) {
                          $className += 'bottom-scratch';
                          //$disabled = true;
                        } else {
                            $disabled = 2;
                        }
                        //break; // we can't break anymore in case another booking intersects
                    }
                }
            }
            return {
                disabled: $disabled > 0 ? true : false,
                className: $disabled==2 ? 'scratch' : $className
            }

        }
}));
$d1=0;
$('#departure').keypress(preventDefault).focus(function(){$(this).trigger('click');}).DatePicker($.extend({},datepicker,{
        onBeforeShow: function(){
            $d1=$('#input-arrival').val();
            $('#departure').DatePickerRender();
            $(this).DatePickerSetDate( new Date($('#input-departure').val()*1000), true);
	},
        onRender: function(date) {
            $disabled=(date.valueOf() < now.valueOf());
            $className='';
            if(!$disabled && (typeof $$book_dates != 'undefined')) {
                $d = date.valueOf();
                   //     console.log('Date: ' + date);
                $morning=$d ;//+ (11*60*1000);
                $evening=$d +86400000;//+ (15*60*1000);
                if(date<$d1) $disabled=true;
                for(i=0;i<$$book_dates.count.nights;i++) {
                    if(( ($d > $$book_dates.nights[i][0]) && ($d < $$book_dates.nights[i][1]) ) ) {
                        if( Math.ceil( ($evening-$d1)/86400000)-1 < $$book_dates.nights[i][2]) {
                            $disabled=true;
                            break;
                        }
                    }
                }
                for(i=0;i<$$book_dates.count.exclude;i++) {
                    if(( ($morning > $$book_dates.exclude[i][1]) || ($evening < $$book_dates.exclude[i][0]) ) ) {
                        //if(($$book_dates.exclude[i][0]-$evening ) < 86400000 && ($$book_dates.exclude[i][0]-$morning ) > 0) {
                        //  $className += 'bottom-scratch ';
                       // }
                    } else {
                        //console.log(new Date($$book_dates.exclude[i][1]));

                        if(($$book_dates.exclude[i][1] -$morning) < 86400000) {
                          $className += 'top-scratch';
                          $disabled = 2;
                        } else if (($evening - $$book_dates.exclude[i][0]) <86400000) {
                          $className += 'bottom-scratch';
                          //$disabled = true;
                        } else {
                            $disabled = 2;
                        }
                        //break; // we can't break anymore in case another booking intersects
                    }
                }
            }
            return {
                disabled: $disabled,
                className: $disabled==2 ? 'scratch' : $className
            }

        }
}));

/*
 * Load in the required/optional parameters
 */

$req = $('.input-required');
$opt = $('.input-optional');

if($req && (r=$req.val())){
    rp = r.split('+');
    $('#required-list a[rev='+rp.join('],#required-list a[rev=')+']').addClass('in');
    //$('input[name=required[]][type=checkbox][value='+rp.join('],input[name=required[]][type=checkbox][value=')+']').attr('checked','checked');
}

if($opt && (r=$opt.val())){
    rp = r.split('+');
    $('#optional-list a[rev='+rp.join('],#optional-list a[rev=')+']').addClass('in');
    //$('input[name=optional[]][type=checkbox][value='+rp.join('],input[name=optional[]][type=checkbox][value=')+']').attr('checked','checked');
}



$('.select')

/**
 * We have to add the click and focus events for Webkit/Chrome,
 * since there is still an open bug with :focus.
 */
.each( function() {
    t=$(this);
    i = $('input[name='+t.attr('rev')+']');
    if ( i &&  (i=i.val()) ) {
        l = t.find('[title='+i+']');
        if( l &&  (l=l.text()) ) {
            t.find('b').text(l);
        }
    }
})
.focus(function(e){
    val = $('input[name='+$(this).attr('rev')+']').val();
    selected = $(this).find('li[title='+val+']');
    //console.log(selected.attr('title'));
    if(selected == null) {
        selected = $(this).find('li:first');
    }
    selected.trigger('mouseover');
    e.stopImmediatePropagation();
})
.keypress(function(e){
    if(e.keyCode==9) { // tab
        $(this).trigger('blur');
    } else {
        e.stopImmediatePropagation();
        if(e.keyCode==40) {        // down
            $(this).find('li[class=hover]').next().trigger('mouseover');
        } else if(e.keyCode==38){   // up
            $(this).find('li[class=hover]').prev().trigger('mouseover');
        } else if(e.keyCode==13){ // enter
            $(this).find('li[class=hover]').trigger('mouseup');
        } else if(e.keyCode==27){ // escape
            $(this).trigger('blur');
        }
    }
})
.keydown(function(e){
    e.preventDefault();
})
.click(function(){return false;})
.mousemove(function(){return false;})
.mousedown(
    function(){
        focused=$(this);
        $(this).trigger('focus');
        focused.addClass('focus');
        $(document).one('click', function(){
            focused.trigger('blur');
        })
        return false;
    })
.blur(
    function(){
        $(this).removeClass('focus');
    })
/**
 * When we select an 'option' go ahead and send it back to the
 * display area and set the form element to that value.
 */
.find('li')
    .mouseup(
        function(){
            $('input[name='+
                $(this).parents('a').blur()
                    .find('b').html($(this).html()).end()
                .attr('rev')
              +']').val($(this).attr('title')).trigger('change');
          return false;
        })
    .hover(
        function(){
            $(this).siblings().removeClass('hover');
            $(this).addClass('hover');
        },
        function(){
            $(this).removeClass('hover');
        }
    );




$('#search-form,#widget_basicSearch').submit(function(e){
    e.preventDefault();
    $(this).trigger('beforeSubmit');

    str = $$defaults;
    var cook = {'destination': $('#input-destination').val(),
                'm':$('#input-m').val(),
                'arrival' : $('#input-arrival').val(),
                'departure':$('#input-departure').val(),
                'sleeps':$('#input-sleeps').val(),
                'price':0,
                'required':0
                };

    if($('#input-price-lo').length != 0) {
        cook.price=$('#input-price-lo').val()+'-'+$('#input-price-hi').val();
    }
    if($('#required').length != 0) {
        cook.required=$('#required').val();
    }
    for (i in cook) {
        if(cook[i]) {
            str[i]=i+":"+cook[i].replace(/\//g,'-');
        } else {
            str[i]='';
        }
    }
    var loc = '';
    for(i in str) {
        if(str[i]) {
            loc += str[i] + '/';
        }
    }

    /*d = new Date();
    d = new Date(d.getTime() + (8*7*86400000));
    document.cookie = 'arrival='+cook.arrival+';expires '+d.toGMTString()+'; path=/';
    document.cookie = 'departure='+cook.departure+';expires '+d.toGMTString()+'; path=/';
    document.cookie = 'sleeps='+cook.sleeps+';expires '+d.toGMTString()+'; path=/';
    */
   
    if(!window.location.href.match(/search/)) {
        window.location = '/search/#!/'+loc;
    } else {
        runAjaxSearch(loc);
        window.location.hash='#!/'+loc;

    }

    return false;
});

$(".when h5").click(function(e){
    $(this).parent().find('input').click();
    return false;
})

return true;
// end onready
});

function datestring($d){if(isNaN($d.getTime()))return ''; m=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; return m[$d.getMonth()]+" "+zerofill($d.getDate(),2)+", "+$d.getFullYear();};
function zerofill(a,b){b-=a.toString().length;if(b>0){return new Array(b+(/\./.test(a)?2:1)).join('0')+a}return a}
// strtotime (string, now)
function strtotime(e,f){var i,match,s,strTmp='',parse='';strTmp=e;strTmp=strTmp.replace(/\s{2,}|^\s|\s$/g,' ');strTmp=strTmp.replace(/[\t\r\n]/g,'');if(strTmp=='now'){return(new Date()).getTime()/1000}else if(!isNaN(parse=Date.parse(strTmp))){return(parse/1000)}else if(f){f=new Date(f*1000)}else{f=new Date()}strTmp=strTmp.toLowerCase();var g={day:{'sun':0,'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6},mon:{'jan':0,'feb':1,'mar':2,'apr':3,'may':4,'jun':5,'jul':6,'aug':7,'sep':8,'oct':9,'nov':10,'dec':11}};var h=function(m){var a=(m[2]&&m[2]=='ago');var b=(b=m[0]=='last'?-1:1)*(a?-1:1);switch(m[0]){case'last':case'next':switch(m[1].substring(0,3)){case'yea':f.setFullYear(f.getFullYear()+b);break;case'mon':f.setMonth(f.getMonth()+b);break;case'wee':f.setDate(f.getDate()+(b*7));break;case'day':f.setDate(f.getDate()+b);break;case'hou':f.setHours(f.getHours()+b);break;case'min':f.setMinutes(f.getMinutes()+b);break;case'sec':f.setSeconds(f.getSeconds()+b);break;default:var c;if(typeof(c=g.day[m[1].substring(0,3)])!='undefined'){var d=c-f.getDay();if(d==0){d=7*b}else if(d>0){if(m[0]=='last'){d-=7}}else{if(m[0]=='next'){d+=7}}f.setDate(f.getDate()+d)}}break;default:if(/\d+/.test(m[0])){b*=parseInt(m[0],10);switch(m[1].substring(0,3)){case'yea':f.setFullYear(f.getFullYear()+b);break;case'mon':f.setMonth(f.getMonth()+b);break;case'wee':f.setDate(f.getDate()+(b*7));break;case'day':f.setDate(f.getDate()+b);break;case'hou':f.setHours(f.getHours()+b);break;case'min':f.setMinutes(f.getMinutes()+b);break;case'sec':f.setSeconds(f.getSeconds()+b);break}}else{return false}break}return true};match=strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);if(match!=null){if(!match[2]){match[2]='00:00:00'}else if(!match[3]){match[2]+=':00'}s=match[1].split(/-/g);for(i in g.mon){if(g.mon[i]==s[1]-1){s[1]=i}}s[0]=parseInt(s[0],10);s[0]=(s[0]>=0&&s[0]<=69)?'20'+(s[0]<10?'0'+s[0]:s[0]+''):(s[0]>=70&&s[0]<=99)?'19'+s[0]:s[0]+'';return parseInt(this.strtotime(s[2]+' '+s[1]+' '+s[0]+' '+match[2])+(match[4]?match[4]/1000:''),10)}var j='([+-]?\\d+\\s'+'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+'|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+'|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday)'+'|(last|next)\\s'+'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+'|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+'|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday))'+'(\\sago)?';match=strTmp.match(new RegExp(j,'gi'));if(match==null){return false}for(i=0;i<match.length;i++){if(!h(match[i].split(' '))){return false}}return(f.getTime()/1000)}
