/**
 * Concertagenda.nl Javascript
 *
 * @copyright  BliXem Internet Services
 */

/**
 * initMenu. Initializes the main menu and makes it IE6 proof (IE6 does not support hover on list-items).
 */

function initMenu() {
	
	$("#mainMenu > *").mouseover(
		function(){ 
			// adds "over" class to list-item, so that submenu below will become visible
			$(this).addClass(" over"); 
			// call the function positionSubmenu to center the submenu relative to the current list-item
			positionSubmenu(this);	
			// check if this list-item has a submenu
			var hasSub = $(this).children("ul").length;
			// if it has a submenu AND it's not the active menu-item
				if(!$(this).hasClass("on") && hasSub != "0"){ 
					var borderColorActiveLI = $("li.on ul li a").css("borderRightColor");
					$("li.on ul li a").css({color:borderColorActiveLI}); // ...change the submenu color
					}
				})
		
	$("#mainMenu > *").mouseout(
		function(){  ;
			$(this).removeClass(" over"); 
			$("li.on ul li a").css({color:"#FFF"});
			});
	
	}
	

/**
 * initFieldset. Adds the overlay. 
 * @param fieldset FieldsetId
 */

function initFieldset(fieldset){
	var fieldsetHeight = $("#" + fieldset).innerHeight();
	var fieldsetWidth = $("#" + fieldset).outerWidth();
	var fieldsetId = $("#" + fieldset).attr("id");
	// adds a div with the class "overlay", which has the height/width of the fieldset
	$("#" + fieldset)
	.append("<div class='overlay' id='overlay" + fieldsetId + "'></div>")
	.children(".overlay").css({height:fieldsetHeight,width:fieldsetWidth});		
}


/**
 * disableFieldset. Disables the fieldset input elements and hides the overlay.
 * @param fieldsetId: A fieldsetId.
 */

function disableFieldset(fieldsetId){
	$("#" + fieldsetId + " .overlay").css({display:"block"});
	$("#" + fieldsetId + " input").attr("disabled",true);
	$("#" + fieldsetId + " select").attr("disabled",true);
	$("#" + fieldsetId + " button").attr("disabled",true);
	$("#" + fieldsetId + " textarea").attr("disabled",true);
}

/**
 * enableFieldset. Enables the fieldset input elements and hides the overlay.
 * @param fieldsetId: A fieldsetId.
 */

function enableFieldset(fieldsetId){
	$("#" + fieldsetId + " .overlay").css({display:"none"});
	$("#" + fieldsetId + " input").attr("disabled",false);
	$("#" + fieldsetId + " select").attr("disabled",false);
	$("#" + fieldsetId + " button").attr("disabled",false);
	$("#" + fieldsetId + " textarea").attr("disabled",false);
	// focus on the first inputfield, selectbox or textarea
	var found = false; 
	$("#" + fieldsetId + " *").each(function(){
		var type = this.tagName.toLowerCase();
		if(!found){
			if(type == "select" || type == "input" || type == "textarea"){
				$(this).focus();	
				found = true;
			}
		}		
		
	});	
}


/**
 * validateFieldset. Validates the fields in the given fieldset
 * @param fieldset: A DOM element.
 */

function validateFieldset(fieldsetObj) {	
	// reset the values for each field
	$(".formFeedback").removeClass("formFeedbackNegative");
	$(".formFeedback").removeClass("formFeedbackPositive");
	// get the validationruleset
	var debug = $("input[type='hidden'][name='validation-debug']").val();
	debug = (debug != undefined && debug.toLowerCase() == 'true');
	var validationUrl = $("input[name='validation-url']").val();	
	var fieldsetId = fieldsetObj.attr("id");
	var loadingMargin = $("#" + fieldsetId + " .overlay").height()/2 - 25;
	if($("#loading").length == 0){
		$("#" + fieldsetId + " .overlay").css({display:"block"}).append("<div class='loadingOverlay' id='loading'>Een moment geduld...<br /><img src='/images/loading-white.gif' /></div>");
		}
	$("#loading").css({marginTop:loadingMargin + "px"});
	
	// finds all the input fields in this fieldset with the class "validate"
	$("#" + fieldsetId + " .validate").each(function(){
		$(this).prepareValidation($(this), validationUrl, debug);			
	});		
	
	// optional extra validation
	setTimeout(function(){ 
		// check if the standard validation is done
		if($("#" + fieldsetId + " li .formFeedbackNegative").length == 0){			
			var extraValidation = fieldsetId + "validation";
			// check if a function exists with the name of the fieldsetId + "validation" (e.g. "stap1validation").
			if (typeof extraValidation == 'string' && eval('typeof ' + extraValidation) == 'function') {
				eval(extraValidation + '()');
			}
		} else { // if there's an error, hide the overlay
 			$("#" + fieldsetId + " .overlay").css({display:"none"});
		}		 
	},1200);
	}

/**
 * nextFieldset. Shows the next fieldset
 * @param fieldset: A DOM element.
 */
function nextFieldset(fieldsetObj){
	var fieldsetId = fieldsetObj.attr("id");
	var nextFieldsetId = fieldsetObj.next().attr("id");
	var targetOffset = fieldsetObj.next().offset().top;
	if($("#" + fieldsetId + " li .formFeedbackNegative").length == 0){				
		$('html,body').animate({scrollTop: targetOffset}, 1000, function(){
			enableFieldset(nextFieldsetId);
			disableFieldset(fieldsetId);
			$("#loading").remove();
		})
		} else {
			$("#" + fieldsetId + " .overlay").css({display:"none"});
			$("#loading").remove();
		}
	}

			
// Initialize the formValidate object
$.formValidate = {
	init: function(formId){
		var fieldName;	
		var fieldWidth;
		var feedbackId;
		var formValidated = false; 	
		
		// disable the venue selector
		$("#venue").attr("disabled",true);	

		// adds the action to the submit button, which once more checks the whole form
		$("#" + formId).submit(function(){
			$("#" + formId + " input").attr("disabled",false);
			$("#" + formId + " select").attr("disabled",false);
			$("#" + formId + " textarea").attr("disabled",false);
		});	
				
		// adds a span with the id 'formFeedback' + the fieldname of the input to be validated
		$("#" + formId + " .validate").each(function(){ 			
			fieldName = $(this).attr("name");			
			feedbackId = "formFeedback" + fieldName;
			if(!$(this).hasClass("feedback")){ // adds feedback span once
				$(this).css({display:"inline"});				
				$(this).after("<div class='formFeedback' id='" + feedbackId + "'>&nbsp;</div>");
			} 		
		 });
		
		// removes the formFeedback div (if no feedback is required)
		$("#" + formId + " .validateNoComment").each(function(){ // remove fields where no feedback is wanted
			fieldName = $(this).attr("id");	
			feedbackId = "formFeedback" + fieldName;	
			$("#" + feedbackId).remove();
		 });
		
		 // cancel submit button
			$("#" + formId).submit(function(){
				if(!formValidated){
					return false;
				}
			});
			
		// this part of the function generates the various steps the user will see. Each step is a fieldset.
		var counterFieldsets = 0;
		$("#" + formId).children("fieldset").each(function(){ 
			// insert "next"/"previous"  buttons (but remove it from the last section)
			$(this).append("<button type='button' class='prev floatLeft' title='" + counterFieldsets + "'>Terug naar stap " + counterFieldsets +"</button>");
			counterFieldsets++;
			$(this).append("<button type='button' class='next' title='" + (counterFieldsets + 1) + "'>Verder naar stap " + (counterFieldsets + 1) + "</button>");
			initFieldset($(this).attr("id"));
			// next button
			$(this).children(".next").bind("click",function(){
				var fieldsetToShow = $(this).attr("title");
				var fieldsetToValidate = $(this).parent();
				var fieldsetId = $(this).parent().attr("id");
				validateFieldset(fieldsetToValidate);
				setTimeout(function(){ 
					if($("#" + fieldsetId + " input").hasClass("error")){
						$("#" + fieldsetId + " .overlay").css({display:"none"});
						$("#loading").remove();
						return false;
					}
					else {
						nextFieldset(fieldsetToValidate);
					}
				},4000);
			});			
			$(this).children(".submitValidation").bind("click",function(){
				var fieldsetToValidate = $(this).parent();			
				var fieldsetId = $(this).parent().attr("id");
				validateFieldset(fieldsetToValidate);				
				setTimeout(function(){
					if($("#" + fieldsetId + " li .formFeedbackNegative").length == 0){						
						formValidated = true; 
						$("#" + formId).submit(); 
					} else {
						$("#" + fieldsetId + " .overlay").css({display:"none"});
						$("#loading").remove();
						return false;
					}				
				},4000);								
				
			});
			// prev button
			$(this).children(".prev").bind("click",function(){
				var fieldsetToShow = $(this).attr("title");	
				var fieldsetToHide = parseFloat(fieldsetToShow) + 1;							
				// scroll to the previous fieldset	
				var targetOffset = $(this).parent().prev().offset().top;		
				$('html,body').animate({scrollTop: targetOffset}, 1000, function(){					
					enableFieldset("stap" + fieldsetToShow);				
					disableFieldset("stap" + fieldsetToHide);						
				});
			});
		});
			
		// remove the first "prev"/last "next" button of the form
		$("#" + formId + " fieldset:first-child .prev").remove();						
		$("#" + formId + " fieldset:last-child .next").remove();
		$("#" + formId + " fieldset:last-child .prev").insertBefore(".submitValidation");	
		// show the first fieldset, disable the other fieldsets		
		$("#" + formId + " fieldset input").attr("disabled",true);
		$("#" + formId + " fieldset select").attr("disabled",true);
		$("#" + formId + " fieldset button").attr("disabled",true);
		$("#" + formId + " fieldset textarea").attr("disabled",true);
		$("#" + formId + " fieldset:first-child .overlay").css({display:"none"});			
		$("#" + formId + " fieldset:first-child input").attr("disabled",false);
		$("#" + formId + " fieldset:first-child textarea").attr("disabled",false);
		$("#" + formId + " fieldset:first-child select").attr("disabled",false);
		$("#" + formId + " fieldset:first-child .next").attr("disabled",false)		
		$("#" + formId + " fieldset:first-child input:first-child").parent().next().children("input").focus();	
	}
}



/**
 * positionSubmenu. Positions the submenu to the center of the top menu item.
 * @param element: A main menu item (<li>)
 */
 
function positionSubmenu(element){
	
	if(!$(element).hasClass("positioned")){
		var menuID = $(element).attr("id");
		$(element).addClass("positioned"); 									 
		var liWidth = $(element).width();
		// gets the submenu of the current list-item
		var ulSubmenu = $(element).children("ul");
		var ulSubmenuWidth = $(element).children("ul").outerWidth();
		// gets the position from the left side of the screen of this element
		var liPosition = $(element).position();				
		var liLeft = liPosition.left; 
		$(element).children("ul").css({width:ulSubmenuWidth + "px",left: (liLeft + liWidth/2) - ulSubmenuWidth/2 });	
		var ulSubNewLeft = (liLeft + liWidth/2) - ulSubmenuWidth/2; // new left position of submenu
		var subEnd = ulSubNewLeft + ulSubmenuWidth; // new end position of submenu
		var subOverFlowRight = subEnd - 540;

		// if the left side of the submenu overflows the left side of the main menu
		// align the submenu to the left side of the main menu (0)
		if(ulSubNewLeft < 0){
			$(element).children("ul").css({left:"0"});				
		// if the right side of the submenu overflows the right side of the main menu
		// align the submenu to the right side of the main menu (0)
		} else if(subEnd > 550){
			$(element).children("ul").css({marginLeft:"-" + subOverFlowRight + "px"});				
			$("#" + menuID + " ul li a.lastItem").css({backgroundPosition:"bottom right"});
		} 
	}
	
}
	
/**
 * writeColumnCookie. Saves the columnconfiguration in a cookie for 365 days.
 */
 
function writeColumnCookie(){
  var arrayColumns = [];
  $("#containerSet").children(".column").each(function(){ 
		arrayColumns.push($(this).attr("id"));
		});
  $.cookie("concertAgendaColumnCookie", arrayColumns,{ path: '/', expires: 365 });
}

/**
 * writeColumnCookie. Saves the columnconfiguration in a cookie for 365 days.
 */
	  
function readColumnCookie(){  
  var columnOrderCookie = $.cookie("concertAgendaColumnCookie");
	// if cookie is found the above var has been set
	if(columnOrderCookie) 
	var columnOrder = columnOrderCookie.split(",");
	  if(columnOrder){
		  for (var i = 0; i < columnOrder.length; i++){
			  // change the order of the columns
			$("#containerSet").append($("#" + columnOrder[i]));
		  }	
		// remove the class "lastColumn" from every column
		$("#containerSet .column").removeClass("lastColumn");
		// add the class "lastColumn" to the last column
		$("#containerSet .column:last-child").addClass("lastColumn");
	  }			  

	  $("#containerSet .column .moveColumnLeft").css({display:"inline"});
	  $("#containerSet .column .moveColumnRight").css({display:"inline"});
	  $("#containerSet .column:first-child .moveColumnLeft").css({display:"none"});
	  $("#containerSet .column:last-child .moveColumnRight").css({display:"none"});	  
}
	  

/**
 * switchStyleSheet. Switches the active stylesheet. This did not properly work with JQuery, hence this DOM-version. 
 */
 
function switchStylesheet(styleName){
	var i, s;
	for(i=0; (s = document.getElementsByTagName("link")[i]); i++) {
		 if(s.getAttribute("rel").indexOf("style") != -1 && s.getAttribute("title")) {
		   s.disabled = true;
		 if(s.getAttribute("title") == styleName) s.disabled = false;
	 }
	 }
	$.cookie("concertAgendaColorCookie", styleName,{ path: '/', expires: 365 });
}

/**
 * updateTagCloud
 * Adds a tag to the database and returns the new tagcloud
 */
 
function updateTagCloud(tag){			
		var tagType = $("input[name='tagType']").val();
		var tagTypeId = $("input[name='tagTypeId']").val();		
		$("#tagFeedback").addClass("formFeedbackLoading");		
		$.getJSON("/tag/toevoegen", {tag:tag,tagType:tagType,tagTypeId:tagTypeId},function(data){			
		if(data){
			$("#tagFeedback").removeClass("formFeedbackLoading");
			$("#tagFieldCloud").empty();
			$.each(data, function(i,item){				
					$("#tagFieldCloud").append("<li><span><a href='/tag/" + item.seo_name + "' class='tagSize" + item.tagsize + "'>" + item.name + "</a><a href='#' class='addTagProfile' title='" + item.name + "'><img src='/images/add.gif' alt='Tag!' title='Tag!' /></a></span></li>");				
				});			
			$("#tagFieldCloud .addTagProfile").click(function(){
				var tag = $(this).attr("title");		
				updateTagCloud(tag);
				return false;
				});				
			}
		});
		return false;	
	}

	/**
 	* Function to fill the city select box
 	*/
	
	function fillCitySelectBox(province) {
		$.getJSON("/validation/CitiesInProvince/",{province: province}, function(data){
				if(data){
					$("#calendarSelectCity").empty();
					$("#calendarSelectCity").append("<select id='select_city' name='select_city'></select>");
					$.each(data, function(i,item){
						$("#select_city").append("<option value=" + item.id + ">" + item.city_name + "</option>");
					});	
				}
		});	
	}
	
	

/**
 * Functions to initialize document ready
 */

$(document).ready(function(){

	// searchbox 
	$("#searchField").focus(function(){
		$(this).val("");
	}).blur(function(){
		var currentValue = $(this).val();
		if(currentValue == ""){
			$(this).val("Vul je zoekterm in...");
		}
	});
	
	// stars for rating items
	$("#ratingButton").remove();
$('.hover-star').rating({
	callback: function(value, link){
	    this.form.submit();
  },
  focus: function(value, link){
    var tip = $('#hoverText');
    tip[0].data = tip[0].data || tip.html();
 	tip.html(link.title || 'value: '+value);
  },
  blur: function(value, link){
   var tip = $('#hoverText');
   $('#hoverText').html(tip[0].data || '');
  }
});
	
	// init the calendar
	 $("form#calendar").jcalendar();
	// hide the location-selector
	$("#locationPicker ol").hide();
	// add the function to show the locationselectors
	$("#locationPicker span").css({cursor:"pointer"}).click(function(){
		$("#locationPicker ol").slideToggle(500);
		$(this).toggleClass("active");
	});
	// Show the city select-box in the calendarblock (disabled for non-javascript users)
	$("#select_city").attr("disabled",true);
	$("#select_province").change(function(){ 
		var province = $(this).val();
		fillCitySelectBox(province);
	});

	initMenu();
	readColumnCookie();
	Shadowbox.init();
	
	// init the various tabbed content sections
	$("ul.tabbedContentMenu").tabs();
	
	// Tag-field initialize	
	$("input[name='tagField']").autocomplete("/validation/tag/",
		{minChars:2,inputClass:'formAutocomplete',resultsClass:'formAutocompleteResults',onItemSelect:
		function(selectedItem){ 
			$("input[name='tagId']").val(selectedItem.extra);
		}});			
	
	$("#tagFieldCloud .addTagProfile").click(function(){		
		var tag = $(this).attr("title");		
		var tagId = $(this).attr("rel");
		updateTagCloud(tag);
		return false;
	});
	
	$("#tagButton").click(function(){
		var tag = $("input[name='tagField']").val();
		var tagId = $("input[name='tagId']").val();	
		if(tag != ""){
			updateTagCloud(tag);			
		}
		return false;
	});
		
	// show the tabs/columnmoves. These are hidden for users with no Javascript or Javascript disabled.
	$(".columnMovers").css({ display:"inline" });				

	// Finds all form to be initialized
	$("form.init").each(function(){
			var formId = $(this).attr("id");
			$.formValidate.init(formId);
		  });
								 
	// positions the submenu of the active menu-item
	$("#mainMenu > *").each(function(){
		if ($(this).hasClass("on")){
			  positionSubmenu(this);
			}
	   });
	

	$(".moveColumnRight").click(function()  {
		var nextColumn = $(this).parent().parent().next();
		$(nextColumn).after($(this).parent().parent());				
		$("#containerSet .column").removeClass("lastColumn");
		$("#containerSet .column:last-child").addClass("lastColumn");
	    $("#containerSet .column .moveColumnLeft").css({display:"inline"});
        $("#containerSet .column .moveColumnRight").css({display:"inline"});
		$("#containerSet .column:first-child .moveColumnLeft").css({display:"none"});
		$("#containerSet .column:last-child .moveColumnRight").css({display:"none"});
		$(this).css({color:"#565656"}); // ie7 doesn't remove :hover
		writeColumnCookie();
	});
	  
	$(".moveColumnLeft").click(function()  {		
		var prevColumn = $(this).parent().parent().prev();
		$(prevColumn).before($(this).parent().parent());		
		$("#containerSet .column").removeClass("lastColumn");
		$("#containerSet .column:last-child").addClass("lastColumn");
   		$("#containerSet .column .moveColumnLeft").css({display:"inline"});
  		$("#containerSet .column .moveColumnRight").css({display:"inline"});
		$("#containerSet .column:first-child .moveColumnLeft").css({display:"none"});
  		$("#containerSet .column:last-child .moveColumnRight").css({display:"none"});
		$(this).css({color:"#565656"}); // ie7 doesn't remove :hover
		writeColumnCookie();
	});

	// Actionmessage "remove"-link	
	$("#message a#close").click(function()  {				
		$("#message").hide(function(){
			  $("#message").remove();
			  });		
		return false;
	});

	// Handle the clicks for the styleswitch links at the top of the page
	$("a[rel='styleSwitch']").bind('click', function(){	
		var style = $(this).attr("class");
		switchStylesheet(style);
		return false;
	});	
	
	 // Handle the click on a link with rel=external
	$("a[rel='external']").bind('click', function(){					
		window.open($(this).attr('href'));
		return false;
	});	

	$(".foldOpenLink")
	.each(function(){
		var itemToFold = $(this).attr("title");
		$(this).css({cursor:"pointer"});
		$("#" + itemToFold).css({display:"none"});
	})
	.click(function() {    	 
    	var itemToFold = $(this).attr("title");
		$("#" + itemToFold).toggle();
		return false;
	});
	
	
	$("ul.items").accordion({alwaysOpen:true,event:"click",header:".overviewHeader",animated:false,selectedClass:"active"});
		
	$('.delete').click(function(){
	  var answer = confirm('Definitief verwijderen?');
	  return answer // answer is a boolean
	}); 
});