String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  var regex; 
  for (var i = 0; i < find.length; i++) {
    regex = new RegExp(find[i], "g");
    replaceString = replaceString.replace(regex, replace[i]);
  }
  return replaceString;
};

var month_name=Array("იანვარი", "თებერვალი", "მარტი", "აპრილი", "მაისი", "ივნისი", "ივლისი", "აგვისტო", "სექტემბერი", "ოქტომბერი", "ნოემბერი", "დეკემბერი");

var timeout_time=2000;
var popup_timer=null;

var find_text = ['ა','ბ','გ','დ','ე','ვ','ზ','თ','ი','კ','ლ','მ','ნ','ო','პ','ჟ','რ','ს','ტ','უ','ფ','ქ','ღ','ყ','შ','ჩ','ც','ძ','წ','ჭ','ხ','ჯ','ჰ'];
var replace_text = ['a','b','g','d','e','v','z','t','i','k','l','m','n','o','p','j','r','s','t','u','f','q','g','k','sh','ch','c','dz','w','ch','x','j','h'];


function parseVideoURL(url) {
    var provider=id1=id2='';
	if(url!='' && url!==undefined) {
		url.match(/^htt.+:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/);//.+$
		provider=RegExp.$1;
		id1=RegExp.$2;
		id2=RegExp.$3;
	}
	//url.match(/http:\/\/(?:www.)?(?:(vimeo).com\/(.*)|(youtube).com\/watch\?v=(.*?)&)/);
    return {
        provider : provider,
        id : provider == 'vimeo' ? id1 : id2
    }
}


$(document).ready(function() {
	latin_input();
	number_input();
	int_number_input();
	$('.calendar').datepick({showTrigger:'#cal_img'});
	$('input').attr('autocomplete', 'off');
    $('.mask-time').mask('00:00');

	message_popup_pos();
	
	$('#keyword').unbind('keyup');
	$('#keyword').keyup(function (e) { 
		if(e.which==13) {
			var data=$(this).attr('data-id');
			if(data==1) top_user_program_result();
		}	
	});
	
	// საჯეშენი
	/*
	$('#keyword').autocomplete({
		url: 'index.php?query_string=home&action=sugestion',
		sortFunction: function(a, b, filter) {
			var f = filter.toLowerCase();
			var fl = f.length;
			var a1 = a.value.toLowerCase().substring(0, fl) == f ? '0' : '1';
			var a1 = a1 + String(a.data[0]).toLowerCase();
			var b1 = b.value.toLowerCase().substring(0, fl) == f ? '0' : '1';
			var b1 = b1 + String(b.data[0]).toLowerCase();
			if(a1 > b1) return 1;
			if(a1 < b1) return -1;
			return 0;
		},
		showResult: function(value, data) {
			var txt=$('#keyword').val();
			value=value.replace(txt, '<b>'+txt+'</b>');
			return '<span>' + value + '</span>';
		},
		onItemSelect: function(item) {
			var list=item.data;
			$('#advertise').val('0');
			$('#top_keyword').val('0');
		},
		onNoMatch: function() {
			$('#advertise').val('0');
			$('#top_keyword').val('0');
		},
		maxItemsToShow: 5
	});
	*/
	select_checkbox();
});





function select_checkbox() {
	$('.select_checkbox').each(function(index, element) {
		html='<span class="select_checkbox_count"></span>';
		$(html).insertBefore($(this).find('img'));		
    });
	
	$('.select_checkbox_div').each(function(index, element) {
		var raod=$(this).find('input:checked').length;
		if(raod>0) raod=' ('+raod+')'; else raod='';		
		$(this).find('.select_checkbox_count').html(raod);	
    });	
	
	$('.select_checkbox_div input:checkbox').unbind('click');
	$('.select_checkbox_div input:checkbox').click(function () {		
		var raod=$(this).parent().parent().parent().find('input:checked').length;
		if(raod>0) raod=' ('+raod+')'; else raod='';		
		$(this).parent().parent().parent().parent().parent().find('.select_checkbox_count').html(raod);
	});
	
	
	$('.select_checkbox').unbind('click');
	$('.select_checkbox').click(function () {
		if(!$(this).parent().find('.select_checkbox_list').is(':visible')) {
			$('.select_checkbox_list').css('display', 'none');
			if($(this).parent().find('.select_checkbox_list').html()!='') $(this).parent().find('.select_checkbox_list').stop().slideDown(150);
		} else {
			$(this).parent().find('.select_checkbox_list').stop().slideUp(150);
		}
	});
	
	$(document).mouseup(function(e){
		var container=$('.select_checkbox_div');
		if(container.has(e.target).length===0) {
			container.find('.select_checkbox_list').slideUp(150);
		}
	});
}
























$(window).resize(function() {
	$('.acResults').css('display','none');
});
$(window).scroll(function() {
	$('.acResults').css('display','none');
});

function change_url(url, url2) {
	if(typeof(window.history.pushState)=='function') {
		window.history.pushState("", "", url);
	} else {
		window.location.hash=url2;
	}
}

$(window).resize(function() {
	message_popup_pos();
});

// მხოლოდ ლათინური
function latin_input() {
	$('.latin').unbind('keypress');
	$('.latin').keypress(function (e) { 
		if((e.which<32 || e.which>126) && e.which != 0 && e.which != 8 && e.which != 13) {
			return false;
		}
	});
}

// მხოლოდ ციფრები
function number_input() {
	$(document).on('keypress', '.number', function (e) { 
		if((e.which != 46 || $(this).val().indexOf('.') != -1 || $(this).val().indexOf(',') != -1) && (e.which != 44 || $(this).val().indexOf('.') != -1 || $(this).val().indexOf(',') != -1) && e.which > 31 && (e.which < 48 || e.which > 57) && e.which != 45 && e.which != 37 && e.which != 38 && e.which != 39 && e.which != 40 && e.which != 41 && e.which != 43 && e.which != 58 && e.which != 95 && e.which != 0 && e.which != 8) {
			return false;
		}	
	});
}

// მხოლოდ ციფრები
function int_number_input() {
	$(document).on('keypress', '.int_number', function (e) { 
		if(e.which > 31 && (e.which < 48 || e.which > 57) && e.which != 45 && e.which != 37 && e.which != 38 && e.which != 39 && e.which != 40 && e.which != 0 && e.which != 8) {
			return false;
		}	
	});
}

function time_input() {
	$(document).on('keypress', 'input.time', function (e) { 
		if(e.which > 31 && (e.which < 48 || e.which > 57) && e.which != 45 && e.which != 37 && e.which != 38 && e.which != 39 && e.which != 40 && e.which != 0 && e.which != 8 && (e.which != 58 || (e.which == 58 && $(this).val().indexOf(':') != -1))) {			
			return false;
		}	
	});
}


// პოპაპის დახურვა
function popup_close() {
	$('#message_popup').remove();	
	if(popup_timer) clearTimeout(popup_timer);
	popup_timer=null;
}

// პოპაპის გახსნა
function popup(text, op, bg, width, close_bt, def_top) {
	if(typeof def_top != 'undefined') {
		
	} else {
		def_top=-1;
	}
	
	var page=1;
	var html='';
	html+='<div id="message_popup" style="display:none;">';
	html+='	<div id="message_popup_bg"'+(bg?' onclick="popup_close();"':'')+'></div>';
	html+='	<div id="message_popup_content">';	
	html+='		<div id="message_popup_result" class="popup_div1">';
	html+='			<div class="popup_div2">';
	html+='				<div class="popup_div3" style="width:'+width+'px;">';
	html+='					<div class="popup_div4">'+(close_bt?'<a style="cursor:pointer;" onclick="popup_close();"><img src="img/close.png" alt="" /></a>':'')+'</div>';
	html+='					<div class="popup_div5">';
	html+=text;
	html+='					</div>';
	html+='				</div>';
	html+='			</div>';
	html+='		</div>';
	html+='	</div>';
	html+='</div>';	
	
	$('#body').append(html);
	$('#message_popup').css({'display':'block', 'opacity':'0'});
	var width=$(window).width(); if(width<1003) width=1003;
	var height=$(window).height(); if(height<500) height=500;
	var r_width=$('#message_popup_result').width();
	var r_height=$('#message_popup_result').height();
	var left=parseInt((width-r_width)/2);
	var top=parseInt(($(window).height()-r_height)/2);
	if(def_top>0) top=def_top;
	

	$('#message_popup').css({'display':'none', 'opacity':'1', 'width':width, 'height':height, 'position':'absolute', 'top':'0', 'left':'0', 'z-index':'2000'});
	$('#message_popup_bg').css({'width':width+20, 'height':height, 'position':'fixed', 'top':'0', 'left':'0', 'z-index':'2001', 'background-color':'#353a3f', 'opacity':op});
	$('#message_popup_content').css({'position':(def_top<0?'fixed':'absolute'), 'top':top, 'z-index':'2002', 'left':left, 'padding-bottom':'40px'});
	$('#message_popup').fadeIn(300);
	
	$(window).unbind('resize');
	$(window).resize(function() {
		var width=$(window).width(); if(width<1003) width=1003;
		var height=$(window).height(); if(height<500) height=500;
		var r_width=$('#message_popup_result').width();
		var r_height=$('#message_popup_result').height();
		var left=parseInt((width-r_width)/2);
		var top=parseInt(($(window).height()-r_height)/2);
		if(def_top>0) top=def_top;
		
		$('#message_popup').css({'width':width, 'height':height});
		$('#message_popup_bg').css({'width':width, 'height':height});
		$('#message_popup_content').css({'top':top, 'left':left});
	});
}

// პაროლის გენერირება
function password_generate(el, el2) {
    var length = 7;
    var charset = "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var number = "0123456789";
    var retVal = "";
    for(var i=0, n=charset.length; i<length; ++i) {
        retVal+= charset.charAt(Math.floor(Math.random() * n));
    }
    for(var i=0, n=number.length; i<1; ++i) {
        retVal+= number.charAt(Math.floor(Math.random() * n));
    }
    el.val(retVal).css({'color':'#000', 'font-style':'normal'});
	if(typeof(el2)==='undefined') el2=''; else el2.val(retVal);
}

//
function message_popup_pos() {
	var width=$('#body').width(); //width=1003;
	var f_left=$('.fakult_popup').width();
	f_left=parseInt((width-f_left)/2);
	$('#register_stop').css({'left':f_left, 'top':200});
	$('#delete_confirm').css({'left':f_left, 'top':200});
	$('#delete_confirm2').css({'left':f_left, 'top':200});
	$('#prev_step').css({'left':f_left, 'top':200});
	$('#next_step').css({'left':f_left, 'top':200});
}

// ველების ვალიდაცია
function input_validate(id, type) {
	var val=0;
	var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var input_val=$.trim($('#'+id).val());
	if(!$('#'+id).attr('disabled'))
	if(type=='input') {
		if(input_val=='' || input_val==$('#'+id).attr('title')) {
			val=1;
			$('#'+id).addClass('i_error');
		} else {
			$('#'+id).removeClass('i_error');
		}
	} else if(type=='select') {
		if(input_val=='0') {
			val=1;
			$('#'+id).addClass('i_error');
		} else {
			$('#'+id).removeClass('i_error');
		}
	} else if(type=='mail') {
		if(!filter.test(input_val)) {
			val=10;
			$('#'+id).addClass('i_error');
		} else {
			$('#'+id).removeClass('i_error');
		}
	} else if(type=='password') {
		if(input_val.length<6 || !(/\d+/g.test(input_val)) || !(/[a-zA-Z]+/g.test(input_val))) {
			val=9;
			$('#'+id).addClass('i_error');
		} else if(input_val!=$('#'+id+'2').val()) {
			val=8;
			$('#'+id).addClass('i_error');
			$('#'+id+'2').addClass('i_error');
		} else {
			$('#'+id).removeClass('i_error');
			$('#'+id+'2').removeClass('i_error');
		}
	} else if(type=='check') {
		if($('#'+id).is(':checked')) {
			$('#'+id).removeClass('i_error');
			$('#register_agree_text').css('color','#000');
		} else {
			val=1;
			$('#'+id).addClass('i_error');
			$('#register_agree_text').css('color','#C00');
		}
	}
	return val;
}

// ელემენტის ვალიდაცია
function field_validate(field, index) {
	var val=true;
	$('.field'+field).eq(index).removeClass('i_error');
	if($.trim($('.field'+field).eq(index).val())=='') {
		val=false;
		$('.field'+field).eq(index).addClass('i_error');
	}
	return val;
}

// ფელის მნიშვნელობა
function req_add($obj, type, name, validate) {
	var val=true;
	var time_val=/^([01]?[0-9]|2[0-9]):([0-5][0-9])*$/i;
	var date_val=/^(([0-9][0-9])\/([0-9][0-9])\/[0-9][0-9][0-9][0-9])*$/i;
	var mail_val=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var pass1_val=/\d/;
	var pass2_val=/[a-z]/;
	var pass3_val=/[A-Z]/;
	var value='';
	var req='';

	//var pass1_val=/\d+/g;
	//var pass2_val=/[a-z]+/g;
	//var pass3_val=/[A-Z]+/g;
	
	if(type=='checkbox') {
		value=($obj.is(':checked')?$obj.val():0);
	} else if(type=='price') { 
		value=$.trim($obj.val());
		if(value!='') value=value.replace(',', '.');
	} else if(type=='editor') {
		value=$.trim(tinyMCE.get(name).getContent());;
	} else {
		value=$.trim($obj.val()); 
	}
	
	if(value==$obj.attr('title')) value='';
	
	if(validate) {
		$obj.removeClass('i_error');
		$obj.parent().find('.ui-combobox').removeClass('i_error');
		
		if(type=='text' && value=='') {
			$obj.addClass('i_error');
			val=false;
		} else if(type=='time' && !time_val.test(value)) {
			$obj.addClass('i_error');
			val=false;
		} else if(type=='date' && !date_val.test(value)) {
			$obj.addClass('i_error');
			val=false;
		} else if(type=='mail' && !mail_val.test(value)) {
			$obj.addClass('i_error');
			val=false;
		} else if(type=='password' && (value.length < 6 || !pass1_val.test(value) || !pass2_val.test(value))) { // || !pass3_val.test(value) // || !pass1_val.test(value) || !pass2_val.test(value) || !pass3_val.test(value)
			$obj.addClass('i_error');
			val=false;
		} else if(type=='select' && value==0 && $obj.find('option').length > 1) {
			$obj.addClass('i_error');
			val=false;
		} else if(type=='select2' && value==0) {
			$obj.addClass('i_error');
			val=false;
		} else if(type=='select3' && value==0) {
			$obj.parent().find('.ui-combobox').addClass('i_error');
			val=false;
		} else if(type=='file' && value=='') {
			$obj.addClass('i_error');
			val=false;
		}
		
		if(type == 'password') {
			$('#register-password').removeClass('i_error i_error_1 i_error_2');
			$('#register-password2').removeClass('i_error i_error_1 i_error_2');

			value += '';
			if(value.length < 6 || !pass1_val.test(value) || !pass2_val.test(value)) { // || !pass3_val.test(value)
				val = false;
				$('#register-password').addClass('i_error').addClass('i_error_1');
				//console.log("value = " + value);
				//console.log("value length = " + value.length);
				//console.log("pass1_val = " + pass1_val.test(value));
				//console.log("pass2_val = " + pass2_val.test(value));
				//console.log("pass3_val = " + pass3_val.test(value));
			} else if(value == '' || value != $('#register-password2').val()) {
				val = false;
				$('#register-password').addClass('i_error').addClass('i_error_2');
				$('#register-password2').addClass('i_error').addClass('i_error_2');
			} else {
				$('#register-password').removeClass('i_error i_error_1 i_error_2');
				$('#register-password2').removeClass('i_error i_error_1 i_error_2');
			}
		}
	}
	
	if(val) {
		if(type == 'checkbox' && value != 0) {
			if(validate) $obj.parent().removeClass('i_error');
		}
		
		
		if(type == 'text' && value == '') {
			
		} else if(type == 'select' && value == 0) {
			
		} else if(type == 'checkbox' && value == 0) {
			if(validate) {
				$obj.parent().addClass('i_error');
				val=false;
				req='req_false';
			}
		} else {
			if(name === 'object_name') {
				req = '&objectName=' + encodeURIComponent(value);
			} else {
				req = '&' + name + '=' + encodeURIComponent(value);
			}
		}
	} else {
		req='req_false';
	}
	
	return req;
}

function sortDiv(parent, childSelector, keySelector, type) {
    var items = parent.children(childSelector).sort(function(a, b) {
		var vA = $(keySelector, a).attr('title'); if(typeof vA === 'undefined') vA = $(keySelector, a).text();
		var vB = $(keySelector, b).attr('title'); if(typeof vB === 'undefined') vB = $(keySelector, b).text();
		vA=vA.toLowerCase();
		vB=vB.toLowerCase();
		vA=(vA==parseInt(vA)?parseInt(vA):vA);
		vB=(vB==parseInt(vB)?parseInt(vB):vB);
        //var vA = $(keySelector, a).text(); vA=(vA==parseInt(vA)?parseInt(vA):vA);
        //var vB = $(keySelector, b).text(); vB=(vB==parseInt(vB)?parseInt(vB):vB);
        if(type==1) return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
        else return (vA > vB) ? -1 : (vA < vB) ? 1 : 0;
    });
	//alert($(items[0]).html())
	parent.html('');
    parent.append(items);
}

function template(tmp_id, vars) {
	var tpl=$('#'+tmp_id).html();

	//placeholders replacement
	var result=tpl.replace(/{(\w+)}/gi, function(match, key) {
		return key in vars?vars[key]:'';
	});
	return result;
}

/*
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});
*/

function string_time(string) {
	if(typeof string === "undefined" || string=='') return 0;
    string=string.split(/:/);
	//alert(string+' '+(string[0]*3600+string[1]*60+1262289600)*1000)
    return (string[0]*3600+string[1]*60+1262289600)*1000;
}

function time_add(time, add) {
	return time+add*60000;
}

function time_string(time) {	
	var d=new Date();
	var n=d.getTimezoneOffset();
	n=n+240;
	n*=60000;
	
	time=parseInt(time);	
	var date=new Date(time+n);	
	var hours=date.getHours();
	var minutes=date.getMinutes(); minutes=(minutes<10?'0'+minutes:minutes);
	
	return hours+':'+minutes;
}

function date_string(date, type) {
	date=parseInt(date)*1000;
	var date=new Date(date);
	
	var year=date.getFullYear();
	var month=date.getMonth();
	var day=date.getDate();
	
	var r_date='';
	
	r_date=year+'-'+month+'-'+day;
	if(type==1) {
		day=(day<10?'0'+day:day);
		r_date=day+' '+month_name[month]+' '+year;
	}
	
	return r_date;
}

function calculate_age(bdate) {
	bdate=bdate.split('/');
	var birth_day=bdate[0]; if(birth_day.substr(0, 1)=='0') birth_day=birth_day.substr(1, 1);
	var birth_month=bdate[1]; if(birth_month.substr(0, 1)=='0') birth_month=birth_month.substr(1, 1);
	var birth_year=bdate[2];
	birth_day=parseInt(birth_day);
	birth_month=parseInt(birth_month);
	birth_year=parseInt(birth_year);
	
	today_date=new Date();
    today_year=today_date.getFullYear();
    today_month=today_date.getMonth();
    today_day=today_date.getDate();
    age=today_year-birth_year;

    if(today_month<(birth_month-1)) {
        age--;
    }
    if(((birth_month-1)==today_month) && (today_day<birth_day)) {
        age--;
    }
    return age;
}

function patientId(id) {
	id=parseInt(id);
	if(id<10) return '00'+id;
	else if(id<100) return '0'+id;
	else return id;
}

function filter_ch(name, type) {
	if(type=='text') {
		return ($('#'+name+'_on').is(':checked') && $('#'+name).val()!='' && $('#'+name).val()!=$('#'+name).attr('title'))?$('#'+name).val():'';
	} else if(type=='select') {
		return ($('#'+name+'_on').is(':checked') && $('#'+name).length && $('#'+name).val()!=0 && $('#'+name).val()!=null)?$('#'+name).val():'';
	}
}

function row_filter(parent_class, row_class, index, value, equal) {
	var index_val=true;
	if(value!='') {
		$(parent_class).eq(index).css('display','none');
		if(equal==1) {
			if($(parent_class+":eq("+index+") "+row_class+"").html()==value) $(parent_class+":eq("+index+") "+row_class+"").parent().css('display','block');
		} else {
			$(parent_class+":eq("+index+") "+row_class+":contains('"+value+"')").parent().css('display','block');
		}
		if(!$(parent_class+':eq('+index+')').is(':visible')) index_val=false;
	}
	return index_val;
}

function date_range(date1, date2) {
	if(date1!='' && date2!='') {
		var d1=date1.split('/');
		var d2=date2.split('/');
		
		d1[1]=parseInt(d1[1])-1;
		d2[1]=parseInt(d2[1])-1;
		
		var oneDay = 24*60*60*1000;
		var firstDate = new Date(d1[2], d1[1], d1[0]);
		var secondDate = new Date(d2[2], d2[1], d2[0]);
		
		var diffDays=Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
		diffDays=(diffDays>=0?(diffDays+1):diffDays);
		diffDays+='';
		
		var last=diffDays[diffDays.length-1]; last=parseInt(last);
		if(diffDays.length>1 && diffDays[diffDays.length-2]==1) return diffDays+' дней';
		else if(last==0 || last>=5) return diffDays+' дней';
		else if(last>1 && last<5) return diffDays+' дня';
		else return diffDays+' день';
	} else {
		return '';	
	}
}

function date_range2(date1, date2) {
	if(date1!='' && date2!='') {
		var d1=date1.split('/');
		var d2=date2.split('/');
		
		d1[1]=parseInt(d1[1])-1;
		d2[1]=parseInt(d2[1])-1;
		
		var oneDay = 24*60*60*1000;
		var firstDate = new Date(d1[2], d1[1], d1[0]);
		var secondDate = new Date(d2[2], d2[1], d2[0]);
		
		//var diffDays=Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
		var diffDays=firstDate.getTime() - secondDate.getTime();
		//alert(diffDays)
		diffDays=Math.abs(diffDays);
		diffDays/=oneDay;
		//alert(diffDays)		
		diffDays=(diffDays>=0?(diffDays+1):diffDays);
		diffDays+='';
		//alert(diffDays)
		
		var last=diffDays[diffDays.length-1]; last=parseInt(last);
		if(diffDays.length>1 && diffDays[diffDays.length-2]==1) return diffDays+' дней';
		else if(last==0 || last>=5) return diffDays+' дней';
		else if(last>1 && last<5) return diffDays+' дня';
		else return diffDays+' день';
	} else {
		return '';	
	}
}

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}
