$(document).ready(function() {

	$('#head_login_form').bind('keypress', function(e) {
		if(e.keyCode == 13) {
			$('#head_login_form').submit();
		}
	});

    if($.datepicker){
        $.datepicker.setDefaults($.datepicker.regional['de']);
    }

	$('div.bar').click(function() {
		var bID = $(this).attr('id');
		if($(this).find('h2').hasClass('active')) {
			$(this).find('h2').removeClass('active');
			$('#'+bID+'_content').hide();
		} else {
			$(this).find('h2').addClass('active');
			$('#'+bID+'_content').show();
		}
	});

	$('span.error').tooltip({
		bodyHandler: function(){
			return $(this).html();
		},
		showURL: false
	});

	$('area').tooltip({
		bodyHandler: function() {
			return $(this).attr('lang');
		},
		showURL: false
	});

    //open nedded href's in new window (not valid with target="_blank")
    //all links that need to be opened in new window must have a generic class targetBlank
    $('.targetBlank').attr('target','_blank');

	//auto loading
	if ($('#loading_ajax').length > 0) {
		$('#loading_ajax')
		.hide()  // hide it initially
		.ajaxStart(function() {
			$(this).show();
		})
		.ajaxStop(function() {
			$(this).hide();
		});
	}

	$("form").bind("submit", function() {
       $('#loading_ajax').show();
    });
	// /auto loading

	//$(".error").hide(); // hide all errors on load

	if($("#dialog_sendFeedback").length > 0) {
		$("#dialog_sendFeedback").dialog({
			autoOpen: false,
			modal: true,
			closeText: '',
			width:400
		});
	}

	$("input, select, textarea").live('focusin', function() {
		$(this).addClass('focused');
	});

	$("input, select, textarea").live('focusout', function(){
		$(this).removeClass('focused');
	});

	//left menu
	//Hide (Collapse) the toggle containers on load
	$("ul.nav").hide();

	$("a.updown").click(function() {
		if ($(this).parent().next("ul.nav").find("a.active").length == 0) {
			$(this).toggleClass('active').parent("h3.trigger").toggleClass('active');
		}
	}).bind("click",function() {
		if ($(this).parent().next("ul.nav").find("a.active").length == 0) {
			$(this).parent().next("ul.nav").slideToggle("fast");
		}
	});
	// /left menu

	//hover rows
	$('table.listing tr').live("mouseover", function() {
	    if ($(this).prev().length >= 1) {
	    	$(this).addClass('selected');
		  	if ($(this).prev().find('th').length != 0) {
		    	$(this).prev().find('th').each(function() {
		        	$(this).addClass('upper_border');
		        });
		    }

	        $(this).prev().children('td').each(function(){
	        	$(this).addClass('upper_border');
	        });
		}
	});

	$('table.listing tr').live("mouseout", function() {
	    if ($(this).prev().length >= 1) {
	    	$(this).removeClass('selected');
		    if ($(this).prev().find('th').length != 0) {
		    	$(this).prev().find('th').each(function() {
		        	$(this).removeClass('upper_border');
		        });
		    }

	        $(this).prev().children('td').each(function(){
	        	$(this).removeClass('upper_border');
	        });
		}
	});
	// /hover rows

	//table order
	$('table.listing th.ov,table.listing  th.ov_a').live("mouseover", function() {
		if($(this).children("a").hasClass('null')) {
			$(this).children("a").removeClass('null');
			$(this).children("a").addClass('asc');
		} else if($(this).children("a").hasClass('desc')) {
			$(this).children("a").removeClass('desc');
			$(this).children("a").addClass('asc');
		} else if($(this).children("a").hasClass('asc')) {
			$(this).children("a").removeClass('asc');
			$(this).children("a").addClass('desc');
		}
		$(this).addClass("active_2");
	});

	$('table.listing th.ov, table.listing th.ov_a').live("mouseout", function(){

		if($(this).children("a").hasClass('desc')) {
			$(this).children("a").removeClass('null');
			$(this).children("a").removeClass('desc');
			$(this).children("a").addClass('asc');
		} else if($(this).children("a").hasClass('asc')) {
		    if ($(this).hasClass("active")) {
		        $(this).children("a").removeClass('asc');
				$(this).children("a").removeClass('null');
				$(this).children("a").addClass('desc');
		    } else {
				$(this).children("a").removeClass('asc');
				$(this).children("a").removeClass('desc');
				$(this).children("a").addClass('null');
		    }
		}

		$(this).removeClass("active_2");
	});

	$('table.listing th.ov').live("click", function() {
		var sortType, sortBy;
		if ($(this).children("a").hasClass('asc')) {
			sortType = 'asc';
		} else {
			sortType = 'desc';
		}

		sortBy = $(this).children("a").attr('title');

		$("#sortBy").val(sortBy);
		$("#sortType").val(sortType);

		var mainForm = $(this).parents('form');
		mainForm.submit();
	});

	$('table.listing th.ov_a').live("click", function() {
//		var sortType, sortBy;
//		if ($(this).children("a").attr('class') == 'order_asc') {
//			sortType = 'asc';
//		} else {
//			sortType = 'desc';
//		}
//
//		sortBy = $(this).children("a").attr('title');
//
//		$("#sortBy").val(sortBy);
//		$("#sortType").val(sortType);
//
//		var mainForm = $(this).parents('form');
//		mainForm.submit();
	});
	// /table order
});

// make height fixed for pages with tables
function doResize() {

//	if ($('table.listing').length > 0) {
//		var tableMaxWidth = 0;
//		var realWidth = $('#top').width();
//
//		$('div.mainbox').width(realWidth);
//
//		$('#main-content-inner').width(realWidth + 25);
//
//		$('table.listing').each(function() {
//			if (tableMaxWidth < $(this).width()) {
//				tableMaxWidth = $(this).width();
//			}
//		});
//
//		if (tableMaxWidth >= realWidth-50) {
//			$('div.mainbox').width(tableMaxWidth + 50);
//			$('#main-content-inner').width(tableMaxWidth + 75);
//		}
//	} else {

		var screenWidth = $(window).width();
		//var oldDocWidth = $(document).width();
		var oldMainBoxWidth = $('div.mainbox').width();
		//$('div.mainbox').width(screenWidth - 240);
		//var newMainBoxWidth = $('div.mainbox').width();
		//var newDocWidth = $(document).width();


		if (oldMainBoxWidth > screenWidth - 240) {
		//	$('div.mainbox').width(oldMainBoxWidth);
			//$('div.mainbox').width(docWidth - 240);
		} else {
			$('div.mainbox').width(screenWidth - 240);
		}

		//alert(" screen :"+ screenWidth + " >> doc old :" + oldDocWidth + ">>  doc new: " + newDocWidth  + " >> old : " + oldMainBoxWidth + " >> new : " + newMainBoxWidth + " >> should be:" +(screenWidth - 240));
//	}
}
// /make height fixed for pages with tables

function initDialog(){ // de pus: $(document).ready(function() {  initDialog() });
	$("#m_dialog").dialog({
		autoOpen: false,
		modal: true,
		closeText: '',
		bgiframe: true/*,

		close: function(event, ui) {
				$(this).dialog("destroy");
			}*/
	});
}

function initDialogBox(divID){
	$("#"+divID).dialog({
		autoOpen: false,
		bgiframe: true,
		resizable: false,
		draggable: false,
		modal: true
	});
}

function showDialog(title, message){
	$("#m_dialog")
		.dialog('option', 'title', title)
		.dialog('option', 'buttons', {
			"OK":function(){
				$(this).empty();
				$(this).dialog("close");
			}
		})
		.html(message)
		.dialog("open");

	return false;
}

function showDialog2(title, message){
	$("#m_dialog")
		.dialog('option', 'title', title)
		.dialog('option', 'buttons', {
			"OK":function(){
				$(this).empty();
				$(this).dialog("close");
			}
		})
		.html(message)
		.dialog("open")
		.fadeIn('fast')
		.animate({opacity: 1.0}, 1000)
		/*.fadeOut('slow', function() {
			$(this).empty();
			$(this).dialog("close");
		});*/

	return false;
}


//usage : confirmDialog("titlu","mesaj", nume_functie_yes)
function confirmDialog(title, message, yesCallback){

	yesCallback = handleYes || function(){return true};

	$("#m_dialog")
		.html(message)
		.dialog("open");
	$('#m_dialog').dialog('option', 'title', title);

	$('#m_dialog').dialog('option', 'buttons', {
		"No":function(){
			$(this).dialog("close");
		},
		"Yes":function(){
			yesCallback();
			$(this).dialog("close");

		}
	});
	return false;

}

function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (regex.test(email)){
    	return true;
    } else {
    	return false;
    }
}
////check if enter

var isNavEnter, isIEEnter;
if (parseInt(navigator.appVersion)>=4) {
	if(navigator.appName == "Netscape")
	{
		isNavEnter = true;
	}
	else
	{
		isIEEnter = true;
	}
}

function checkEnter(evt, action) {
	var key;
	if (isNavEnter)
	{
		key = evt.which;
	}
	else
	{
		key = window.event.keyCode;
	}
	if (key==13)
	{
		eval(action);

	}
}

function checkTab(evt, action) {
	var key;
	if (isNavEnter)
	{
		key = evt.keyCode;
	}
	else
	{
		key = window.event.keyCode;
	}


	if (key==9)
	{
		eval(action);

	}
}

//show loading bar
function showLoading(){
    $('#loading_ajax').show();
}

//hide loading bar
function hideLoading(){
    $('#loading_ajax').hide();
}

function redirectLoading(RURL) {
	showLoading();
	document.location.href = RURL;
	return false;
}

function submitLoading(formAction, formID) {
	showLoading();
	$('#'+formID).attr("action", formAction);
	$('#'+formID).submit();
	return false;
}

function isURL(argvalue) {

	  if (argvalue.indexOf(" ") != -1)
	    return false;
	  else if (argvalue.indexOf("http://") == -1)
	    return false;
	  else if (argvalue == "http://")
	    return false;
	  else if (argvalue.indexOf("http://") > 0)
	    return false;

	  argvalue = argvalue.substring(7, argvalue.length);
	  if (argvalue.indexOf(".") == -1)
	    return false;
	  else if (argvalue.indexOf(".") == 0)
	    return false;
	  else if (argvalue.charAt(argvalue.length - 1) == ".")
	    return false;

	  if (argvalue.indexOf("/") != -1) {
	    argvalue = argvalue.substring(0, argvalue.indexOf("/"));
	    if (argvalue.charAt(argvalue.length - 1) == ".")
	      return false;
	  }

	  if (argvalue.indexOf(":") != -1) {
	    if (argvalue.indexOf(":") == (argvalue.length - 1))
	      return false;
	    else if (argvalue.charAt(argvalue.indexOf(":") + 1) == ".")
	      return false;
	    argvalue = argvalue.substring(0, argvalue.indexOf(":"));
	    if (argvalue.charAt(argvalue.length - 1) == ".")
	      return false;
	  }

	  return true;

}

/**
 * Using jQuery utilities, this function changes a given value of an input with another given value
 *
 * @param selector
 * @param value
 * @param replace
 * @return bool
 */
function fetch_value(selector, value, replace){
	if($('#' + selector).val() == value){
	    $('#' + selector).val(replace);
	}

	return false;
}

/**
 * A particular case of fetch_value() function
 * Using jQuery utilities, this function changes the current value of a checkbox to a deserved value
 *
 * @param selector
 * @param data
 * @returns	bool
 */
function change_checkbox_value(selector, data){
	console.log($(selector));
	first = data[0];
	second = data[1];

	if($(selector).val() == first){
		$(selector).val(second);
	}else{
		if($(selector).val() == second){
			$(selector).val(first);
		}
	}
	console.log($(selector));
	return false;
}

/**
 * Select all checkboxes in a list with a specified class
 *
 * @access      public
 * @return      void
 *
*/
function select_all(obj, class_checkbox){
	var check = obj.checked;
	$('input[type="checkbox"].' + class_checkbox).each(function (){
		this.checked = check;
	});
}

function selectUnselectAll(clicked, what){
	 var checked_status = $("#"+clicked+"").attr("checked");

	 $("input[type='checkbox'][name='"+what+"']").each(function(){
	 	if($(this).attr("disabled")){
	 	}
	 	else{
	 		$(this).attr("checked", checked_status);
	 	}
	 });
}

function startWait() {
	$("body").css("cursor", "wait");
}

function stopWait() {
	$("body").css("cursor", "auto");
}

function resetPageNumber(formID) {
	$('#pageNumber').val(1);
	$('#'+formID).submit();
}

function formatMoney(value, lang){

    var formatedValue = value;

    // float $number  ,  int $decimals  ,  string $dec_point  ,  string $thousands_sep
    if(lang != ""){
        switch(lang){
            case 'en':
                formatedValue = number_format(value, 0, ",", ".");
                break;
            case 'de':
                formatedValue = number_format(value, 0, ",", ".");
                break;
            default:
                formatedValue = number_format(value, 0, ",", ".");
                break;
        }
    }
    else{
        formatedValue = number_format(value, 0, ",", ".");
    }

    return formatedValue;
}

function formatLocationName(cityName, regionName, countryName) {
	if(cityName != '') {
		return cityName + " ("+regionName + ", "+countryName + ")";
	} else if (regionName != '') {
		return regionName + " (" + countryName + ")";
	} else if (countryName != '') {
		return countryName;
	}

	return '';
}


function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}