/**
 *  this variable tells which event signup form is opened. 1 is user form, 0 is company form
 */
var userOrCompanyForm = 1;
/**
 *  Global variable used by "switchEventBannerContent" function to store its ajax cache data
 *
 */
var bannerCache = new Array;
/**
 *  Global cache lock
 */
var bannerCacheLock = 0;
/**
 * Description: this function enables the blue ribbon indicator in the front of
 * the event list button. 
 */
/* 
function activateBlueIndicator(element){
     var el = $(element).children(".active_event_list");
     $(el).css("display","block");
}
*/
function activateIndicator(element,selected) {
	/**
	 *  remove selection from all elements/tabs
	 */
	var allTabs = $(".event_list_container").children(".active_event_list");
	jQuery.each(allTabs, function(){
		$(this).css("display","");
	}
	);
	var el = $('#eda'+element).children(".active_event_list");
	$(el).addClass(selected);
	$(el).css('display','block');
}

/**
 *  @ description   : this function removes colored ribbons from right menu except for current one.
 *
 *  @param selected : name of the class for active ribbon/tab indication (only the color of the ribbon
 *  @paran element  : current hover elment
 */
function deactivateIndicator(element,selected,disable) {

	/**
	 *  remove selection from all elements/tabs
	 */
	var allTabs = $(".event_list_container").children(".active_event_list");

	jQuery.each(allTabs, function(){
		$(this).css("display","");
	}
	);

	/**
	 * last hover element/tab must remain selected
	 */
	el = $('#eda'+disable).children(".active_event_list");

	$(el).css("display","block");
	$(el).addClass(selected);
}
/**
 * Description: this function submits sign up for e news form. Form is placed 
 * in the events template (blue box at tle left side) 
 */ 
function submitSignUpForm(element, nid){
	var person_email = $("#person_email_for_enews").val();

	// ensure that data is non empty string
	var afna_position        = person_email.lastIndexOf("@");
	var last_dot_position    = person_email.indexOf(".",afna_position);
	var lang_id              = $("#lang_id").val();
	if(typeof person_email == "string" && person_email.length > 0 && afna_position > 1 && last_dot_position > 1){
          
	// make mail accepted animation
	$("#person_email_for_enews_txt").fadeOut(300, function(){
		$("#person_email_for_enews_txt").css("display","none");
		$("#person_email_for_enews_txt_ok").fadeIn(100, function(){
            $("#person_email_for_enews").animate( { backgroundColor: '#D7FCB1' }, 500);
			$("#person_email_for_enews").val("");
			$("#person_email_for_enews_txt_ok").fadeOut(5000, function(){
				$("#person_email_for_enews").animate( { backgroundColor: 'white' }, 500);
          		$("#person_email_for_enews_txt").fadeIn(300);
			});
		});
	});
	// make ajax request
	$.ajax({
		type: "GET",
		url: "/"+lang_id+"/ajax/",
		data: "signup_for_event_enews=1&email_address="+person_email+"&type="+nid,
		success: function(msg){
		//alert( "Data Saved: " + msg );
	}
	});
          
     }else{
          // make error animation
		$("#person_email_for_enews_txt").fadeOut(300, function(){
			$("#person_email_for_enews_txt").css("display","none");
			$("#person_email_for_enews_txt_err").css("color","#FFFFFF");
			$("#person_email_for_enews_txt_err").css("font-weight","bold");
			$("#person_email_for_enews_txt_err").fadeIn(300, function(){
                $("#person_email_for_enews").animate( { backgroundColor: '#FBF179' },1600)
				$("#person_email_for_enews_txt_err").fadeOut(3500, function(){
					$("#person_email_for_enews_txt").fadeIn(300);
					$("#person_email_for_enews").animate( { backgroundColor: 'white' }, 1300)
				});
			});
		});
     }
     
     // free
     afna_position       = null;
     last_dot_position   = null;
     person_email        = null;
     lang_id             = null;
}

/**
 *  @description : function retrieves banner data from ajax call. If call has been alreay retrieved earlier, display data is take from the cache whic is generated with every call.
 *
 *  @param bannerType 	: type of the banner/current template (e.g. events, library,news, ...)
 *  $param id           : id of the event/news/bookstore
 *
 *  @uses               : function uses global variable bannerCache to store cache data from ajax calls
 *  @author             : Jernej Gololicic
 */
function switchEventBannerContent(bannerType, id) {

	var lang_id = $("#lang_id").val();
	var valuesArray = new Array();
	var tmpString = "";

	/**
	 *  Is data already in global cache ?
	 */
	if (bannerCache[bannerType+id]) {
		switch (bannerType) {
			case "events" :
				processAjaxEventData(bannerCache[bannerType+id]);
				break;
			case "bookstore" :
				processAjaxBookstoreData(bannerCache[bannerType+id]);
				break;
		}
	}
	else if (bannerCacheLock == 0)
	{
	/**
	 *  Data is not in global cache, retreive data from ajax call
	 */

		/**
		 *  Lock banner cache
		 */
		bannerCacheLock = 1;

		$.ajax({
			type	: "GET",
			url		: "/"+lang_id+"/ajax/",
			data	: "bannerData="+bannerType+"&id="+id,
			async	: true,
			success: function(msg){
				bannerCache[bannerType+id] = msg;	
				switch (bannerType) {
					case "events" :
						processAjaxEventData(msg);
						break;
					case "bookstore" :
						processAjaxBookstoreData(msg);
						break;
				}
			}	
		});
	}
}
function processAjaxBookstoreData(msg)
{
	$("#events_banner_container").fadeOut(10,function (){
		$("#events_banner_container").html(msg);
		$("#events_banner_container").fadeIn(1000);
	});
	bannerCacheLock = 0;
}
/**
 *  @description	: function assigns ajax return data to html elements on event template
 *  @param msg      : echo message string returned by ajax call
 *
 *  @author         : Jernej Gololicic
 */
function processAjaxEventData(msg){
	var wholeData =new Object();

	valuesArray = msg.split("|");

	/**
	 * Fill object members with data
	 */
	for (var i = 0; i < valuesArray.length; i++) {
		tmpString = valuesArray[i].split("=");
		wholeData[tmpString[0]] = tmpString[1];
	}

	/**
	 * Set the css background
	 */
	$("#seminar_book_logo_container").fadeOut(10, function () {
		$("#seminar_book_logo_container").css("background-image","url(/static/images/"+ wholeData.seminar_book_logo_container +")");
        $("#seminar_book_logo_container").fadeIn(1000);
	});
	$("#bottom_image_container").fadeOut(10, function () {
		$("#bottom_image_container").css("background-image","url(/static/images/"+ wholeData.bottom_image_container +")");
    	$("#bottom_image_container").fadeIn(1000);
	});

	/**
	 * Set the html content
	 */
 	$("#event_banner_top_title_container_h1").fadeOut(10, function () {
		$("#event_banner_top_title_container_h1").html(wholeData.event_banner_top_title_container_h1);
		$("#event_banner_top_title_container_h1").fadeIn(1000);
	});
	$("#event_banner_top_title_container_h2").fadeOut(10, function () {
		$("#event_banner_top_title_container_h2").html(wholeData.event_banner_top_title_container_h2);
		$("#event_banner_top_title_container_h2").fadeIn(1000);
	});
	$("#event_banner_top_title_container_h3").fadeOut(10, function () {
		$("#event_banner_top_title_container_h3").html(wholeData.event_banner_top_title_container_h3);
		$("#event_banner_top_title_container_h3").fadeIn(1000);
	});

	/**
	 *  Set the href attribute
	 */
	$("#seminar_button_blue").attr("href",wholeData.seminar_button_blue+"/");
	$("#seminar_button_dark_blue").attr("href", wholeData.seminar_button_dark_blue+"/"+$("#signup_url").val()+"/");


	/**
	 *  Unlock banner cache
	 */
	bannerCacheLock = 0;
}
/**
 *  @description    : 	This function displays person signup form. Form is located in "event_signup.tpl" template file.
 *  					After page refresh person form is displayed as default form.
 *  @author         :   Jernej Gololicic
 */
function showPersonSignupForm(){

		/**
		 *  Set proper form display
		 */
		 userOrCompanyForm = 1;

		/**
		 *  Hide unrelevant fields
		 */

		$("#company_number_container").fadeOut(0, function () {
			$("#company_number_container").css("display","none");
		});
		
		$("#tax_yes_no_container").fadeOut(0, function () {
			$("#tax_yes_no_container").css("display","none");
		});

		$("#compay_tax_number_container").fadeOut(0, function () {
			$("#compay_tax_number_container").css("display","none");
		});

		/* person title */
		$("#person_title_container").fadeOut(0, function () {
			$("#person_title_container").css("display","none");
		});

		/* person firstname */
		$("#company_firstname_container").fadeOut(0, function () {
			$("#company_firstname_container").css("display","none");
		});

		/* person lastname */
		$("#company_lastname_container").fadeOut(0, function () {
			$("#company_lastname_container").css("display","none");
		});

		/* person email */
		$("#company_email_container").fadeOut(0, function () {
			$("#company_email_container").css("display","none");
		});

		/* person workplace */
		$("#company_workplace_container").fadeOut(0, function () {
			$("#company_workplace_container").css("display","none");
		});

		/* workplace */
		$("#workplace_container").fadeOut(0, function () {
			$("#workplace_container").css("display","none");
		});
		/* company title */
		$("#company_title_container").fadeOut(0, function () {
			$("#company_title_container").css("display","none");
		});

		$(".add_another_user_button_container").each(function(){
			$(this).fadeOut(0, function () {
				$(this).css("display","none");
			});
		});

		$(".company_user_subform").each(function(){
			$(this).fadeOut(0, function () {
				$(this).css("display","none");
			});
		});

		/**
		 *  Show relevant fields
		 */
		/* firstname */
		$("#firstname_container").fadeIn(0, function () {
			$("#firstname_container").css("display","block");
		});

		/* lastname */
		$("#lastname_container").fadeIn(0, function () {
			$("#lastname_container").css("display","block");
		});

		/* lastname */
		$("#email_container").fadeIn(0, function () {
			$("#email_container").css("display","block");
		});

        /* onlyPerson */
		$(".special_group:first").fadeIn(0, function () {
			$(".special_group:first").css("display","block");
		});
		

		$(".company_user_subform:first").fadeIn(0, function () {
			$(".company_user_subform:first").css("display","block");
		});
        

}

/**
 *  @description    : This function displays company signup form. Form is located in "event_signup.tpl" template file.
 *
 *  @author         : Jernej Gololicic
 */
function showCompanySignupForm(){

		/**
		 *  Set proper form display
		 */
		 userOrCompanyForm = 0;

		/**
		 *  Show relevant fields
		 */

		$("#company_number_container").fadeIn(0, function () {
			$("#company_number_container").css("display","block");
		});
		
		$("#tax_yes_no_container").fadeIn(0, function () {
			$("#tax_yes_no_container").css("display","block");
		});

		$("#compay_tax_number_container").fadeIn(0, function () {
			$("#compay_tax_number_container").css("display","block");
		});

		$("#person_title_container").fadeIn(0, function () {
			$("#person_title_container").css("display","block");
		});
		$("#company_firstname_container").fadeIn(0, function () {
			$("#company_firstname_container").css("display","block");
		});
		$("#company_lastname_container").fadeIn(0, function () {
			$("#company_lastname_container").css("display","block");
		});
		$("#company_email_container").fadeIn(0, function () {
			$("#company_email_container").css("display","block");
		});
		$("#company_workplace_container").fadeIn(0, function () {
			$("#company_workplace_container").css("display","block");
		});
		
		$("#company_title_container").fadeIn(0, function () {
			$("#company_title_container").css("display","block");
		});

		$(".add_another_user_button_container").each(function(){
			$(this).fadeIn(0, function () {
				$(this).css("display","block");
			});
		});

		$(".company_user_subform").each(function(){
			$(this).fadeIn(0, function () {
				$(this).css("display","block");
			});
		});

		/**
		 *  Hide relevant fields
		 */
		/* firstname */
		$("#firstname_container").fadeOut(0, function () {
			$("#firstname_container").css("display","none");
		});
		
		/* onlyPerson */
		$("#onlyPerson").fadeOut(0, function () {
			$("#onlyPerson").css("display","none");
		});
		

		/* lastname */
		$("#lastname_container").fadeOut(0, function () {
			$("#lastname_container").css("display","none");
		});

		/* lastname */
		$("#email_container").fadeOut(0, function () {
			$("#email_container").css("display","none");
		});
		/* lastname */
		$("#workplace_container").fadeOut(0, function () {
			$("#workplace_container").css("display","none");
		});
}

/**
 *  @description    :   This function attaches new form for adding new user to the event.
 *
 *  @author         :   Jernej Gololicic
 */
function attachAnotherUser(clickElement){
	/**
	 *  Create form
	 **/
	// simon start
	var $formObj= $(clickElement).parent().parent();
	$formObjClone= $formObj.clone(true);
	var counterRadioBox = 0;
	$formObjClone.find("input").each(function(){
	    if ($(this).attr("type") != "radio" && $(this).attr("type") != "checkbox") {
		    $(this).attr("value","");
	    }
	    else {
            $(this).attr("checked","");
        }
	    
	    if ($(this).attr("type") == "radio" && counterRadioBox == 0) {
            $(this).attr("checked","checked");
            counterRadioBox++;
        }
        
        if ($(this).attr("type") == "radio" || $(this).attr("type") == "checkbox") {
            var num = $("div[class='special_group']").size();
            $formObjClone.find("label[for='"+$(this).attr("id") + "']").attr("for", "specialr_" + $(this).attr("value") + "_" + num);
            $(this).attr("name", $(this).attr("name") + "_" + num)
                   .attr("id", "specialr_" + $(this).attr("value") + "_" + num); 
        }
        
        
    });
	// simon end
	
	//var userFormHtml = $(".company_user_subform").html(); // simon
	var userFormHtml = $formObjClone; // simon
	var numberOfSubForms = $(".company_user_subform").length;

	//userFormHtml = "<div class='company_user_subform' style='display:none'>"+userFormHtml+"</div>"; // simon

	$("#user_company_signup_form").append(userFormHtml);

	$(".company_user_subform").each(function(i){
		$(this).attr("id","company_user_subform_"+i);
	});

	/**
	 *  Remove "add new user" button from all but last form
	 */
	$(".company_user_subform").each(function(i){
		$(this).attr("id","company_user_subform_"+i);
	});


	/**
	 *  FadeIn newely created form
	 */
	$("#company_user_subform_"+numberOfSubForms).fadeIn("1000");

	/**
	 *  Manage add and remove buttons.
	 */
   userFormButtonManager();
}

/**
 *  @description    :   This function removes particular user date from main form.
 *
 *  @author         :   Jernej Gololicic
 */
function detachThisUser(_object){

	/**
	 *  Find out parent. Structure is as follows : div > div > label (this)
	 */
	var objectParent = $(_object).parent().parent();
	objectParent.fadeOut(400, function(){
		objectParent.remove();

		$(".company_user_subform").each(function(i){
			$(this).attr("id","company_user_subform_"+i);
		});


		/**
		 *  Manage add and remove button
		 */
		userFormButtonManager();
	});
}

/**
 *  @description    :   This function counts user forms attached to the company signup form and manages add and remove buttons.
 *                      If there are two or more user forms, every form must have add and remove button. If there is only one
 *                      user form only add button must be present according that at least one user must be attached to the event.
 *
 *                      add another user button must have "add" class applied, and remove user form must have "remove" class
 *                      applied.
 *  @author         :   Jernej Gololicic
 */
function userFormButtonManager(){
    //alert("das");

	/**
	 *  count user forms
	 */
	var companyUserSubforms = $(".company_user_subform");
	var numCompanyUserSubform = companyUserSubforms.length;
	var formElement = null;
	var formIteration = 0;

	companyUserSubforms.each(function(i){
		formIteration = i;
		formElement = $(this).children();
		formElement.each(function(){

			var inputElement = $(this).children();

			inputElement.each(function(i){
			
				/**
				 *  Rename all input form ids
				 */
				if ($(this).attr("name")) {
					var newElementId = $(this).attr("name") +"_"+ formIteration;
					$(this).attr("id", newElementId);
				}
				else if ($(this).attr("id") == "add_another_user_button_container") {
					$(this).children(".remove").css("display","inline");
					$(this).children(".remove_line").css("display","inline");
					$(this).children(".add").css("display","inline");
				}
			});
		});
	});

	/**
	 *  Disable remove button if only one subform is displayed
	 */
	if (numCompanyUserSubform == 1) {
		$("#add_another_user_button_container").children(".remove").css("display","none");
		$("#add_another_user_button_container").children(".remove_line").css("display","none");
	}
	/**
	 *  Enable all buttons throughout the form
	 */
	else {
        $(".add_another_user_button_container").each(function(){
			$(this).children(".remove").css("display","inline");
			$(this).children(".remove_line").css("display","inline");
		});
	}
	
	
	if ($(".labels").size() > 1) {
       $("label.remove_line").show();
       $("label.remove").show();
    }
	
	

}
/**
 *  @description:   This function valiadtes data enter by user.
 *
 *  @param array fieldNames 	: 	Array containing names of the fields to validate.
 *  @param array fieldTypes 	:   Array containing types of data that supose to be entered into fields.
 *  @param array required   	:   Array of boolean values telling which field is required and which is optional.
 *  @param array combineWith    :   Array containing label id names, to combine validation coloring with. For example:
 *                                  if value of field at first position is not valid and field value at some other position is valid
 *                                  and both fields share the same preceeding text label, second field overwrites first field.
 *                                  Usualy used for post_number following by post_name;
 *  @param array/strinmg colorTrue  : Array or string representing color of field preceeding label when field data is valid.
 *  @param array/strinmg colorFalse : Array or string representing color of field preceeding label when field data is not valid.
 *
 *  @returns                : Function return true if entered data is proper, otherwise it return false.
 *
 *  @author         		:   Jernej Gololicic
 */
function validateUserForm(fieldNames, fieldTypes, required, label, colorTrue, colorFalse){

	/**
	 *  Return this value
	 */
	var returnValue = true;

	for (var i in fieldNames) {
	    //alert("field name = "+fieldNames[i]+"; required = "+ required[i]);
		if (required[i]) {
			switch ( fieldTypes[i] ) {
				case "string"   :   {
										var stringValue = $("#"+fieldNames[i]).val();
										if (stringValue && trim(stringValue) != "" ) {
                                         	colorPreceedingLabel(label[i], "black");
											returnValue &= true;
										}
										else {
	                                        colorPreceedingLabel(label[i], "red");
											returnValue &= false;
										}
										break;
									}
				case "integer"  :   {
										var intValue = $("#"+fieldNames[i] ).val();
										if ( isInteger(intValue) ) {
										
                                            colorPreceedingLabel(label[i], "black");
											returnValue &= true;
										}
										else {
	                                        colorPreceedingLabel(label[i], "red");
											returnValue &= false;
										}
										break;
									}
				case "email"	:   {
										var emailValue = $("#"+fieldNames[i] ).val();
										if ( isEmail(emailValue) ) {
										
                                            colorPreceedingLabel(label[i], "black");
											returnValue &= true;
										}
										else {
	                                        colorPreceedingLabel(label[i], "red");
											returnValue &= false;
										}
										break;
									}
			}

		}
	}
	return returnValue;
}
/**
There is an annoying exception when selection multiple elements based on a name. If number of returned elements equals 1,
it is still possible, that id has indexer applied to it. This function determines, whether that's true.
*/
function hasIndexer(element)
{
	return element.search(/\d+$/) > -1;
}
/**
 *  @description:   This function valiadtes data enter by user.
 *
 *  @param array fieldNames 	: 	Array containing names of the fields to validate.
 *  @param array fieldTypes 	:   Array containing types of data that supose to be entered into fields.
 *  @param array required   	:   Array of boolean values telling which field is required and which is optional.
 *  @param array combineWith    :   Array containing label id names, to combine validation coloring with. For example:
 *                                  if value of field at first position is not valid and field value at some other position is valid
 *                                  and both fields share the same preceeding text label, second field overwrites first field.
 *                                  Usualy used for post_number following by post_name;
 *  @param array/strinmg colorTrue  : Array or string representing color of field preceeding label when field data is valid.
 *  @param array/strinmg colorFalse : Array or string representing color of field preceeding label when field data is not valid.
 *
 *  @returns                : Function return true if entered data is proper, otherwise it return false.
 *
 *  @author         :   Jernej Gololicic
 */
function validateCompanyForm(fieldNames, fieldTypes, required, label, colorTrue, colorFalse){

	/**
	 *  Return this value
	 */
	var returnValue = true;

	for (var i in fieldNames) {
		//alert("field name = "+fieldNames[i]+"; required = "+ required[i]);
		if (required[i]) {
		      //alert("field name = "+fieldNames[i]+"; required = "+ required[i]);
			switch ( fieldTypes[i] ) {
				case "string"   :   {
										var fieldLength = $("input[name="+fieldNames[i]+"]").length;
										//alert("fieldLength" + fieldLength +"\nfieldName" + fieldNames[i]);
										    //if (fieldLength >= 1 && hasIndexer($("input[name="+fieldNames[i]+"]").attr("id"))) {
										    if (fieldLength > 1 ) {
												
												for(var index=0; index <= (fieldLength-1); index++){

													var stringValue = $("#"+fieldNames[i]+"_"+index).val();
													if (stringValue && trim(stringValue) != "" ) {
														
			                                         	colorPreceedingLabel(label[i]+"_"+index, "black");
														returnValue &= true;
													}
													else {
				                                        colorPreceedingLabel(label[i]+"_"+index, "red");
														returnValue &= false;
														//alert("field name = "+fieldNames[i]+"\nrequired = "+ required[i]+"\nlabel = "+label[i]+"_"+index);
													}
												}
											}
											else {

												var labelName = label[i];
												var fieldName = fieldNames[i];
												var stringValue = $("#"+fieldName).val();

												if (stringValue && trim(stringValue) != "" ) {
		                                         	colorPreceedingLabel(labelName, "black");
													returnValue &= true;
												}
												else {
												
													var stringValue = $("#"+fieldName+"_0").val();
													if (stringValue && trim(stringValue) != "" ) {
			                                         	colorPreceedingLabel(labelName, "black");
														returnValue &= true;
													}
													else {
				                                        colorPreceedingLabel(labelName, "red");
														returnValue &= false;
														//alert("field name = "+fieldNames[i]+"\nrequired = "+ required[i]+"\nlabel = "+labelName);
													}
												}
											}

										break;
									}
				case "integer"  :   {

										var intValue = $("#"+fieldNames[i] ).val();
										if ( isInteger(intValue) ) {

                                            colorPreceedingLabel(label[i], "black");
											returnValue &= true;
										}
										else {
											var intValue = $("#"+fieldNames[i]+"_0" ).val();
											if ( isInteger(intValue) ) {

	                                            colorPreceedingLabel(label[i], "black");
												returnValue &= true;
											}
											else {
		                                        colorPreceedingLabel(label[i], "red");
												returnValue &= false;
												//alert("field name = "+fieldNames[i]+"\nrequired = "+ required[i]+"\nlabel = "+label[i]+"_"+index);
											}
										}
										break;
									}
				case "email"	:   {
				                        var fieldLength = $("[name="+fieldNames[i]+"]").length;
											//if (fieldLength >= 1 && hasIndexer($("[name="+fieldNames[i]+"]").attr("id"))) {
											if (fieldLength > 1 ) {

					                            for (var index = 0; index < fieldLength; index++) {
													var emailValue = $("#"+fieldNames[i]+"_"+index ).val();
													if ( isEmail(emailValue) ) {
			                                            colorPreceedingLabel(label[i]+"_"+index, "black");
	 													returnValue &= true;
													}
													else {
				                                        colorPreceedingLabel(label[i]+"_"+index, "red");
	 													returnValue &= false;
														//alert("field name = "+fieldNames[i]+"\nrequired = "+ required[i]+"\nlabel = "+label[i]+"_"+index);
													}
												}
											}
											else {
												var emailValue = $("#"+fieldNames[i] ).val();
												if ( isEmail(emailValue) ) {
		                                            colorPreceedingLabel(label[i], "black");
	 												returnValue &= true;
												}
												else {
												
													var emailValue = $("#"+fieldNames[i]+"_0" ).val();
													if ( isEmail(emailValue) ) {
														colorPreceedingLabel(label[i], "black");
														returnValue &= true;
													}
													else {
				                                        colorPreceedingLabel(label[i], "red");
		 												returnValue &= false;
														//alert("field name = "+fieldNames[i]+"\nrequired = "+ required[i]+"\nlabel = "+label[i]+"_"+index);
													}
												}
											}
// 										}
										break;
									}
			}

		}
	}
	return returnValue;
}

/**
 *  @description    :   Function validates person of company data and if data is valid it makes ajax call and sends data to database.
 *  @author         :   Jernej Gololicic
 */
function signUpUserOrCompany(update) {

    var checkBox = "";
    var radioBox = "";
    var counter = 0;
    
    if($("div[class='special_group']").size()) {
        $("body").find("div[class='special_group']").each(
            function() {
                checkBox += counter+"|";
                radioBox += counter+"|";                
                $(this).find("input").each(
                    function() {
                        if ($(this).attr("type") == "radio" && $(this).attr("checked")) {
                            radioBox +=   $(this).val() + ".";          
                        }
                        else if ($(this).attr("type") == "checkbox" && $(this).attr("checked")) {
                            checkBox +=   $(this).val() + ".";      
                        }
                    }
                );
                checkBox += ";";
                radioBox += ";"; 
                counter++;
            });
    }
    
    if (checkBox != "" || radioBox != "") {
        $.post("/si/ajax/", { cb_box: checkBox, ra_box: radioBox },
            function(data) {
                //alert(data);
            });
    }
    //signUpUserOrCompany
    //alert(checkBox);
    //alert(radioBox);
    

	/**
	 *  The overloaded value of update is one
	 */
	if (!update) {
		
	    update = -1;
	}

	var validated 	= true;
	var lang_id		= $("#lang_id").val();
	
	

	/**
	 *	Determine validation method user/company
	 */
	if ( userOrCompanyForm == 1 ) {
	
		//alert("user validation settings");
		/**
		 *  User fields to validate
		 */
		// simon START
		/* fieldNames 	= new Array("firstname", "lastname",	"email", 	"workplace",	"address",	"post_number",	"post_name","phone","person_comment","fax","event_id");
		fieldTypes 	= new Array("string",	"string",		"email",	"string", 		"string",	"integer",		"string",	"integer","string","string","integer");
		required   	= new Array(true,		true, 			true,		true,			true,		true,			true,		true, 	false, false,true); */
		fieldNames 	= new Array("firstname", "lastname",	"email", 	"address",	"post_number",	"post_name","phone",	"person_comment",	"fax",		"event_id", "workplace");
		fieldTypes 	= new Array("string",	"string",		"email",	"string",	"integer",		"string",	"string",	"string",			"string",	"integer",	"string");
		required   	= new Array(true,		true, 			true,		true,		true,			true,		true, 		false, 				false,		true,		false);
		// simon END
		
		colorTrue   = "black";
		colorFalse  = "red";
		// simon START
		/* label		= new Array("firstname_text_label","lastname_text_label","email_text_label","workplace_text_label",
								"address_text_label","post_number_text_label","post_name_text_label",
								"phone_text_label","person_comment_text_label","fax_text_label","tax_person_text_label","tax_person_text_label"); */						
		label		= new Array("firstname_text_label","lastname_text_label","email_text_label","address_text_label","post_number_text_label","post_name_text_label",
								"phone_text_label","person_comment_text_label","fax_text_label","tax_person_text_label","tax_person_text_label","workplace_text_label");
		// simon END
	
		validated &= validateUserForm(fieldNames, fieldTypes, required, label, colorTrue, colorFalse);
		
	}
	else if ( userOrCompanyForm == 0 ) {
		//alert("company validation settings");
		/**
		 *  Company fields to validate
		 */
		/* fieldNames 	= new Array("company_title","address","post_number","post_name", "company_number","company_tax_number","phone", "company_firstname","company_lastname","company_user_email","company_user_workplace", "fax", "person_comment",
								"person_title", "company_firstname","company_lastname","company_user_email");
		fieldTypes 	= new Array("string", "string", "integer", "string", "string","string","integer", "string", "string", "email", "string", "string","string",
								"integer","string","string","email");
		required   	= new Array(true, true, true, true, true, true, true, true, true, true, true, false, false,
								false,true,true,true); */
		fieldNames 	= new Array("company_title",	"address",	"post_number",	"post_name", 	"company_number",	"company_tax_number",		"phone", 	"fax", 		"person_comment",	"person_title", 	"company_firstname",	"company_lastname",		"company_user_email",	"company_user_workplace");							
		fieldTypes 	= new Array("string", 			"string", 	"integer", 		"string", 		"string",			"string",					"string", 	"string", 	"string", 			"string", 			"string", 				"string",				"email",				"string"				);
		required   	= new Array(true, 				true, 		true, 			true, 			true, 				true, 						true, 		false, 		false, 				false, 				true, 					true, 					true,					false					);
		
		colorTrue   = "black";
		colorFalse  = "red";
		label		= new Array("company_title_text_label", "address_text_label", "post_number_text_label", "post_name_text_label", "company_number_text_label", "company_tax_number_text_label",
								"phone_text_label","fax_text_label","person_comment_text_label",
								"person_title_text_label","company_firstname_text_label","company_lastname_text_label","company_user_email_text_label","company_user_workplace_text_label");

	
		validated &= validateCompanyForm(fieldNames, fieldTypes, required, label, colorTrue, colorFalse);
        
	}
	/**
	 *  Submit
	 */
	if (validated) {

		var submitString = "update="+update+"&signupUserCompany=" + userOrCompanyForm;
		for (var i in fieldNames) {
		    // check if there are many fields with this field name
		    if ($("input[name="+fieldNames[i]+"]").length > 1) {
		    
		        $("input[name="+fieldNames[i]+"]").each(function(i){
		            submitString += "&" + $(this).attr("id") + "=" + urlencode($(this).val());
				});

			}
			/**
			 * Select boxes for person titles
			 */                   			
            else if ($("select[name="+fieldNames[i]+"]").length > 1) {
		    
		        $("select[name="+fieldNames[i]+"]").each(function(i){
		            submitString += "&" + $(this).attr("id") + "=" + $(this).val();
				});
                  
			}
			else {
				  
			    // input field and textarea values
			    if ( $("#"+fieldNames[i]).val() ) {
				
					submitString += "&"+fieldNames[i]+"="+urlencode($("#"+fieldNames[i]).val());
				}
				else if ($("#"+fieldNames[i]+"_0").val()) {
					submitString += "&"+fieldNames[i]+"="+urlencode($("#"+fieldNames[i]+"_0").val());
				}
			}
		}
		// additionl just for company
		if (userOrCompanyForm == 0) {
			submitString += "&tax=" + $("input[name='tax_person']:checked").val();
		}
		submitString+= "&id_event="+ $("#event_id").val();
		/**
			Fetch special fields...
		*/
		/*$("[id^=signupevent_special]").each(function() {
			submitString+= "&" + $(this).attr("id");
		})*/
		/**
		 *  Send data with Ajax
		 */
		 //alert("/"+lang_id+"/ajax/");
		$.ajax({
			type	: "POST",
			url		: "/"+lang_id+"/ajax/",
			data	: submitString,
			async	: true,
			success: function(id){
				/**
				 *  Redirect to the edit/submit page
				 */

//                         alert($("#event_signup_edit").val()+id+","+userOrCompanyForm);
//alert(id);
				
				//alert($("#event_signup_edit").val()+id+","+userOrCompanyForm);
				window.location = $("#event_signup_edit").val()+id+","+userOrCompanyForm;
			}

		});
	}
}

/**
 *  @description    :   Function turns particular label into color defined as parameter.
 *  @param label    :   Label to apply color on. Label is refered to as id!
 *  @param color    :   Which color to apply on label
 *
 *  @author         :   Jernej Gololicic
 */
function colorPreceedingLabel(label, color){
	
	$("#"+label).css("color",color);
}
/**
 *  @description    :   Function checks if s is integer.
 *  @param mixed s  :   Mixed value to check for integer type.
 *
 *  @ return        :   Function returns true if parameter s is integer.
 */
function isInteger( s ) {
     return !isNaN( parseInt( s ) );
}

/**
 *  @description    :   Function checks if parameter is valid email address.
 *  @param  mixed email :   Mixed value to check for email pattern.
 *
 *  return          :   Function returns true if input parameter is valid email address
 *  @author         :   Jernej Gololicic
 */
function isEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email
   if(reg.test(address) == false) {
      return false;
   }
   return true;
}


/**
 *  @description    :   Removes leading whitespaces
 *  @param value    :   mixed input string
 *
 *  @return         :   Function returns string without leading whitespaces
 *  @author         :   Jernej Gololicic
 */
function lTrim( value ) {

	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");

}

/**
 *  @description    :   Removes ending whitespaces
 *  @param value    :   mixed input string
 *
 *  @return         :   Function returns string without ending whitespaces
 */
function rTrim( value ) {

	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");

}

/**
 *  @description    :   Removes leading and ending whitespaces
 *  @param value    :   mixed input string
 *
 *  @return         :   Function returns string without leading and ending whitespaces
 *  @author         :   Jernej Gololicic
 */
function trim( value ) {
	return lTrim(rTrim(value));
}

/**
 *  @description    :   Company user sign up form has at the bottom two button, add and delete, if there is only one form
 *                      delete buttom must be disabled according to that at least one person must be attached to event.
 *
 *  @author         :   Jernej Gololicic
 */
function disableRemoveUserAtStart(){
	if ( $(".remove") ) {
	    $(".remove").css("display","none");
	}
	if ( $(".remove_line") ) {
	    $(".remove_line").css("display","none");
	}
}
function commentArticleAppend(id){
    //polja za validacijo
    var data =new Array("comment_name", "comment_email", "comment_title", "comment_message"); 
    var prefix_text = "_txt";
    var prefix_error = "_error";
    var validator = true;
    //prevermo ali je vse ok (podatki v formi)
    for(var i = 0; i <= (data.length-1); i++){
        if (trim($("#"+data[i]).val()) == "" || (i == 1 && !isEmail($("#"+data[i]).val()))) {
             validator = false;
            $("#"+data[i]+prefix_text).css("color",     "red");
            $("#"+data[i]+prefix_error).css("display",  "block"); 
        } 
        else {
            $("#"+data[i]+prefix_text).css("color",     "#4C4C4C");
            $("#"+data[i]+prefix_error).css("display",  "none"); 
        }            
    } 
    
    //postamo podatke
    if (validator) {
        $.post("/si/ajax/", {  name: $("#"+data[0]).val(), 
                               email: $("#"+data[1]).val(),
                               title: $("#"+data[2]).val(),
                               message: $("#"+data[3]).val(),
                               book_id: id },
            function(data){
                $("#notification_result").css("color",  "red");
                $("#notification_result").html(data);
            });
       
        /*
         * Izpraznimo še podatke komentar ter naslov
         * { pustimo pa ime in priimek ter mail }          
         */         
        for(var i = 2; i <= (data.length-1); i++){
            $("#"+data[i]).val("");
        }   
    }  
    else {
        //izbrišemo še sporočilo
        $("#notification_result").html("");
    } 
}
function do_postback()
{
	
}


/**
 *  @description    :   Naredi enako višino objektov
 *
 *  @author         :   
 */
function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}
/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element 
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article: 
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px) {
	$(this).each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
		alert(currentTallest)
	});
	return this;
};



/*-------------------------------------------------------------------- 
 * javascript method: "pxToEm"
 * by:
   Scott Jehl (scott@filamentgroup.com) 
   Maggie Wachs (maggie@filamentgroup.com)
   http://www.filamentgroup.com
 *
 * Copyright (c) 2008 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
 * Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
 * Demo: http://www.filamentgroup.com/examples/pxToEm/	 	
 *							
 * Options:  	 								
 		scope: string or jQuery selector for font-size scoping
 		reverse: Boolean, true reverses the conversion to em-px
 * Dependencies: jQuery library						  
 * Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
 *
 * Version: 2.0, 08.01.2008 
 * Changelog:
 *		08.02.2007 initial Version 1.0
 *		08.01.2008 - fixed font-size calculation for IE
--------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({
		scope: 'body',
		reverse: false
	}, settings);
	
	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};	
	
	/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
		For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
		When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
		to get an accurate em value. */
				
	if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){		
			return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };
			
	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};

/*
 * fancybox prelistaj
 */ 
$(document).ready(function() {
	$("a.browse_view_article").fancybox();
});

function urlencode(str) {
	//return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
	return str.replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40').replace(/&/g,'%26').replace(/^\s+|\s+$/g, '');
}

function urldecode(str) {
	return unescape(str.replace('+', ' '));
}



/*
Plugin detection & banner display
*/

var plugin = 0;
var forcheck = false;
if (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
        if (navigator.plugins && navigator.plugins["Shockwave Flash"])
			plugin = 1;
			
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0
   && (navigator.userAgent.indexOf("Windows 95")>=0 || navigator.userAgent.indexOf("Windows 98")>=0 || navigator.userAgent.indexOf("Windows NT")>=0)) {
        document.write('<script language="VBScript"\> \n');
        document.write('on error resume next \n');
        document.write('plugin = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.3")))\n');
        document.write('if ( plugin <= 0 ) then plugin = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.4")))\n');
        document.write('if ( plugin <= 0 ) then plugin = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.5")))\n');
		document.write('//plugin= 1;\n');
        document.write('</script\> \n');
}

function flashBannerStr(bannerName, bannerWidth, bannerHeight, bannerLink, bannerSRC) {
                var BannerLinkEncode;
                bannerLinkEncode = escape(bannerLink);
                s = new String();
                s = s + '<object id="flash'+bannerName+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
                s = s + ' codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,0,0" ';
                s = s + ' id="' + bannerName + '" width="' + bannerWidth + '" height="' + bannerHeight + '"\> \n';
                s = s + ' <param name="movie" value="' + bannerSRC +'?clickthru=' + bannerLinkEncode +'" /> \n';
                s = s + ' <param name="quality" value="high"/> \n';
                s = s + ' <embed src="' + bannerSRC +'?clickthru=' + bannerLinkEncode +'" quality="high" ';
                s = s + ' swLiveConnect="false" width="' + bannerWidth + '" height="' + bannerHeight + '" ';
                s = s + ' type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash">';
                s = s + ' </embed> \n';
                s = s + ' </object>\n';
        return(s);
}


function flashBanner(bannerName,bannerSRC,bannerIMG, bannerWidth, bannerHeight, bannerLink, bannerTarget){
	if ( plugin && bannerSRC!="") {
		document.write(flashBannerStr(bannerName, bannerWidth, bannerHeight, bannerLink, bannerSRC));

	}
	else if (!(navigator.appname && navigator.appname.indexOf("Netscape")>=0 && navigator.appVersion.indexOf("2.")>=0)){
		if (bannerTarget == false) {
			cTarget = "";
		} else {
			cTarget = 'onclick="this.target=\'_blank\'"';
		}
		
		if (bannerWidth > 0) {
			cWidth  = "width:" + bannerWidth + "px;";
		} else {
			cWidth = "";
		}

		if (bannerHeight > 0) {
			cHeight = "height:" + bannerHeight + "px;";
		} else {
			cHeight = "";
		}
		
		cStyle = "style=\"border:none;" + cWidth + cHeight + "\"";

		document.write('<a href="' + bannerLink + '" ' + cTarget + '><img src="' + bannerIMG + '" ' + cStyle + ' alt="" /></a>');
	}
}
function sendEventQuestion(nEventId)
{
var validated 	= true;
var lang_id		= $("#lang_id").val();
fieldNames 	= new Array("question_title", "question_description",	"question_author", 	"question_email");
fieldTypes 	= new Array("string", "string", "string", "email");
required   	= new Array(true, true, true, true);
colorTrue   = "black";
colorFalse  = "red";
label		= new Array("question_title_text_label","question_description_label","question_author_text_label","question_email_text_label");
validated &= validateUserForm(fieldNames, fieldTypes, required, label, colorTrue, colorFalse);

if (validated) {
	var submitString = "event_question="+nEventId;
	for (var i in fieldNames) {
		if ($("input[name="+fieldNames[i]+"]").length > 1) {
			$("input[name="+fieldNames[i]+"]").each(function(i){
				submitString += "&" + $(this).attr("id") + "=" + urlencode($(this).val());
			});
		}
		else if ($("select[name="+fieldNames[i]+"]").length > 1) {
			$("select[name="+fieldNames[i]+"]").each(function(i){
				submitString += "&" + $(this).attr("id") + "=" + $(this).val();
			});
		}
		else {
			if ( $("#"+fieldNames[i]).val() ) {
				submitString += "&"+fieldNames[i]+"="+urlencode($("#"+fieldNames[i]).val());
			}
			else if ($("#"+fieldNames[i]+"_0").val()) {
				submitString += "&"+fieldNames[i]+"="+urlencode($("#"+fieldNames[i]+"_0").val());
			}
		}
	}
	$.ajax({
		type	: "POST",
		url		: "/"+lang_id+"/ajax/",
		data	: submitString,
		async	: true,
		success: function(messagetxt){
			$(".login_container").hide();
			$(".text_container").html(messagetxt);
		}
	});
}
}
function toggleDisplay(targetContainerId)
{
	$("#" + targetContainerId).slideToggle("fast");
}
function gotoSelected()
{
	window.location = $("a[rel=goto_" + currentRel + "]").attr("href");
}
function setCurrentRel(rel)
{
	currentRel = rel;
}

function insertIt() {
	$("iframe#tree").attr("height", tree.document.body.scrollHeight)
} 

