/**
* Popup notice about changed form fields
* @example Place after form an javascript with popup_notice.init('form_id');
* Scripts in 'select' and 'checkbox' preserved.
* use class='nomark' to exclude elements
 * @ver 1.2
**/
var popup_notice = {};
/**
 * Init popup on form
 * @param form_id Form ID
 * @param spec_class Class of included elements
 * @param callback Callback function. If not set, will be used div[id=popup_notice] to show warning.
 */
popup_notice.init = function(form_id, spec_class, callback){
	popup_notice.form_id = form_id;
	if(callback) popup_notice.callback = callback;
	if(spec_class) popup_notice.checkboxItems = $('#'+form_id+' select.'+spec_class+','+'#'+form_id+' :checkbox.'+spec_class);
	else popup_notice.checkboxItems = $('#'+form_id+' select,'+'#'+form_id+' :checkbox');
	popup_notice.checkboxItems.each(function(index, element){
		var obj = $(this);
		if(obj.hasClass('nomark')) return false;
		if(obj.attr('type')=='checkbox') obj.data('old_value', this.checked);
		else obj.data('old_value', this.value);
		obj.change(popup_notice.check);
	});

	if(spec_class) popup_notice.textItems = $('#'+form_id+' :text.'+spec_class+','+'#'+form_id+' textarea.'+spec_class);
	else popup_notice.textItems = $('#'+form_id+' :text,'+'#'+form_id+' textarea');
	popup_notice.textItems.each(function(index, element){
		var obj = $(this);
		obj.data('old_value', this.value);
		obj.keyup(popup_notice.check);
	});
};
/**
 * Check for fields.
 * Internal function
 */
popup_notice.check = function(){
	var show = false;
	popup_notice.checkboxItems.each(function(index, element){
		var obj = $(this);
		var v1 = this.value;
		if(this.type=='checkbox') v1 = this.checked;
		if(typeof(obj.data('old_value'))!="undefined" && obj.data('old_value') != v1) show=true;
	});
	popup_notice.textItems.each(function(index, element){
		var obj = $(this);
		if(typeof(obj.data('old_value'))!="undefined" && obj.data('old_value') != this.value) show=true;
	});
	popup_notice.callback(show);
};
/**
 * Default callback function
 * @param show
 */
popup_notice.callback = function(show){
	var notice = $("#popup_notice");
	if(notice.length==0) {
		notice = $("<div id='popup_notice'>You have unsaved changes</div>");
		notice.prependTo('body');
	}
	if(show) notice.slideDown('slow');
	else notice.slideUp('slow');
};
popup_notice.hide = function(){
	popup_notice.callback(false);
};

/**
 * Fast filter to select match values from list of options in select element
 * @ver 1.0
 */
var fast_select_filter = {};
fast_select_filter.select_data = {};
fast_select_filter.init = function(select_id){
	this.select_data[select_id] = {};
	for(var i=0;i<document.getElementById(select_id).options.length;i++){
		this.select_data[select_id][i] = document.getElementById(select_id).options.item(i);
	}
	this.select_data[select_id].length = document.getElementById(select_id).options.length;
};

fast_select_filter.apply = function(select_id, value){
	if(!this.select_data[select_id]) return	 false;
	var oTarget = document.getElementById(select_id);
	while(oTarget.length!=0){oTarget.removeChild(oTarget.options.item(0));}

	for(var i=0;i<this.select_data[select_id].length;i++){
		var oCh = this.select_data[select_id][i];
		if(value=="" || oCh.innerHTML.toLowerCase().indexOf(value.toLowerCase())!=-1) oTarget.options[oTarget.length] = oCh;
	}
};

fast_select_filter.apply_use_timer = function(select_id, value, value_id){
	if(value!=document.getElementById(value_id).value) return false;
	this.apply(select_id, value);
};

/**
 * Search values using JSON call to server-side API
 */
var popup_search = {};
popup_search.init = function(path,object, send_object, request_var, callback_func){
	object.data('ajax_path',path);
	object.data('request_var',request_var);
	object.data('return',callback_func);
	object.data('send_object',send_object);
	object.data('req_sent',false);
	object.each(function(index, element){
		if(this.onkeyup) this.onkeyup_old = this.onkeyup;
		this.onkeyup = function(event){
			var event=window.event || event;
			if((57>=event.keyCode && event.keyCode>=48)
			|| (122>=event.keyCode && event.keyCode>=96)
			|| (90>=event.keyCode && event.keyCode>=65)
			|| (event.keyCode == 8) //|| (event.keyCode == 46) for dot
			|| (event.keyCode == 13) || (event.keyCode == 32)){
				setTimeout(function(recvalue,text_box){
					if(recvalue && recvalue==text_box.value) {
						if($(text_box).data('req_sent')) return false;
						$(text_box).data('req_sent',true);
						popup_search.get($(text_box));
					}
				},1500,this.value,this);
				if(this.onkeyup_old) this.onkeyup_old(event);
			}
		}
	});
};

popup_search.get = function(object){
	var path = object.data('ajax_path'),popup;
	var data = object.data('send_object').serialize();
	data += "&ajax=1";
	popup = object.nextAll(':first .search_popup');
	if(!popup.length) popup = $('<div style="position:absolute;" class="search_popup"></div>');
	var txt_offset = object.offset();
	popup.children().remove();
	object.after(popup);
	popup.offset({left:txt_offset,top:txt_offset+object.height()+1});
	popup.width(object.width());
	popup.append($('<img src="'+images_url+'load_ind_small.gif" />'));
	$.getJSON(path,data,function(result){
		object.data('req_sent',false);
		if($(result).length){
			$('img',popup).remove();
			if(result.error){
				popup.append($('<div>'+result.error+'</div>'));
			}
			if(result.data){
				popup.append($('<ul>'));
				$.each(result.data,function(index,element){
					var tr = $('<li onclick="$(this).data(\'return\')($(this));">');
					tr.data('return',object.data('return'));
					tr.data('data',element);
					tr.html(object.data('request_var'));
					$.each(element,function(indx,elem){
						var search = new RegExp("%"+indx+"%");
						tr.html(tr.html().replace(search,elem))
					});
					$('ul',popup).append(tr);
				});
			}
		}
	});
};

/**
 * Used for 2 input elements, hide one and show another
 * @param first_button
 * @param status
 */
function switch2buttons(first_button, status){
	if(status) {
		$('#'+first_button).next().attr('disabled', false);
		$('#'+first_button).next().show();
		$('#'+first_button).hide();
		$('#'+first_button).attr('disabled', true);
	}
	else{
		$('#'+first_button).next().attr('disabled', true);
		$('#'+first_button).next().hide();
		$('#'+first_button).show();
		$('#'+first_button).attr('disabled', false);
	}
}

/**
 * Open popup window to search clients
 * @param data Object with data to search
 * Fields:
 * - field_firstname - input field to return firstname
 * - field_lastname - input field to return lastname
 * - field_login - input field to return login
 * - field_name - input field for result 'Firstname Lastname'
 * - name - Full name 'Firstname Lastname' Or email
 * - prfx - Suffix used for input fields
 */
function popup_client_search(data){
	var v, result=[];
	for(k in data) if(data.hasOwnProperty(k)) result.push(k+"="+encodeURIComponent(data[k]));
	window.open (api_url + "simplesearch/"+result.join(), "searchclient", "width=400,height=400,toolbar=no,status=no,scrollbars=yes,resizable=no,menubar=no,location=no,direction=no");
}


/**
 * Message Box. Show notifications after page was load
 * @ver 1.0
 */
var MessageBox = {};
MessageBox.messages = [];
MessageBox.type = 'I';
/**
 * Show message box
 * @param items Array with messages
 * @param type Type of message
 */
MessageBox.show = function(items, type){
	if(!items) items=this.messages;
	if(!type) type=this.type;
	if(!items.length) return false;
	var msgBox = $('#message-box');
	msgBox.removeClass();
	switch(type){
		case "I": msgBox.addClass('info'); break;
		case "E": msgBox.addClass('error'); break;
		case "W": msgBox.addClass('info'); break;
	}
	$('span[id^=message_title]',msgBox).hide();
	$('#message_title_'+type,msgBox).show();
	$('#message_content',msgBox).html(items.join('<br/>'));
	msgBox.offset({ left: ($(document).width()-msgBox.width())/2});
	msgBox.slideDown('fast');
	this.messages = [];
	this.type = 'I';
	return true;
};

/**
 * Create fake console object if real object absent
 */
if(!console){
	var console = {};
	console.items = [];
	console.log = function(item){
		this.items.push(item);
	}
}

/**
 * Jquery plugin to switch between blocks
 * Required callback = function(status)
 * Required default value
 * v1.0
 */
(function($) {
	$.fn.changer = function(options) {
		var defaults = {
			callback: {},
			value: false
		};
		var opts = $.extend(defaults, options);
		this.bind('advOnChange',opts.callback);
		this.change(function(){
			$(this).trigger('advOnChange',[this.checked]);
		});
		this.trigger('advOnChange',[opts.value]);
		this.attr('checked',opts.value);
	};
})(jQuery);

/**
 * Jquery plugin to check form fields is empty
 * @param fields Array with fields ids
 * @param callback_conditions Can be true or function. Function should return true if fields checking is required
 * @param callback Callback function for each empty value. If return false - then checking process will be stopped.
 * fields_list, callback_conditions, callback
 */
(function($) {
	$.fn.checkFormFields = function(options) {
		var defaults = {
			fields: false,
			callback_conditions: true,
			callback: function(field){
				alert('Required field is empty');
				field.addClass('text-box-error',500);
				if(!field.data('checkFormFields-change')){
					if(field.is(':text')) {
						field.keyup(function(){
							field.removeClass('text-box-error',500);
						});
					}
					else{
						field.change(function(){
							field.removeClass('text-box-error',500);
						});
					}
					field.data('checkFormFields-change', true);
				}
			}
		};
		var opts = $.extend(defaults, options), $field;
		if(!opts.fields || !opts.fields.length || !$.isFunction(opts.callback)) {
			console.log('Initialization checkFormFields for form '+this.attr('name')+' failed');
			return false;
		}
		$(this).submit(function(){
			var submit = true, require_check;
			if($.isFunction(opts.callback_conditions)) require_check = opts.callback_conditions();
			else require_check = opts.callback_conditions;
			if(!require_check) return true;
			for(var i=0;i<opts.fields.length;i++){
				$field = $('#'+opts.fields[i]);
				console.log($field);
				if(!$.trim($field.val())) {
					if(!opts.callback($field)) return false;
					submit = false;
				}
			}
			return submit;

		});
		return true;
	};
})(jQuery);

/**
 * Countries.data object loaded via /countries_and_states.php?lang=US
 * @param country_id Countries container object, usually "select". It will be filled by options with localized countries
 * @param state_id States container object, usually "select". It will be filled by options with localized states
 * @param default_country Default country code
 * @param default_state Default state code
 * @ver 1.0
 */
var Countries = function(country_id, state_id, default_country, default_state){
	var thisObj = this;
	this.countryObj = $('#'+country_id);
	this.stateObj = $('#'+state_id);
	this.countryObj.change(function(){
		thisObj.fillStates(this.value);
		thisObj.selectState(thisObj.selectedState);
	});
	this.stateObj.change(function(){
		thisObj.selectedState = this.value;
	});
	this.fillCountries();
	if(this.selectCountry(default_country)) this.fillStates(default_country);
	this.selectState(default_state);
};
Countries.prototype.fillCountries = function(){
	var option;
	this.countryObj.children().remove();
	for(var i in this.data){
		if(!this.data[i].country) continue;
		option = $('<option>').html(this.data[i].country).val(this.data[i].country_code);
		this.countryObj.append(option);
	}
};
Countries.prototype.selectCountry = function(countryCode){
	if(!countryCode) return false;
	var option = $("option[value="+countryCode+"]",this.countryObj);
	if(option.length==0) return false;
	option.attr('selected', true);
	return true;
};
Countries.prototype.fillStates = function(countryCode){
	var option;
	this.stateObj.children().remove();
	if(!countryCode || this.data[countryCode].display_states!='Y' || !this.data[countryCode].states){
		option = $('<option>').html('NA').val('NA');
		this.stateObj.append(option);
	}
	else{
		for(var i in this.data[countryCode].states){
			if(!this.data[countryCode].states[i].state) continue;
			option = $('<option>').html(this.data[countryCode].states[i].state).val(this.data[countryCode].states[i].state_code);
			this.stateObj.append(option);
		}
	}
};
Countries.prototype.selectState = function(stateCode){
	if(!stateCode) return false;
	var option = $("option[value="+stateCode+"]",this.stateObj);
	if(option.length==0) return false;
	option.attr('selected', true);
	this.selectedState = stateCode;
	return true;
};

/**
 * Check email address
 * @param field DOM object, field contains email as value
 * @param empty_err
 * @ver 1.0
 */
function checkEmailAddress(field, empty_err) {
	var err = false, res, x, $field, value;
	if(!field) return true;
	if(typeof field=='string') value = field;
	else{
		if(field.jquery) $field = field;
		else $field = $(field);
		value = $field.val();
	}

	if(!value) return empty_err != 'Y';
	if(value.toUpperCase().match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/)==null) return false;
	return true;
}
