// global cookie options
cookieOptions = { path: '/', expires: 90 };


$(document).ready(function() {initDocument()});
		
		
function initDocument() {
	
	mainmenu();
	
	$(".backButton").click(function(){
		var backUrl = $(this).attr("url");
		if (backUrl!=null && backUrl!="undefined"){
			window.location = backUrl;
		}
	});
	
	$(".selectSubcheckboxes1").click(function(){
		var subs = $(this).parent().parent().parent().parent().find("input[type=checkbox]");
		if ($(this).attr('checked')){
			subs.attr('checked', true);
			subs.attr('disabled', true);
		} else {
			subs.attr('checked', false);
			subs.attr('disabled', false);
		}
		$(this).attr('disabled', false);
	});
	
	var $chargeDialog = $('<div></div>')
		.html('<p>You will be charged by 1 credit. Are you sure?</p>'
			+'<p class="info">You can turn these alerts off on the Edit profile page.</p>');
	
	var $emptyDialog = $('<div></div>').html('<h1>Loading...</h1>');
	
	$(".chargeConfirmation").click(function(){
		var redirUrl = $(this).attr("href");
		$chargeDialog.dialog({
			//bgiframe: true,
			title: 'Confirmation',
			resizable: false,
			draggable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				Ok: function() {
					window.location.replace(redirUrl);
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function(event, ui) {
				$(this).dialog('destroy');
			}
		});
		return false;
		
	});
	
	var $modalDialogContent = $('<div></div>');
	$(".showModalDialogContent").click(function(){
		var redirUrl = $(this).attr("href");
		redirUrl = redirUrl + "/nolayout/1";
		$emptyDialog.load(redirUrl).dialog({
			//bgiframe: true,
			title: 'Confirmation',
			resizable: false,
			draggable: false,
			height:500,
			width:700,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			},
			close: function(event, ui) {
				$(this).dialog('destroy');
			}
		});
		return false;

	});
	
	var $noCreditsLeftDialog = $('<div></div>')
	.html('	<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 5px 0;"></span>You have no credits left!</p>');
	
	$(".noCreditsLeftDialog").click(function(){
		$noCreditsLeftDialog.dialog({
			//bgiframe: true,
			title: 'Need to log in',
			resizable: false,
			draggable: false,
			height:140,
			modal: true,
			overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			/*"Add credits": function() {
			window.location  = "/member/credits"
			},*/
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function(event, ui) {
			$(this).dialog('destroy');
		}
		});
		return false;
		
	});
	
	var $notLoggedDialog = $('<div></div>')
		.html('	<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 5px 0;"></span>You need to be logged in!</p>');

	$(".notLoggedConfirmation").click(function(){
		$notLoggedDialog.dialog({
			//bgiframe: true,
			title: 'Need to log in',
			resizable: false,
			draggable: false,
			height:120,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Login": function() {
				window.location  = "/user/login"
				},
				"Register": function() {
					window.location  = "/user/register"
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function(event, ui) {
				$(this).dialog('destroy');
			}
		});
		return false;

	});
	

	$(".TextInput,.ui-autocomplete-input").focus(function() {

         // Destroy currrent tooltip if present
         if($(this).data("qtip")) $(this).qtip("destroy");

         tooltipContent = $(this).parent().next(".description").text();
         if (tooltipContent==""){
             tooltipContent = $(this).next(".description").text();
             if (tooltipContent==""){
             	return;
             }
         }
         $(this).html("leftMiddle") // Set the links HTML to the current opposite corner
            .qtip({
               content: tooltipContent, // Set the tooltip content to the current corner
               position: {
                  corner: {
                     tooltip: "leftMiddle", // Use the corner...
                     target: "rightMiddle" // ...and opposite corner
                  }
               },
               show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
               },
               hide: {
					when: {
						target: $(this),
						event: 'blur' }
               },
               style: {
                  border: {
                     width: 5,
                     radius: 5,
                     color: '#018bba'
                  },
                  padding: 5, 
					background: '#003466',
					textAlign: 'left',
                  tip: true, // Give it a speech bubble tip with automatic corner detection
                  name: 'dark' // Style it according to the preset 'cream' style
               }
            });
	});
	
	

	

}

/**
 * Primary menu function
 */
function mainmenu(){
	$(" #menuholder ul ul ").css({display: "none"}); // Opera Fix
	$(" #menuholder > ul > li:not(.active)").hover(function(){
			$(this).find('ul:first').css({display: "block"}).show();
			$("li.active ul").css({display: "none"}).hide();
			},function(){
			$(this).find('ul:first').css({display: "none"});
			$("li.active ul").css({display: "block"}).show();

			});
	$(" #menuholder li.active ul").css({display: "block"}).show();
	
	}
	 
/**
 * Show confirmation dialog
 */	
function confirmDelete(text){
	if (text==null)
		text = 'Do you really want delete that item?';
	return confirm(text);
}

/**
 * Get all (except submit and empty values) form fields
 * and redirect to the proper ZF rewriten url
 */ 
formRewriteFunction = function() {
	returnStr = '';
	for(var i=0; i < this.elements.length; i++){
		if (this.elements[i].value==''
			|| this.elements[i].value==0
			|| this.elements[i].type=='submit')
			continue;
		var encodeValue = this.elements[i].value.replace(/\//g,"%2F");
		var encodeValue = $.URLEncode(encodeValue);
		
		returnStr += '/';
		returnStr += this.elements[i].name;
		returnStr += '/';
		returnStr += encodeValue;


	}

	searchUrl = this.action;
	document.location = searchUrl + returnStr;
	return false;
}


/*** ACTIVITY TYPES ***/


getParentId = function(childId){
	if (activityTypes[childId]==null || activityTypes[childId]["ActivityTypeParentID"]==null){
		return 0;
	} else {
		return activityTypes[childId]["ActivityTypeParentID"];
	}
}
setActiveSelect = function(el){
	$("select[name='"+activeSelectName+"']").removeAttr("name");
	el.attr("name", activeSelectName);
	el.removeClass("activityParents");
}



createSelectAfter = function(parent, currentBranch, selectedActivityId, parentId){
	var newSelectId = selectParentsNamePrefix+parentId;

	parent.append(getNewSelect(currentBranch, selectedActivityId, newSelectId)
			.fadeIn("fast"));

	createSelectOptions(newSelectId, currentBranch, selectedActivityId);

	appSelects.selectsArrAdd(newSelectId, "0");
	$("#"+newSelectId).change(selectChangeFunction);
	return newSelectId;

}
getNewSelect = function(currentBranch, selectedActivityId, newSelectId){
	var selectIdNum = getParentId(selectedActivityId);
	newEl = $("<select></select>").attr("id",newSelectId)
		.addClass("SelectInput").addClass("activityParents").attr("size", 5);
	return newEl;
}

createSelectOptions = function(newSelectId, currentBranch, selectedActivityId){
	var selectedActivityParentID = getParentId(selectedActivityId);

	var currentText = "";
	var currentOption = null;
	$.each(currentBranch, function(key,element) {
		$('#'+newSelectId).append($("<option></option>").attr("value",key).text(element["ActivityTypeName"]));
	});
	if (selectedActivityId>0){
		$('#'+newSelectId+' option[value='+selectedActivityId+']').attr('selected', 'selected');
	} else {
		$('#'+newSelectId+' option:first').attr('selected', 'selected');
	}
	
}

makeArray = function(currentParent){
	var returnArr = {};
	var childs;
	$.each(activityTypes, function(key,element) {
		if (currentParent==element["ActivityTypeParentID"]){
			
			returnArr[element["ActivityTypeID"]] = element;
			childs = makeArray(key);
			//if (childs!==false){
				returnArr[element["ActivityTypeID"]]["items"] = childs;
			//}
		}
	});
	if (returnArr.length<1){
		return false;
	} else {
		return returnArr;
	}
}

showSubelements = function(branchArray, selectedId){
	if (branchArray==false){
		return false;
	}
	$.each(branchArray, function(key,element) {
		if (element["items"]!=false && element["items"]!=null && element["items"]!=0){
			//showSubelements(element["items"], selectedId);
		}
		return false;
	});
	var newSelectId = createSelectAfter(selectsContainer, branchArray, 0, selectedId);
	setActiveSelect($("#"+newSelectId));
}

getSubbranch = function(branch, elementId){
	var returnValue = false;
	$.each(branch, function(key,element) {
		if (element["ActivityTypeParentID"]==elementId){
			returnValue = branch;
			return false;
		} else {
			if (element["items"]!=null){
				if (returnValue = getSubbranch(element["items"], elementId)){
					return false;
				}
			}
		}
	});
	return returnValue;
}

getSameBranch = function(branch, elementId){
	var returnValue = false;
	$.each(branch, function(key,element) {
		if (element["ActivityTypeID"]!=null && element["ActivityTypeID"]==elementId){
			returnValue = branch;
			return false;
		} else {
			if (element["items"]!=null){
				if (returnValue = getSameBranch(element["items"], elementId)){
					return false;
				}
			}
		}
	});
	return returnValue;
}

getStartingList = function(selectedId) {
	var currenParrentId = activityTypes[selectedId]["ActivityTypeParentID"];


	$.each(activityTypes, function(key,element) {
		if (currenParrentId == element["ActivityTypeID"] && currenParrentId!=0){
			getStartingList(element["ActivityTypeID"]);
			return false;
		}
	});
	startingSelects[currenParrentId] = activityTypes[selectedId];

}

showStartingList = function(selectedId) {
	var newSelectId;

	
	$.each(startingSelects, function(key,element) {
		newSelectId = createSelectAfter(selectsContainer, getSameBranch(activityTypesArr, element["ActivityTypeID"]), element["ActivityTypeID"], key);
	});
	setActiveSelect($("#"+newSelectId));
}

selectChangeFunction = function() {
		var afterCurrent = false;
		var currentElId = $(this).attr("id");
		
		selectedValue = $('#'+currentElId+' option:selected').attr('value');

		$.each(appSelects.selectsArr, function(key,element) {
			if (afterCurrent){
				$("#"+element["selectId"]).remove();
				appSelects.selectsArrRemove(key);
			}
			
			if (currentElId==element["selectId"]){
				afterCurrent = true;
				setActiveSelect($("#"+element["selectId"]));
			}
		});
		
		showSubelements(
			getSubbranch(activityTypesArr, selectedValue),
			$("#"+currentElId+" option:selected").val()
		);
			
}

appSelects = {
	"selectsArr" : {},
	"selectsCount" : 0,
	"selectsArrAdd" : function(selectId, elementId) {
		this.selectsArr[this.selectsCount+1] = {"selectId":selectId, "elementId":elementId};
		this.selectsCount++;
		return this.selectsCount;
	},
	"selectsArrRemove" : function(elementId) {
		if (this.selectsCount>0){
			delete this.selectsArr[elementId];
			this.selectsCount--;
		}
	},
	"getBySelectId" : function(elemetnId){
		var returnValue = false;
		$.each(activityTypes, function(key,element) {
			if (element["selectId"]==elemetnId){
				returnValue = element;
				return false;
			}
		});
		return returnValue;
	}
}

activityTypeSelectsSetup = function(fieldName, fieldId){
	/*if ($("#ActivitySubform-ActivityTypeID")!=null){
		selectsContainer = $("#ActivitySubform-ActivityTypeID").parent();
	} else {
		selectsContainer = $("#ActivityTypeID").parent();
	}*/
	if (fieldName==null){
		fieldName="ActivityTypeID";
	}
	if (fieldId==null){
		fieldId="ActivityTypeID";
	}
	selectsContainer = $("#"+fieldId).parent();
	activeSelectName = fieldName;
	selectParentsNamePrefix = "activitySelect";
	
	
	activityTypesArr = {};
	activityTypesArr = makeArray(0);
	
	// get current activity type
	var selectedActivityType = null;
	$.each(activityTypes, function(key,element) {
		if (element["IsSelected"]==1){
			selectedActivityType = key;
			return false;
		}
	});
		
	// remove old form field
	$("#"+fieldId).remove();
	
	startingSelects = {};
	getStartingList(selectedActivityType);
	showStartingList(selectedActivityType);
	

	appSelects.selectsArrAdd(activeSelectName, "0");


	$("#"+activeSelectName).change(selectChangeFunction);
	$(".activityParents").change(selectChangeFunction);
}

$("#AreaID").change(function() {
	selectedArea = this.options[this.selectedIndex].value;
	var countriesSelect = $("#CountryID")[0];

	for(i=1;i < countriesSelect.length;i++){
		var currEl = countriesSelect.options[i];
			currEl.style.display='';
	}
	if (selectedArea!=0){
		countriesSelect.options[0].selected="selected";
		for(i=1;i < countriesSelect.length;i++){
			var currEl = countriesSelect.options[i];
			var currElValue = currEl.value;
			var currElAreaID = currElValue.substr(0, currElValue.indexOf('_'));
			if (currElAreaID != selectedArea){
				currEl.style.display='none';				
			}
		}
	}
});

/**
 * urlencode
 * http://plugins.jquery.com/project/URLEncode
 */ 
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
while(x<c.length){var m=r.exec(c.substr(x));
  if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
  }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
  o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

function nl2br (str, is_xhtml) {
    // Converts newlines to HTML line breaks  
    // 
    // version: 911.1619
    // discuss at: http://phpjs.org/functions/nl2br    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');    // *     returns 1: 'Kevin\nvan\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '\nOne\nTwo\n\nThree\n'
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';
 
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

/*** *** ***/


// POPUP JQUERY PLUGIN
// http://swip.codylindley.com/popupWindowDemo.html
(function($){ 		  
	$.fn.popupWindow = function(instanceSettings){
		
		return this.each(function(){
		
		$(this).click(function(){
		
		$.fn.popupWindow.defaultSettings = {
			centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
			centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
			height:500, // sets the height in pixels of the window.
			left:0, // left position when the window appears.
			location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
			menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
			resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
			scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
			status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
			width:500, // sets the width in pixels of the window.
			windowName:null, // name of window set from the name attribute of the element that invokes the click
			windowURL:null, // url used for the popup
			top:0, // top position when the window appears.
			toolbar:0//, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
			//autoPrint:0 // determines whether to start print dialog
		};
		
		settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
		
		var windowFeatures =    'height=' + settings.height +
								',width=' + settings.width +
								',toolbar=' + settings.toolbar +
								',scrollbars=' + settings.scrollbars +
								',status=' + settings.status + 
								',resizable=' + settings.resizable +
								',location=' + settings.location +
								',menuBar=' + settings.menubar;

				settings.windowName = this.name || settings.windowName;
				settings.windowURL = this.href || settings.windowURL;
				var centeredY,centeredX;
				
				var currentWindow;
			
				if(settings.centerBrowser){
						
					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
					}else{
						centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
						centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
					}
					currentWindow = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else if(settings.centerScreen){
					centeredY = (screen.height - settings.height)/2;
					centeredX = (screen.width - settings.width)/2;
					currentWindow = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else{
					currentWindow = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();	
				}


				return false;
			});
			
		});	
	};
})(jQuery);