// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

jQuery.ajaxSetup({
    'beforeSend': function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript")
    }
})

function callPreview(path) {
    window.open(path,'sharer','menubar=1,toolbar=0,scrollbars=1,status=0,width=800,height=800');
};
        
$(document).ajaxSend(function(event, request, settings) {
    if (typeof(AUTH_TOKEN) == "undefined") return;
    // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
    settings.data = settings.data || "";
    settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

function addNewCampaign(path){
    jQuery.post(path, null, null, "script");
}

jQuery.fn.submitWithAjax = function(){
    $(this).submit(function(){
        $.post($(this).$('#' + visCnt)("action"), $(this).serialize(), null, "script");
        return false;
    });
}

function destroyWithAjax(path){
    jQuery.post(path, {
        _method:"delete"
    }, null, "script");
}

function addRentalSeason(e, season){
    for(i=2;i<5;i++){
        if(!jQuery('#' + season + '_' + i).length){
            var html = '<tr class="li--42" id="' + season + '_' + i + '"> <th class="first_cell field"><label><span>' + season.substring(0,1).toUpperCase() + season.substring(1, season.length) + ' Season:</span></label></th> <td> <input id="" name="rental_season[][season]" type="hidden" value="' + season + '" /> <input id="" name="rental_season[][position]" type="hidden" value="' + i + '" /> <input class="single datepicker ' + season + '_rental_date_' + i + '" id="' + season + '_start_date_' + i + '" name="rental_season[][start_date]" type="text" onchange="detectDateCollision(this)" /> </td> <td> <input class="single datepicker ' + season + '_rental_date_' + i + '" id="' + season+ '_end_date_' + i + '" name="rental_season[][end_date]" type="text" onchange="detectDateCollision(this)" /> </td> <td> <select class="select_box" id="rental_season__minimum_stay" name="rental_season[][minimum_stay]"><option value="1 night">1 night</option> <option value="2 nights">2 nights</option> <option value="3 nights">3 nights</option> <option value="4 nights">4 nights</option> <option value="5 nights">5 nights</option> <option value="6 nights">6 nights</option> <option value="7 nights">7 nights</option> <option value="8 nights">8 nights</option> <option value="9 nights">9 nights</option> <option value="10 nights">10 nights</option> <option value="11 nights">11 nights</option> <option value="12 nights">12 nights</option> <option value="13 nights">13 nights</option> <option value="2 weeks">2 weeks</option> <option value="3 weeks">3 weeks</option> <option value="4 weeks">4 weeks</option> <option value="8 weeks">8 weeks</option> <option value="3 months">3 months</option> <option value="6 months">6 months</option> <option value="12 months">12 months</option></select> </td> <td> &nbsp; <a href="#" title="" onclick="removeRentalSeason(this); return false;">Remove</a></td> </tr>';
            jQuery(e).parents('tr').after(html);
            jQuery(".datepicker").datepicker({
                dateFormat: 'mm/dd/yy'
            });
            break;
        }
    }
}

function removeRentalSeason(e){
    jQuery(e).parents('tr').remove();
}

function detectDateCollision(element){
    var thisDate = new Date($(element).val());
    var collide = false;
    var invalid = false;
    var compareDate=false;
    var arrValues = [ "mid", "high", "peak" ];
    if($('#normal_start_date').val() != '' && $('#normal_end_date').val() != ''){
        if($('#normal_start_date').val() >= $('#normal_end_date').val()){
            compareDate = true;
        }
    };
    if(!$(element).hasClass('.normal_rental_date')){
        var startDate = new Date($("#normal_start_date").val());
        var endDate = new Date($("#normal_end_date").val());
        if(thisDate <= startDate || thisDate >= endDate){
            invalid = true;
        };
    }

    $.each(arrValues,function(index,season){
        for(i=1;i<=4;i++){
            c = season + '_rental_date_' + i.toString();
            startDate = new Date($("."+c+":eq(0)").val());
            endDate = new Date($("."+c+":eq(1)").val());
            if($("."+c+":eq(0)").val() != '' && $("."+c+":eq(1)").val() != ''){
                if(startDate >= endDate){
                    compareDate = true;
                };
            };
            if(!$(element).hasClass(c) && $("."+c).size() > 1){
                startDate = new Date($("."+c+":eq(0)").val());
                endDate = new Date($("."+c+":eq(1)").val());
                if(startDate != NaN && endDate != NaN){
                    if(thisDate >= startDate && thisDate <= endDate){
                        collide = true;
                    };
                };
                if($("."+c+":eq(0)").val() != '' && $("."+c+":eq(1)").val() != ''){
                    if(startDate >= endDate){
                        compareDate = true;
                    };
                };
            };
        }
    });

    if(invalid){
        alert('Mid, High and Peak seasons should be within Normal range.');
        //$('refresh_link').hide();
        $(element).val("");
    }else if(collide){
        alert('Date collision detected.');
        //$('refresh_link').hide();
        $(element).val("");
    }else if(compareDate){
//TODO: james
//      alert('End Date should be greater than Start Date');
//   $(element).val("");
}
}

function refreshCalendar(calendar_date_display){
    var mid = new Array();
    var high = new Array();
    var peak = new Array();
    $w("mid high peak").each(function(season){
        for(i=1;i<=4;i++){
            c = "." + season + '_rental_date_' + i.toString();
            if($$(c).size() > 1){
                startDate = $$(c)[0].getValue().gsub(/-/, '/');
                endDate = $$(c)[1].getValue().gsub(/-/, '/');
                eval(season + " = " + season + ".concat([{'start_date': startDate, 'end_date': endDate}]);");
            }
        }
    });
    var nstart = $$('.normal_rental_date')[0].getValue().gsub(/-/, '/');
    var nend = $$('.normal_rental_date')[1].getValue().gsub(/-/, '/');
    var normal_season = {
        "start_date":nstart,
        "end_date":nend
    };
    calendar_date_display.normal = normal_season;
    calendar_date_display.mid = mid;
    calendar_date_display.high = high;
    calendar_date_display.peak = peak;
    calendar_date_display.changed = true; // This will disable booking after refresh
    calendar_date_display.refresh();
}

function toggle_recipients_selector() {
    $('#recipients_selector').toggle();
}
(function($){
    $.fn.toggler = function(target){
        return this.each(function(){
            $(this).click(function(){
                $($(this).$('#' + visCnt)('href')).show();
                $(target).hide();
                return false;
            });
        });
    }
})(jQuery)

function developer_access_event() {
    $('#all_access').click(function() {
        if (this.checked) {
            $('.developer_access_select').each(function() {
                this.checked = true;
            });
        }
    });

    $('.contact_select').change(function() {
        $("#access_" + this.getValue).$('#' + visCnt)('checked', true);
    });
	
    $('.developer_access_select').click(function() {
        if (!this.checked)
            $("#all_access").$('#' + visCnt)('checked', false);
    });
}


// tb_remove is a pure copy from the thickbox js lib. For reason unknown calling it doesn't work
// for now just make a copy of it so we can close thickbox manually.
function tb_remove() {
    $("#TB_imageOff").unbind("click");
    $("#TB_closeWindowButton").unbind("click");
    $("#TB_window").fadeOut("fast",function(){
        $('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();
    });
    $("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body","html").css({
            height: "auto",
            width: "auto"
        });
        $("html").css("overflow","");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}


// property media edit
function update_orders(class_name) {
    $('.' + class_name).each(
        function(i) {
            $(this).find('h4').html(i + 1)
        }
        );
}

function update_photo_button(max) {
    if ($('.photo_image').length < max)
        $('#photo_button').show();
    else
        $('#photo_button').hide();
}

function update_plan_button(max) {
    if ($('.plan_image').length < max)
        $('#plan_button').show();
    else
        $('#plan_button').hide();
}

function LimitThis(object_id, evt) {
    evt = (evt) ? evt : (window.event) ? event : null;
    if (evt)
    {
        var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
        if (charCode == 13) {
            if ($('#' + object_id).val().length == $('#' + object_id).attr("maxLength")*1){
                return false;
            }else{
                return true;
            }
        }
    }
}

function CountThis(object_id, visCnt) {
    if ($('#' + object_id).val().length>$('#' + object_id).attr("maxLength")*1) $('#' + object_id).val($('#' + object_id).val().substring(0,$('#' + object_id).attr("maxLength")*1));
    if ($('#' + visCnt)) $('#' + visCnt).html(($('#' + object_id).attr("maxLength")-$('#' + object_id).val().length) + ' remaining');
}


function higlight_in_range(){
    var startDate = null;
    var endDate = null;
    var tempRange = 0;

    if($("#normal_start_date").val() != null && $("#normal_end_date").val() != null){
        var normal_color = "yellow";
        startDate = new Date($("#normal_start_date").val());
        endDate = new Date($("#normal_end_date").val());
        hrange_year(startDate,endDate,normal_color);
    };
 
    for(var c=1;c<=4;c++){
        if($("#mid_start_date_"+c).val() != null && $("#mid_end_date_"+c).val() != null){
            var mid_color = "cyan";
            startDate = new Date($("#mid_start_date_"+c).val());
            endDate = new Date($("#mid_end_date_"+c).val());
            hrange_year(startDate,endDate,mid_color);
        };
        if($("#high_start_date_"+c).val() != null && $("#high_end_date_"+c).val() != null){
            var high_color = "chartreuse";
            startDate = new Date($("#high_start_date_"+c).val());
            endDate = new Date($("#high_end_date_"+c).val());
            hrange_year(startDate,endDate,high_color);
        };
        if($("#peak_start_date_"+c).val() != null && $("#peak_end_date_"+c).val() != null){
            var peak_color = "HotPink";
            startDate = new Date($("#peak_start_date_"+c).val());
            endDate = new Date($("#peak_end_date_"+c).val());
            hrange_year(startDate,endDate,peak_color);
        }
    }


    function hrange_year(startDate,endDate,color){
        var startMonth = null;
        var endMonth = null;
        if(startDate.getYear() < endDate.getYear()){
            for(var y = startDate.getYear();y<=endDate.getYear();y++){
                startMonth = startDate.getMonth();
                endMonth = endDate.getMonth();
                if(startDate.getYear() == y){
                    startDate = new Date(y + 1900,0,1);
                };
                if(endDate.getYear() == y){
                    endMonth = endMonth;
                }else{
                    endMonth = 11;
                }
                hrange_month(y,startDate,endDate,startMonth,endMonth,color);
            };
        }else{
            hrange_month(startDate.getYear(),startDate,endDate,startDate.getMonth(),endDate.getMonth(),color);
        };
    };

    function hrange_month(y,startDate,endDate,startMonth,endMonth,color){
        var range_date= 0;
        if(startDate.getMonth() == endDate.getMonth()){
            hrange_date(y,endDate.getDate() - startDate.getDate()+1,startDate,color);
        };

        if(startDate < endDate){
            var mo = null;
            for(var m = startMonth;m<=endMonth;m++){
                mo = new Date(y + 1900,m,1);
                range_date = mo.getDaysInMonth();
                if(startDate.getMonth() < m){
                    startDate = new Date(y + 1900,m,1);
                };
                if(startDate.getYear() == endDate.getYear()){
                    if(endDate.getMonth() == m){
                        range_date = endDate.getDaysInMonth() - (endDate.getDaysInMonth()-endDate.getDate());
                    }else{
                        startDate = new Date(y + 1900,m,1);
                        range_date = mo.getDaysInMonth();
                    };
                };
                hrange_date(y,range_date, startDate,color);
            };
        }
    };

    function hrange_date(y,range_date,startDate,color){
        var d = null;
        for(var i=startDate.getDate();i<=range_date;i++){
            d = new Date(y + 1900,startDate.getMonth(),i);
            $(".current-month").filter("."+d.asString().split('/').join('')).css("background-color", color).addClass(color);
        }
    }

    function set_temp_range(new_temp_range){
        tempRange = new_temp_range;
    }

    function get_temp_range(){
        return tempRange;
    }

    var unavailable_date = $("#unavailable_date");
    if(unavailable_date.val() != null || unavailable_date.val() != "" || unavailable_date.val() != undefined){
        var date_store = new Array();
        date_store = cleanArray(new String(unavailable_date.val()).split(" "));
        for(var i = 0;date_store.length > i ;i++){
            if(date_store[i] != ""){
                $("#calendar_date_display").find("."+date_store[i]).attr('style','background-color:#CCCCCC;color:#000000;');
            }
        }
        
    }

};


function cleanArray(actual){
    var newArray = new Array();
    for(var i = 0; i<actual.length; i++){
        if (actual[i]){
            newArray.push(actual[i]);
        }
    }
    return newArray;
}