//OPL PUBLIC
/* ---------- VARIABLES ---------- */
var TXT_HIDE_DETAILS = 'ukryj szczegóły';
var cl_OK = 'form-input-ok';
var cl_Error = 'form-input-error';
var cl_ErrorInput = 'form-field-error';
var cl_OmitError = 'form-error-omit';

/* ---------- FUNCTIONS ---------- */
function pause(millisecondi) {
	var now = new Date();
	var exitTime = now.getTime() + millisecondi;
	while(true)	{
		now = new Date();
		if (now.getTime() > exitTime) {
			return;
		}
	}
}
function getViewportSize(includeScroll){
    var viewportwidth;
    var viewportheight;
	var scrollwidth = function()
	{
	   var w = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
	   return w ? w : 0;
	};
	var scrollheight = function()
	{
	   var h = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;           
	   return h ? h : 0;
	};
    
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    
    if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth;
		viewportheight = window.innerHeight;
	}
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else {
		if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' &&	document.documentElement.clientWidth !== 0) {
			viewportwidth = document.documentElement.clientWidth;
			viewportheight = document.documentElement.clientHeight;
		}
		// older versions of IE
		else {
			viewportwidth = document.getElementsByTagName('body')[0].clientWidth; 
			viewportheight = document.getElementsByTagName('body')[0].clientHeight;
		}
	}
	return {
		width: (includeScroll) ? viewportwidth + scrollwidth() : viewportwidth,
		height: (includeScroll) ? viewportheight + scrollheight() : viewportheight
	};
}
function getCursorPosition(e){
	var x;
	var y;
	
	if (!e) {
		var e = window.event;
	}
	if (e.pageX || e.pageY) 	{
		x = e.pageX;
		y = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		y = e.clientY + document.body.scrollTop	+ document.documentElement.scrollTop;
	}
	
	return {x:x,y:y};
}
function getJQObjectDimensions(object){
	var offset = object.offset();
	return {x:object.left,y:object.top,width:object.width(),height:object.height()};
}
/**
 * Function for creating a cookie
 * @param {Object} name
 * @param {Object} value
 * @param {Object} days
 */
function createCookie(name,value,time) {
	if (time) {
		var date = new Date();
		date.setTime(date.getTime() + time);
		var expires = "; expires=" + date.toGMTString();
	}
	else {
		var expires = "";
	}
	document.cookie = "esky_"+name+"="+escape(value)+expires+"; path=/";
}
/**
 * Function for reading a cookie.
 * @param {Object} name
 */
function readCookie(name) {
	var nameEQ = "esky_" + name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1, c.length);
		}
		if (c.indexOf(nameEQ) === 0) {
			return unescape(c.substring(nameEQ.length, c.length));
		}
	}
	return null;
}
function eraseCookie(name) {
	createCookie("esky_"+name,"",-1);
}
/**
 * Special function for spliting form element name/id
 * into 2 pieces: name (letters) and number (digits).
 * This function is used by hotels/flights ASF
 */
function splitValue(value) {
	if (typeof value != "string") {
		var value = value.toString();
	}
	var objectName = value.match(/(\.|\#)?[\/\?\.\:=a-z_]+/g);
	var objectId = value.match(/\d+/g);
	return {
		name:objectName,
		id:objectId,
		array:( objectId != parseInt(objectId,10) && objectId !== null )?true:false
	};
}
/**
 * Formating function for autocomplete plugin
 * @param {Object} row
 */
var formatItem = function(row) {
	return "<div class=\"ac_line\"><strong>"+row[4]+"</strong>, "+row[5]+" - "+row[3]+" ("+row[0]+")</div>";
};

var formatItemHotel = function(row) {
	return "<div class=\"ac_line\"><strong>"+row[3]+"</strong>, "+row[4]+" ("+row[0]+")</div>";
};


//javascript equivalent to php function
function substr( f_string, f_start, f_length ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''
 
    f_string += '';
 
    if(f_start < 0) {
        f_start += f_string.length;
    }
 
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
 
    if(f_length < f_start) {
        f_length = f_start;
    }
 
    return f_string.substring(f_start, f_length);
}

/* qsf error */
var cl_Error = 'input_error_class';
var cl_OK = 'input_ok_class';
function toggleClass(o,re){
	var re = new RegExp(re,"i");

	if(re.test(o.val())==false||o.val()=='') {
		o.prev().prev().removeClass(cl_OK);
		o.prev().prev().addClass(cl_Error);
	} else {
		o.prev().prev().removeClass(cl_Error);
		o.prev().prev().addClass(cl_OK);
	}
}

/**
 * Form Validation
 * @param {field} o
 * @param {regexp} re
 * @param {boolean} b
 */
function checkInput(o,re,b){
	$(o).each(function(){
		if(b){
			$(this)
			.change(function(){
				toggleClass($(this),re);
				
			});
		}else{
			toggleClass($(this),re);
		}
	});
}

function checkQSF(b) {
	
		var airports_fields = "";
		
		if ($('#fly_from_0').length == 1) {	
			airports_fields += '#fly_from_0,';
		}
		
		if ($('#fly_to_0').length == 1) {
			airports_fields += '#fly_to_0,';
		}
		
		if ($('#ff0').length == 1) {
			airports_fields += '#ff0,';
		}
		
		if ($('#ft0').length == 1) {
			airports_fields += '#ft0,';
		}
		
		
		var dates_fields = "";
		if ($('#fly_from_date_0').length == 1) {
			dates_fields += '#fly_from_date_0,';
		}
		
		if ($('#fly_to_date_0').length == 1) {
			dates_fields += '#fly_to_date_0,';
		}
		
		if ($('#ffrom').length == 1) {
			dates_fields += '#ffrom,';
		}
		
		if ($('#fto').length == 1) {
			dates_fields += '#fto,';
		}
		
		airports_fields = substr(airports_fields, 0, -1);
		dates_fields = substr(dates_fields, 0, -1);
		
		//alert(checkInput(dates_fields,"^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$",b));
		
		checkInput(airports_fields, "^[A-Z ]{3}", b);
		checkInput(dates_fields, "^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$", b);
}


/**
 * Airport selector for citySelector plugin
 * @param {Object} code
 * @param {Object} field
 */
var selectAirportBack = function(code,field,fieldCode) {
	$('#'+field).unbind('focus').val(code).removeClass('virgin');
	$('#'+field).focus();
	closeCitySelector();
};
/**
 * Little function for closing city selector box
 */

var closeCalendar = function() {
	$('#esky_calendar').empty().remove();
	//$(document).blur();
};
var closeErrorMessage = function() {
	$('#msg-balloon').empty().remove();
	//$(document).blur();
};

/* ---------- DESTINATOR FUNCTIONS ----------- */
var closeDestinator = function() {
	$destinator = $('#destinator');
	if ($destinator.length > 0) {
		$destinator.empty().remove();
	}
};
var setDestination = function(target, value) {
	$('#' + target).attr('value', value).unbind('focus').removeClass('virgin');
	closeDestinator();
};


/* ---------- JQUERY EXTENSIONS ---------- */
jQuery.fn.extend({
	saveQuery: function(formId,days){
		var cookieId = (formId) ? formId : $(this).attr('id');
		var queryString = cookieId;
		$('input[type="text"],input[type="hidden"].hidden,select,input[type="radio"]:checked,input[type="checkbox"]:checked',$(this))
		.not(':disabled').each(function(){
			var val = $(this).val();
			if (typeof val != 'undefined' && val !== '') {
				queryString += '|' + $(this).attr('type') + ':' + $(this).attr('name') + '=' + val;
			}
		});
		createCookie(cookieId,queryString,days);
	},
	loadQuery: function(formId,field){
		var cookieId = (formId) ? formId : $(this).attr('id');
		var cookie = readCookie(cookieId);
		if (cookie) {
			var fields = cookie.split('|');
			for (i in fields) {
				var a = fields[i].split(':');
				if (a[1]) {
					var b = a[1].split('=');
				}
				else {
					continue;
				}
				if (field && field != b[0]) {
					continue;
				}
				switch(a[0]) {
					case 'radio':
					case 'checkbox':
						$('input[@name="' + b[0] + '"][@value="' + b[1] + '"]', $(this)).attr('checked','checked');
						break;
					case 'text':
					case 'hidden':
						$input = $('input[@name="' + b[0] + '"]', $(this));
						$input.val(b[1]);
						if (b[1] != ASF_ENTER_FROM_CITY_NAME && b[1] != ASF_ENTER_TO_CITY_NAME && b[1] != Date.format.toUpperCase() && b[1] != 'RRRR-MM-DD') {
							$input.removeClass('virgin');
						}
						break;
					default:
						$('select[@name="' + b[0] + '"]', $(this)).val(b[1]);
						break;
				}
			}
		}
	},
	/*
	 * DESTINATOR - select destination from flash map
	 */
	destinator: function() {
		$(this).each(function(){
			$(this).unbind().click(function(){
				if ($('#destinator').length > 0) {
					closeDestinator();
					return false;
				}
				var ww = $(window).width();
				//var input = $('#' + $(this).attr('rel'));
				var input = $(this).prev();
				var xy = input.offset();
				var dx = xy.left; //destinator offset x
				if (xy.left > ww/2) { //if QSF is on the right side of the screen, align destinator to right
					dx = (xy.left + input.width() + parseInt(input.css('padding-left'),10)*2 - 711);
				}
		
				$('body').append(
					$('<div></div>')
					.attr('id', 'destinator')
					.css({top: xy.top + input.height() + 8, left: dx})
					.append(
						$('<div></div>')
						.attr('id', 'destinatorContent')
						.append(
							$('<p></p>')
							.html('За да работи картата трябва да имате инсталиран Flash Player 9 – моля свалете от <a href="http://get.adobe.com/flashplayer/" target="_blank">тукh</a>.')
						)
					)
				);

				swfobject.embedSWF(ibeConfig.host + "/swf/destinator_bg.swf", "destinatorContent", "750", "500", "9.0.0", "", {input:$(this).attr('rel'),lang:'BG',selectedContinent:'EU',selectedCountry:'BG'});

				return false;
			});
		});
	},
	tipBox: function(html,width){
		$(this)
		.mouseover(function(e){
			var a = $(this);
			//var xy = a.offset();
			var pos = getCursorPosition(e);

			$('div#custom-field-help').remove();
			$('body').append($('<div></div>')
				.attr('id', 'custom-field-help')
				.css({
					'display':'none',
					'position': 'absolute',
					'left': pos.x + 8,
					'top': pos.y + 8,
					'width':(width)?width:200
				})
				//.load( a.attr('href')+ ' #jqText' )
				.html(html)
				.fadeIn('slow')
			);
			return false;
		})
		.mouseout(function(){
			$('div#custom-field-help').remove();
			return false;
		})
		.click(function(){return false;});
	}
});

$(document).ready(function(){
	
	$("input[name='fly_trip_type']").click( function(){
		if( !$("input[value='roundtrip']").attr('checked') ){
			$("input[name='fly_to_date_0']").attr("id","");
			$("input[name='fly_to_date_0']").prev().prev().attr("class","");
		}	
		else{
			$("input[name='fly_to_date_0']").attr("id","fto");	
		}
	} );
	
	
	//checkQSF(true);
		
	$("#qsf").submit(function(){
		//checkQSF();
		//var n = $('label',$(this)).not('.not_needed').size();
		var n_Error = $('label[class*="'+cl_Error+'"]',$(this)).size();
		var n_OK = $('label[class*="'+cl_OK+'"]',$(this)).size();
		//n>n_OK||
		
		if( n_Error>0 ){
			//var debug = '<b>'+n+','+n_Error+','+n_OK+'</b><br />';

			var html = '<div id="errors"><strong>Грешно въведени данни в полетата:</strong><ul>';
			$('label[class*="'+cl_Error+'"]',$(this)).each(function(){
					html += '<li>' + $(this).text() + '</li>';
			});
			html += '</ul></div>';
			html += '<div id="help"><strong>Внимание!</strong><br /><ul>';
			html += '<li>Име на град или три буквения код на летището в полетата „От” и „До” трябва да бъдат въведени на латиница. Например: SOFIA или SOF. Можете също да използвате иконата в дясно от където можете да изберете държава и желаната от вас дестинация.</li>';
			html += '<li>Дата на тръгване/Дата на връщане най-бързо и лесно можете да изберете от календара в дясно от полето. Когато въвеждате датата ръчно моля използвайте формата: ДД.ММ.ГГГГ (ден.месец.година)</li>';
			html += '</ul></div>';

//			html += '<li>Please enter city name or a 3-letter city code. Use autosuggestion or select city from the list (click the world icon to see the list).</li>';

			var docHeight = ($.browser.opera)
				? document.documentElement.scrollHeight
				: document.documentElement.clientHeight;
			var offsets = {
				'left':parseInt($('body').width()/2)-150,
				'top':parseInt(docHeight/2)+document.documentElement.scrollTop-125
			};

			$('body').append($('<div></div>').attr('id','softbox'));
			$('#softbox').softbox({
				width:400,
				offset:offsets,
				html:html,
				mask:false
			});
//				height:150,

			return false;
		}
		else
		{
			return true;
		}
	});
	
	
	
	//poniewaz ciasteczko przychodzi obecnie z php musi zostac unescapowane przed uzyciem (adamp) 
	createCookie('flights',unescape(readCookie('flights')));
	
	$('a.btn-city').unbind().destinator();

	$('#fly_from_0,#fly_to_0').focus(function(){
		closeDestinator();
	})

	$(this).click(function(){
		closeDestinator();
		closeCalendar();
		closeErrorMessage();
	});

	$('input.external,a.external,a._blank').attr({target: "_blank"});
	$('input.print,a.print').click(function(){
		window.print();
		return false;
	});

	$('input.virgin')
	.one('focus',function(){
		if($(this).hasClass('virgin')){ // do it only if the object still has "virgin" class
			$(this).val('').removeClass('virgin');
		}
	});
	
	$('input[type=text]').focus(function(){
		$(this).get(0).select();
	});
	
	$().eskyfeedback({action: ibeConfig.feedbackTarget});

});