var maxDayInMonth = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
//var arrivalDate = new Date(2000, 0, 1);
//arrivalDate.setDate(arrivalDate.getDate() + 1)
//var departureDate = arrivalDate;
//departureDate.setDate(departureDate.getDate() + 1)
var today = new Date();

var currDate = new Date();
var arrivalDate = currDate;
var departureDate = new Date(currDate.getTime()+1*(1000*60*60*24));
var currYear = arrivalDate.getFullYear();

function changeArrivalDate(dateText, inst){
    var myDate = Date.parse(dateText);
    var testArr = dateText.split("-")
    var departureDateStr = (parseInt(testArr[0]) + 1) + "-" + parseInt(testArr[1]) + "-" + testArr[2]
    $("#arrDateHI").val(dateText);
    $("#depDateHI").val(departureDateStr);
    $("#arrivalDt").val(testArr[0]);
    $("#arrivalMn").val(testArr[1]);
    $("#arrivalYr").val(testArr[2]);
    arrivalDate = new Date(testArr[2], parseInt(testArr[1]) - 1, parseInt(testArr[0]));
    if (departureDate <= arrivalDate) {
        departureDate = new Date(testArr[2], parseInt(testArr[1]) - 1, parseInt(testArr[0]) + 1);
        var departureDateStr = departureDate.getDate() + "-" + (departureDate.getMonth() + 1) + "-" + departureDate.getFullYear()
        $('#departureDate').datepicker('option', 'minDate', departureDate);
        //alert (departureDateStr);
        changeDepartureDate(departureDateStr, null);
    }
    else {
        var tempDate = arrivalDate;
        tempDate.setDate(tempDate.getDate() + 1);
        $('#departureDate').datepicker('option', 'minDate', arrivalDate);
    }
    $('#departureDate').datepicker('setDate', departureDate);
}

function changeDepartureDate(dateText, inst){
    var myDate = Date.parse(dateText);
    var testArr = dateText.split("-")
    $("#depDateHI").val(dateText);
    $("#departureDt").val(testArr[0]);
    $("#departureMn").val(testArr[1]);
    $("#departureYr").val(testArr[2]);
    departureDate = new Date(testArr[2], parseInt(testArr[1]) - 1, parseInt(testArr[0]));
}

function checkDates(){
    var dt = $("#dtIn").val();
	var mn = $("#mnIn").val();
	var arrivalDateStr = currYear+""+mn+""+dt;
	//console.log(arrivalDateStr);
	arrivalDate = new Date(currYear, mn-1, dt);
	//console.log(arrivalDate);
	var arrivalDateStrNew = arrivalDate.getFullYear()+""+(arrivalDate.getMonth()+1)+""+arrivalDate.getDate();
	if (arrivalDateStr!=arrivalDateStrNew) {
		arrivalDate.setDate(0);
		//console.log(arrivalDate);
		$("#dtIn").val(arrivalDate.getDate());
	}
	
	if (arrivalDate<currDate) {
		arrivalDate.setFullYear(arrivalDate.getFullYear()+1);
	}
	
	var dt = $("#dtOut").val();
	var mn = $("#mnOut").val();
	var departureDateStr = currYear+""+mn+""+dt;
	//console.log(departureDateStr);
	departureDate = new Date(currYear, mn-1, dt);
	var departureDateStrNew = departureDate.getFullYear()+""+(departureDate.getMonth()+1)+""+departureDate.getDate();
	if (departureDateStr!=departureDateStrNew) {
		//console.log(departureDateStrNew);
		departureDate.setDate(0);
		$("#dtOut").val(departureDate.getDate());
		//$("#mnOut").val(departureDate.getMonth()+1);
	}	

	if (arrivalDate>=departureDate) {
		departureDate.setTime(arrivalDate.getTime()+(1000*60*60*24));
		//console.log(departureDate);
		$("#dtOut").val(departureDate.getDate());
		$("#mnOut").val(departureDate.getMonth()+1);
	}
	
	var datediff = Math.round((departureDate-arrivalDate)/1000/60/60/24);
	if (datediff>30) {
		//console.log(datediff);
		//console.log(arrivalDate.getTime());
		//console.log(arrivalDate.getTime()+30*(1000*60*60*24));
		departureDate.setTime(arrivalDate.getTime()+30*(1000*60*60*24));
		var datediff = Math.round((departureDate-arrivalDate)/1000/60/60/24);
		//departureDate.setTime(arrivalDate.getTime+)
		$("#dtOut").val(departureDate.getDate());
		$("#mnOut").val(departureDate.getMonth()+1);
	}
	
	$("#nbcrs-nn").val(datediff);
	
	//console.log(departureDate);
	//console.log(arrivalDate>=departureDate);
	
	//console.log(departureDate);
	/*
	$("#mnOut option:selected").each(function () {
		str += $(this).val() + " ";
	});
	*/
	//alert(str);
	//$("#text").val(str);
	//console.log(currYear+""+mn+""+dt);
}

function changeDepartureDateTest(){
    var dt = $("#dtIn").val();
	var mn = $("#mnIn").val();
	var arrivalDateStr = currYear+""+mn+""+dt;
	//console.log(arrivalDateStr);
	arrivalDate = new Date(currYear, mn-1, dt);

	var dt = $("#dtOut").val();
	var mn = $("#mnOut").val();
	var departureDateStr = currYear+""+mn+""+dt;
	//console.log(departureDateStr);
	departureDate = new Date(currYear, mn-1, dt);
	var departureDateStrNew = departureDate.getFullYear()+""+(departureDate.getMonth()+1)+""+departureDate.getDate();
	if (departureDateStr!=departureDateStrNew) {
		//console.log(departureDateStrNew);
		departureDate.setDate(0);
		$("#dtOut").val(departureDate.getDate());
		//$("#mnOut").val(departureDate.getMonth()+1);
	}
	if (arrivalDate>=departureDate) {
		departureDate.setDate(arrivalDate.getDate()+1);
		//console.log(departureDate);
		$("#dtOut").val(departureDate.getDate());
		$("#mnOut").val(departureDate.getMonth()+1);
	}
	//console.log(departureDate);
	var datediff = Math.round((departureDate-arrivalDate)/1000/60/60/24);
	if (datediff>30) {
		//console.log(datediff);
		//console.log(arrivalDate.getTime());
		//console.log(arrivalDate.getTime()+30*(1000*60*60*24));
		departureDate.setTime(arrivalDate.getTime()+30*(1000*60*60*24));
		var datediff = Math.round((departureDate-arrivalDate)/1000/60/60/24);
		//departureDate.setTime(arrivalDate.getTime+)
		$("#dtOut").val(departureDate.getDate());
		$("#mnOut").val(departureDate.getMonth()+1);
	}
	
	$("#nbcrs-nn").val(datediff);
	
	//console.log(departureDate);
	$("#mnOut option:selected").each(function () {
		str += $(this).val() + " ";
	});
	//alert(str);
	$("#text").val(str);
	//console.log(currYear+""+mn+""+dt);
}

/*
 function changeArrivalDate(dateText, inst){
 var myDate = Date.parse(dateText);
 var testArr = dateText.split("-")
 var departureDateStr = (parseInt(testArr[0]) + 1) + "-" + parseInt(testArr[1]) + "-" + testArr[2]
 //alert(testArr[1]);
 alert (dateText);
 $("#arrDateHI").val(dateText);
 $("#depDateHI").val(departureDateStr);
 $("#arrivalDt").val(testArr[0]);
 $("#arrivalMn").val(testArr[1]);
 $("#arrivalYr").val(testArr[2]);
 arrivalDate = new Date(testArr[2], parseInt(testArr[1]) - 1, parseInt(testArr[0]));
 if (departureDate <= arrivalDate) {
 departureDate = new Date(testArr[2], parseInt(testArr[1]) - 1, parseInt(testArr[0]) + 1);
 var departureDateStr = departureDate.getDate() + "-" + (departureDate.getMonth() + 1) + "-" + departureDate.getFullYear()
 $('#departureDate').datepicker('option', 'minDate', departureDate);
 //alert (departureDateStr);
 changeDepartureDate(departureDateStr, null);
 }
 else {
 var tempDate = arrivalDate;
 tempDate.setDate(tempDate.getDate() + 1);
 $('#departureDate').datepicker('option', 'minDate', arrivalDate);
 }
 $('#departureDate').datepicker('setDate', departureDate);
 alert ($("#arrDateHI").val());
 }
 function changeDepartureDate(dateText, inst){
 var myDate = Date.parse(dateText);
 var testArr = dateText.split("-")
 //alert(testArr[1]);
 $("#depDateHI").val(dateText);
 $("#departureDt").val(testArr[0]);
 $("#departureMn").val(testArr[1]);
 $("#departureYr").val(testArr[2]);
 departureDate = new Date(testArr[2], parseInt(testArr[1]) - 1, parseInt(testArr[0]));
 //alert (parseInt(testArr[0])+1);
 //alert (new Date(testArr[2], testArr[1], parseInt(testArr[0])+1));
 //$('#departureDate').datepicker('option', 'minDate', new Date(testArr[2], parseInt(testArr[1])-1, parseInt(testArr[0])+1));
 }
 */
function deleteAddService(code){
    var tempAddService = "";
    var answer = confirm(confirmDelAS + ":\n" + $('#' + code).text() + " ?");
    var addService = $('#addService').val().split(', ');
    //    alert(addService.length);
    addService = jQuery.grep(addService, function(a){
        return a != code;
    });
    //    alert(addService.length);
    
    if (answer) {
        switch (addService.length) {
            case 0:
                $('#addService').val('');
                break;
            case 1:
                $('#addService').val(addService[0]);
                break;
            default:
                for (i = 0; i < addService.length - 1; i++) {
                    tempAddService += addService[i] + ", "
                }
                tempAddService += addService[i]
                $('#addService').val(tempAddService);
        }
        submitResForm('book_form', 'nbcrs-bookForm');
        //$('#nbcrs-bookForm').submit();
    }
}


/////////////////
var ln_hash;
/*
 $(document).ready(function() {
 InitProfile();
 });
 */
function checkLastname(){
    var hash = hex_md5($("#r_email").val().toUpperCase() + $("#r_lastName").val().toUpperCase());
    if (jQuery.inArray(hash, ln_hash) != -1) {
        return true;
    }
    else {
        return false;
    }
}

function clearForm(){
    $("#r_firstName").val("");
    $("#lastName").val("");
    $("#email").val("");
    $("#r_email2").val("");
    $("#r_homePhone").val("");
    $("#r_country").val("");
    $("#r_city").val("");
    $("#line1").val("");
    $("#r_postalCode").val("");
    var r_mobilPhone = $("#r_mobilPhone");
    if (r_mobilPhone.length > 0) {
        r_mobilPhone.val("");
    }
}

function InitProfile(){
    var hasData = 0;
    
    //$("#NbPrI-clearButt").click(clearForm);
    
    $("#lastName").focus(function(){
        if (hasData != 1) {
            var request_body = {
                email: $("#email").val()
            };
            //console.log(request_body);
            //$.post(mainEndpoint + "?action=popup&page=profilei", request_body, parseProfile);
            $.post("?action=popup&page=profilei", request_body, parseProfile);
            hasData = 1;
        }
    });
    
    $("#lastName").change(function(){
        if (checkLastname()) {
            //var has_profile = "Данные уже зазружены. Заполнить?";
            var request_body = {
                email: $("#email").val(),
                lastName: $("#lastName").val()
            };
            var answer = confirm(has_profile);
            
            if (answer) {
                $.post("?action=popup&page=profilel", request_body, parseProfile);
            }
        }
    });
    
    var hash = $.cookie("p_hash");
    if (hash != null) {
        var request_body = {
            p_hash: hash
        };
        $.post(mainEndpoint + "?action=popup&page=profilel", request_body, parseProfile);
    }
    return false;
}

function parseProfile(xml){
    if (typeof(xml) == "string") 
        xml = $.parseXML(xml);
    if ($("Response", xml).attr("status") == "isExist") {
        ln_hash = $("r_lastNameHash", xml).text().split(";");
    }
    else 
        if ($("Response", xml).attr("status") == "Success") {
            //alert("test");
            $("#r_firstName").val($("r_firstName", xml).text());
            $("#r_lastName").val($("r_lastName", xml).text());
            $("#r_email").val($("r_email", xml).text());
            //$("#r_email2").val($("r_email", xml).text());
            $("#r_homePhone").val($("r_homePhone", xml).text());
            $("#r_country").val($("r_country", xml).text());
            $("#r_city").val($("r_city", xml).text());
            $("#line1").val($("line1", xml).text());
            $("#r_postalCode").val($("r_postalCode", xml).text());
            var r_mobilPhone = $("#r_mobilPhone");
            if (r_mobilPhone.length > 0) 
                r_mobilPhone.val($("r_mobilPhone", xml).text());
            if ($("#p_remember:checked").val() == "1") {
                var options = {
                    path: '/',
                    expires: 7
                };
                $.cookie("p_hash", $("p_hash", xml).text(), options);
            }
            /*$("#NbPrI-PLoaderError").text("");
         $("#NbPrI-loadedDiv").show();
         $("#NbPrI-LoadProfile").hide();
         $("#NbPrI-loadFormDiv").hide();
         $("#NbPrI-ExitProfile").show();*/
            $("#NbPrI-clearButt").show();
        }
        else {
            $("#NbPrI-clearButt").hide();
        /*$("#NbPrI-LoadProfile").show();		
         $("#NbPrI-ExitProfile").hide();
         $("#NbPrI-loadFormDiv").show();
         $("#NbPrI-PLoaderError").text($("Error", xml).text());*/
        }
}

/*hash*/
var hexcase = 1;
var b64pad = "";
var chrsz = 8;
function hex_md5(s){
    return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}

function b64_md5(s){
    return binl2b64(core_md5(str2binl(s), s.length * chrsz));
}

function str_md5(s){
    return binl2str(core_md5(str2binl(s), s.length * chrsz));
}

function hex_hmac_md5(key, data){
    return binl2hex(core_hmac_md5(key, data));
}

function b64_hmac_md5(key, data){
    return binl2b64(core_hmac_md5(key, data));
}

function str_hmac_md5(key, data){
    return binl2str(core_hmac_md5(key, data));
}

function md5_vm_test(){
    return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

function core_md5(x, len){
    x[len >> 5] |= 0x80 << ((len) % 32);
    x[(((len + 64) >>> 9) << 4) + 14] = len;
    var a = 1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d = 271733878;
    for (var i = 0; i < x.length; i += 16) {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;
        a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
        d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
        c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
        b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
        a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
        d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
        c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
        b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
        a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
        d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
        c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
        b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
        a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
        d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
        c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
        b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
        a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
        d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
        c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
        b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
        a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
        d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
        c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
        b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
        a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
        d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
        c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
        b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
        a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
        d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
        c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
        b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
        a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
        d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
        c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
        b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
        a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
        d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
        c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
        b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
        a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
        d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
        c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
        b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
        a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
        d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
        c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
        b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
        a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
        d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
        c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
        b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
        a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
        d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
        c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
        b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
        a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
        d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
        c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
        b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
        a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
        d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
        c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
        b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
    }
    return Array(a, b, c, d);
}

function md5_cmn(q, a, b, x, s, t){
    return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}

function md5_ff(a, b, c, d, x, s, t){
    return md5_cmn((b & c) | ((~ b) & d), a, b, x, s, t);
}

function md5_gg(a, b, c, d, x, s, t){
    return md5_cmn((b & d) | (c & (~ d)), a, b, x, s, t);
}

function md5_hh(a, b, c, d, x, s, t){
    return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}

function md5_ii(a, b, c, d, x, s, t){
    return md5_cmn(c ^ (b | (~ d)), a, b, x, s, t);
}

function core_hmac_md5(key, data){
    var bkey = str2binl(key);
    if (bkey.length > 16) 
        bkey = core_md5(bkey, key.length * chrsz);
    var ipad = Array(16), opad = Array(16);
    for (var i = 0; i < 16; i++) {
        ipad[i] = bkey[i] ^ 0x36363636;
        opad[i] = bkey[i] ^ 0x5C5C5C5C;
    }
    var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
    return core_md5(opad.concat(hash), 512 + 128);
}

function safe_add(x, y){
    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xFFFF);
}

function bit_rol(num, cnt){
    return (num << cnt) | (num >>> (32 - cnt));
}

function str2binl(str){
    var bin = Array();
    var mask = (1 << chrsz) - 1;
    for (var i = 0; i < str.length * chrsz; i += chrsz) 
        bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
    return bin;
}

function binl2str(bin){
    var str = "";
    var mask = (1 << chrsz) - 1;
    for (var i = 0; i < bin.length * 32; i += chrsz) 
        str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);
    return str;
}

function binl2hex(binarray){
    var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
    var str = "";
    for (var i = 0; i < binarray.length * 4; i++) {
        str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
        hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
    }
    return str;
}

function binl2b64(binarray){
    var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var str = "";
    for (var i = 0; i < binarray.length * 4; i += 3) {
        var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
        for (var j = 0; j < 4; j++) {
            if (i * 8 + j * 6 > binarray.length * 32) 
                str += b64pad;
            else 
                str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
        }
    }
    return str;
}

/////////////////

//$().ready({
//function test(){
$(function(){
	if ($("#nbcrs-smallform").length) {
		$("#dtIn").val(arrivalDate.getDate());
		$("#mnIn").val(arrivalDate.getMonth()+1);
		$("#dtOut").val(departureDate.getDate());
		$("#mnOut").val(departureDate.getMonth()+1);
		$("#dtOut").attr("temp_dtOut","dtOut");
		$("#mnOut").attr("temp_mnOut","mnOut");
		//$("#nightsHolder").hide();
		$("#dtOut").change(changeDepartureDateTest);
		$("#mnOut").change(changeDepartureDateTest);
		$("#dtIn").change(checkDates);
		$("#mnIn").change(checkDates);
		$("#checkOutHolder").show();
	}
	/*
    if ($("#nbcrs-cancelForm").length) {
        var cnlDlgTitle = 'Create an account';
        //alert($("#nbcrs-cancelForm").length);
        $("#nbcrs-cnlbtn").hide();
        $("#nbcrs-showcnldiv").show();
        
        $("#nbcrs-showcnldiv a").click(function(){
            $("#nbcrs-cancelDialog").dialog('open');
            return false;
        });
        
        $("#nbcrs-cnlbtnconf a").click(function(){
			var bValid = false;
            var str = $("input[name=cnlRsn]:checked").val();
            if (str != undefined) {
                if (str == "cnlRsn0") {
                    str = $("#cnlrsnother").val();
					if (str) {
						bValid = true;
					}                    
                }else{
					bValid = true;
				}
            }
            if (bValid) {
				//console.log(str);
				//$("#nbcrs-cancelForm").submit();
			}
            return false;
        });
        
        $("#nbcrs-cnlbtncnl a").click(function(){
            $("#nbcrs-cancelDialog").dialog('close');
            ;
            return false;
        });
        
        $("#nbcrs-cancelDialog").dialog({
            title: cnlDlgTitle,
            bgiframe: true,
            autoOpen: false,
            width: 'auto',
            height: 'auto',
            modal: true
        });
        
        /*
         $('#create-user').click(function(){
         $('#nbcrs-cancelDialog').dialog('open');
         });
         /*
    }
	*/
	if ($("#nbcrs-bookForm").length) {
		$("#nbcrs-bookForm").validate({
			errorElement: "em",
			errorPlacement: function(error, element) {
				error.appendTo( element.parent("p") );
			},
			errorClass: "nbcrs-error",
			rules: {
				lastName: "required",
				firstName: "required",
				address: "required",
				cityc: "required",
				countryc: "required",
				zip: "required",
				email: {
					required: true,
					email: true
				},
				phone: {
					required: true,
					digits: true
				},
				ccType: {
					required: function(element){
						return $("#payType option:selected").val() == 1;
					}
				},
				ccNumber: {
					required: function(element){
						return $("#payType option:selected").val() == 1;
					},
					creditcard: true
				},
				ccExpMonth: {
					required: function(element){
						return $("#payType option:selected").val() == 1;
					}
				},
				ccExpYear: {
					required: function(element){
						return $("#payType option:selected").val() == 1;
					}
				},
				cvvCode: {
					required: function(element){
						return $("#payType option:selected").val() == 1;
					},
					digits: true,
					rangelength: [3, 4]
				},
				ccHolder: {
					required: function(element){
						return $("#payType option:selected").val() == 1;
					}
				},
				acceptPolicy: "required"
			},
			invalidHandler: function(e, validator){
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = errors == 1 ? missed1Field : missedFields.replace("{0}", errors);
					$("div.error span").html(message);
					$("div.error").show();
				}
				else {
					$("div.error").hide();
				}
			},
			messages: {
				acceptPolicy: acceptPolicy
			},
			onkeyup: false,
			debug: true
		});
	}
    
	if ($("#arrivalDate").length) {
		$.datepicker.setDefaults($.extend({
			showMonthAfterYear: false
		}, $.datepicker.regional['ru']));
		$("#arrivalDate").datepicker({
			onSelect: changeArrivalDate,
			dateFormat: 'd-m-yy',
			minDate: 0,
			maxDate: '+1Y -1D',
			changeMonth: true,
			changeYear: true
		
		});
		$('#departureDate').datepicker({
			onSelect: changeDepartureDate,
			defaultDate: +1,
			dateFormat: 'd-m-yy',
			minDate: +1,
			maxDate: '+1Y -1D',
			changeMonth: true,
			changeYear: true
		});
		//$("#departureDt").val(departureDate.getDate());
		$("#arrivalDt").change(checkArrival);
		$("#arrivalMn").change(checkArrival);
		$("#arrivalYr").change(checkArrival);
		$("#departureDt").change(checkDeparture);
		$("#departureMn").change(checkDeparture);
		$("#departureYr").change(checkDeparture);
		$("#submitLink").click(function(){
			$("#searchForm").submit();
			return false;
		});
	}
    
	if ($('a.nbcrs-tooltipFull').length) {
		$('a.nbcrs-tooltipFull').tooltip({
			bodyHandler: function(){
				return $($(this).attr("href")).html();
			},
			showURL: false
		});
	}
    //InitProfile();
    
});
function checkArrival(){
    var arrivalDtSel = $("#arrivalDt")[0];
    var arrivalMnSel = $("#arrivalMn")[0];
    var arrivalYrSel = $("#arrivalYr")[0];
    var arrivalYr = $("#arrivalYr").val();
    var arrivalMn = parseInt($("#arrivalMn").val()) - 1;
    var arrivalDt = $("#arrivalDt").val();
    var today = new Date();
    var lastDate = new Date();
    lastDate.setFullYear(lastDate.getFullYear() + 1);
    lastDate.setDate(lastDate.getDate() - 2);
    
    arrivalDate = new Date(arrivalYr, arrivalMn, arrivalDt);
    //alert(arrivalDate);
    if (arrivalDate.getMonth() != arrivalMn) {
        arrivalDate = new Date(arrivalYr, arrivalMn + 1, 1);
        arrivalDate.setDate(arrivalDate.getDate() - 1);
    }
    if (arrivalDate < today) {
        arrivalDate = today;
    }
    if (arrivalDate > lastDate) {
        arrivalDate = lastDate;
    }
    
    
    arrivalDtSel.options.selectedIndex = arrivalDate.getDate() - 1;
    arrivalMnSel.options.selectedIndex = arrivalDate.getMonth();
    //	arrivalYrSel.options.selectedIndex = arrivalDate.getFullYear()-1;
    $('#arrivalDate').datepicker('setDate', arrivalDate);
    //alert(arrivalDate);
    if (departureDate <= arrivalDate) {
        departureDate = arrivalDate;
        departureDate.setDate(arrivalDate.getDate() + 1);
        var departureDateStr = departureDate.getDate() + "-" + (departureDate.getMonth() + 1) + "-" + departureDate.getFullYear();
        $('#departureDate').datepicker('option', 'minDate', departureDate);
        changeDepartureDate(departureDateStr, null);
    }
    else {
        var tempDate = arrivalDate;
        tempDate.setDate(tempDate.getDate() + 1);
        $('#departureDate').datepicker('option', 'minDate', arrivalDate);
    }
    $('#departureDate').datepicker('setDate', departureDate);
};

function checkDeparture(){
    var departureDtSel = $("#departureDt")[0];
    var departureMnSel = $("#departureMn")[0];
    var dateYr = $("#departureYr").val();
    var dateMn = parseInt($("#departureMn").val()) - 1;
    var dateDt = $("#departureDt").val();
    var today = new Date();
    var lastDate = new Date();
    lastDate.setFullYear(lastDate.getFullYear() + 1);
    lastDate.setDate(lastDate.getDate() - 1);
    
    departureDate = new Date(dateYr, dateMn, dateDt);
    //alert(departureDate);
    if (departureDate.getMonth() != dateMn) {
        departureDate = new Date(dateYr, dateMn + 1, 1);
        departureDate.setDate(departureDate.getDate() - 1);
    }
    if (departureDate <= arrivalDate) {
        departureDate = arrivalDate;
        departureDate.setDate(arrivalDate.getDate() + 1);
    }
    if (departureDate > lastDate) {
        departureDate = lastDate;
    }
    
    
    departureDtSel.options.selectedIndex = departureDate.getDate() - 1;
    departureMnSel.options.selectedIndex = departureDate.getMonth();
    //	arrivalYrSel.options.selectedIndex = arrivalDate.getFullYear()-1;
    $('#departureDate').datepicker('setDate', departureDate);
    //alert(departureDate);
};

function trueDate(dateDt, dateMn, dateYr){
    var date = new Date(dateYr, dateMn, dateDt);
    if (date.getMonth() != dateMn) {
        return false;
    }
    return true;
}

function showRatePlanAddInfo(id){
    if ($('#' + id).is(':visible')) {
        $('#' + id).hide();
    }
    else {
        $('#' + id).show();
    }
    return false;
}


function submitResForm(action, formId){
    /*
     *function submitResForm(action, formId, clearUrl){
     if (!clearUrl) {
     var clearUrl = false;
     }
     */
    var actionFm = document.getElementById(formId).action;
    switch (action) {
        case 'add_service':
            actionFm = actionFm.replace("{2}", "add_service");
            break;
        case 'price':
            actionFm = actionFm.replace("{2}", "price");
            break;
        case 'book_form':
            actionFm = actionFm.replace("{2}", "book_form");
            break;
        case 'check_book_form':
            actionFm = actionFm.replace("{2}", "book_form");
            actionFm = actionFm.concat("&sub_action=check_book_form")
            break;
        case 'book_room':
            actionFm = actionFm.replace("{2}", "book_room");
            break;
        default:
            actionFm = actionFm.replace("{2}", "");
    }
    document.getElementById(formId).action = actionFm;
    
    //    if ($("#nbcrs-bookForm").valid()) {
    document.getElementById(formId).submit();
    //    }
}

function checkResForm(action, formId){
    if ($("#nbcrs-bookForm").valid()) {
        submitResForm('check_book_form', formId);
        //$("#nbcrs-bookForm").submit();
    }
}