// GENERIC JQUERY FILE
// CREATED: MARCH 02 2010 (CCA / EPISTEME)

// MODALBOX
function getModal(from) {
		var params = getParams(from);
		var action = params.action;
		var realid = params.id;
		var catid = params.categoryid;
		
		var step = params.step;
		var contactid = params.contactid;
		
		$.ajax({	
			url: "index.php?modal="+action,
			success: function(data) {
				
				$("body").append("<div id='modalback'></div><div id='modalbox'></div>");
				$("#modalbox").html(data);			
				
				//calc x-pos
				var boxwidth = $("#modalbox").width();
				var leftmargin = 0-boxwidth/2;
				$("#modalbox").css("margin-left",leftmargin);
				
				//show
				showModal();
				
				//BINDING
				$(".modalboxclosebtn").click(function() { closeModal(this);	});
				$(".cancelandclose").click(function() { closeModal(this);	});
				
				$("input[name=categoryid]").val(catid);
				$("input[name=id]").val(realid);
				
				if (params.step == 'suserreg') {
					$("input[name=contactid]").val(contactid);
					}
				
				modalBoxBinding();	
			}
		})		
		return false;	
}
	
//SHOW MODALBOX	
function showModal() {
		//IE 6 adjustments 
		if (typeof document.body.style.maxHeight === "undefined") {
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			$("body").append("<iframe id='modalhideselect'>");
			$("#modalhideselect").show();
		}
		
		//all
		$("#modalback").show();
		$("#modalbox").show();
}
	
// REMOVE MODALBOX	
function closeModal(btn) {
		//IE 6 adjustments
		if (typeof document.body.style.maxHeight === "undefined") {
			$("body","html").css({height: "auto", width: "auto"});
			$("html").css("overflow","");
			$("#modalhideselect").remove();
		}
		
		//all
		$("#modalback").remove();
		$("#modalbox").remove(); 
}

//get and export the different steps in user regrestration
function userreg(from) {
	var form = $(from).parents("form");
	var action = form.attr("action");
	var fields = $("input", form).serializeArray();
	
	$.ajax({   
		url: action,	
		data: fields,
		type: "POST",
		beforeSend: function() {
				$("input.userregister").unbind("click");
				
				$("div.modalcontent div.content").animate({opacity:0}, 200);
				$("#ajaxloader").show(); 
				$("a.closeloginbox").fadeOut(100);
			},
		success: function(data) {
					//clone wrapper
					$("div.modalcontent div.content").clone(true).insertAfter("div.modalcontent div.content").hide()
					
					//animate previous and remove
					.prev().animate({opacity:0}, 200, function() { 
						
						$("#ajaxloader").fadeOut(100); }).slideUp(1000, function() { 
							
							$(this).remove();
							$("a.closeloginbox").fadeIn(300);						
							$("div.modalcontent div.content").html(data).css({opacity:1}).show();

							//binding
							stepsBinding();
							
						});//end slide callback
				
				}
			});
}


//MODALBOX BINDING FROM INTPOW
function modalBoxBinding() {// BINDING
		
		//close login dialog
		$(".closemodal").click(function() { closeModal(this); });
		
			$("input#step1reg").click(function() { 
			
				if ($("#email").val().length != 0) { 
					 $(this).removeClass("error");
					 userreg(this); return false;
				} else { 
					$(this).addClass("error"); return false;
				}			
		});
		
		$("input.userregister").click(function() { userreg(this); return false; } );
}

function stepsBinding() {																	  
	
	var formid = $("form","div.modalcontent").attr("id");
	
	if (formid == "createuser") { 
	
		$("input[type=submit]").click(function() {
			$("input.val").each(function(i) { if ($(this).val().length < 3) { $(this).addClass("error"); } else { $(this).removeClass("error"); } });
			if ($("input.val").hasClass("error")) { $("div#createusermsg").show(); return false; }
		});
	
	} else {
		
		$("input.userregister").click(function() { userreg(this); return false; } );
	
	}
	
	$(".closemodal").click(function() { closeModal(this); });
	$("a.submitform").click(function () { $(this).submit(); });
	
	var idet = $("input:radio:checked").attr("id");
	$("input[name=contactid]","form#selectcompany").val(idet); 

	$("input[name=company]","form#selectcompany").click(function() {
							var theid = $(this).attr("id");
							$("input[name=contactid]","form#selectcompany").val(theid);		 
	});
	
	//mark row that is selected with the color green
	$("input[type=radio]","form#selectcompany").click(function() {
			$("tr.selectedrow").removeClass("selectedrow");
			$(this).parent().parent().addClass("selectedrow");
															 });

}

//SuckerFish hover
$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};	

// PARAMETER FUNCTIONS
function getParams(from) {
	var params = {};
	if($(from).attr("params")){
		$.each($(from).attr("params").split(","), function(){		
			var thiskey = this.split(":")[0];
			//var thisval = this.split(":")[1]; 
			// enhanced for url
			var thisval = this.substr(this.split(":")[0].length+1,this.length);
			tmpobj = {};
			eval("tmpobj." + thiskey + "=thisval");
			jQuery.extend(params,tmpobj);	
		});
		return params;
	}
}

//PARAMS TO PATH FUNCTION
function paramsToPath(obj) {
	if(obj) {
		var pairs = [];
		var path = "";
		var del1 = "=";
		var del2 = "&";
		$.each(obj, function(i,val) { 
			if(val!=""){ pairs.push(i+del1+encodeURIComponent(val)); }//values are encoded to pass urls etc. 
		});
		path = pairs.join(del2);
		return path;
	}
}

// PATH FUNCTIONS
function parsePath(searchstring) {
	var crumbs = location.pathname.split("/");
	var nextcrumb = false;
	$.each(crumbs, function(i,val) {
      if(val==searchstring){ 
      	nextcrumb = crumbs[i+1];
      };
    });	
    return nextcrumb;	
}

//CLEAR FIELDS ON FOCUS
function clearOnFocus(obj) {
	var prevtext = $(obj).val();
	var orgtext = $(obj).attr("title");
	
	if ((prevtext != orgtext) && (prevtext != "")) {
		//do nothing...
	} else if(prevtext == "") {
		$(obj).val(orgtext);
	} else {
		$(obj).val("");
	}

}

//TOGGLE REGRESTATION TO AN EVENT
function toggleRegistration(eventid, subeventid, personid, setORdel, userid, id) {
	var action=(setORdel)?"insert":"delete";
	var href="transactions.php?ajax=1&table=subeventparticipation&action="+action+"&personid="+personid+"&eventid="+eventid+"&subeventid="+subeventid+"&userid="+userid+"&id="+id;
	// alert(href);
	$("#blank").load(href);
	// alert(ret);

}


//EDIT FAVOURITES FUNCTION
function editFavourites(obj) {
	var params = getParams(obj);
	var href ="transactions.php?table=favourites&action="+params.action+"&id="+params.id+"&ajax=1";

	$("#blank").load(href);
	
	if (params.removeobj) { $("#fav"+params.removeobj).fadeOut(); }
}

//toggle quick post form
function toggleQuickAdd(obj) {
	$(obj).parent().parent().hide();
}

$(document).ready(function(){
	
	// TAB UNIVERSAL
	$("a:not(.notclickable)","ul.tabmenu").click(function () {
		var tabs = $("a",$(this).parent().parent());
		
		$(tabs).removeClass("activeTab");
		$(this).addClass("activeTab");
		$("li.tabcontentlistitem").removeClass("selected");
		$("li.tabcontentlistitem:eq("+tabs.index(this)+")").addClass("selected");
		
		//if login is down and away it will scroll up!
		var bubbleposition = $("div.loginBubble").css("top");
		if (bubbleposition != "18px") {	$("div.loginBubble").animate({top: "18px"}, 400); }
		
		//if cluetip is visible then we must hide it!
		if ($("#cluetip:visible")) { $("#cluetip").hide(); }
		
		//update page when you click on the tabs in tab universal
		$("input[name=page]").val(tabs.index(this)+1);
		
	});
	
	//UPDATE MESSAGE
	if ($("#updatemsg").length) { $("#blank").animate({opacity:100}, 1500, function() {
														if ($("#updatemsg").hasClass("changedcompaymsg")) {
															//do nothing because the user have to select a option in the modal...
														} else {
														 	$("#updatemsg").fadeOut("slow")
														}
	}); }
	
	//SHOW FAVS IN ARTICLELIST
	$("li","ul.favs").hover(function() { $(this).find("div.deletefav").fadeIn(300); }, function() { $(this).find("div.deletefav").fadeOut(300); });
	
	//USER REG
	$("input.userregister").click(function() { userreg(this); return false; } );
	
	//EXPAND OR COLLAPSE FOR SIDEMENU
	$("a[title=expand]","ul.sidemenu li.collapse").click(function() {
					$(this).hide().parent().children("ul").show();
					$(this).parent().find("a[title=collapse]").show();
												  });
	
	$("a[title=collapse]","ul.sidemenu li.collapse").click(function() {
					$(this).hide().parent().children("ul").hide();
					$(this).parent().find("a[title=expand]").show();
												  });
												
	
	//TABLE SORTER
	if($("table.sortable").length > 0) {
		$.getScript("http://www.episteme.no/publib//jslib3/plugins/jquery.tablesorter.min.js", function(){
			setTimeout(function(){
				//New parser for table sorter
					$.tablesorter.addParser({
						// set a unique id
						id: 'gobyrel',
						is: function(s) {
								// return false so this parser is not auto detected
								return false;
						},
						format: function(s, table, cell) {
							// format your data for normalization
							var data = $(cell).attr('rel');
						
							return data;
						},
						// set type, either numeric or text
						type: 'numeric'
					});
					
					//call of plugin for sort tables
			$("table.sortable").tablesorter({
				  	widgets: ['zebra'],
					textExtraction: 'simple'
							});
					
			}, 100);
		});
	}
	
	//GET MODALBOX
	$(".getModal").click(function() { getModal(this); });
	
	// a href to submit forms
	$("a.submitform").click(function () { $(this).submit(); });
	
	//clear inputs text on blur
	$("input.clearfocus").focus(function() { clearOnFocus(this); });
	$("input.clearfocus").blur(function() { clearOnFocus(this); });
	
	//toggle div
	$("a.togglediv").click(function() {
					var div = $(this).attr("rel");									
					$("div.wrapcontainer").slideUp(500, function() { $(div).slideDown(500); });
					return false;
	});
	
	
	//to send ajax with the interests on my page
	$("input.toggleinterests").click(function() {
		var params = getParams(this);
		
		if ($(this).is(":checked")) { var action = "insert"; } else { var action = "delete"; }
		var href="transactions.php?ajax=1&table=userkeyword&action="+action+"&userid="+params.userid+"&keywordid="+params.keywordid;
		
		$("#blank").load(href);
	});
	
	//Cycling plugin for image roattor
	$("#imageRotator").cycle();
	
	//innerFade plugin
	var cspeed = $("input[name=cycle_speed]").val();
	var ctimeout = $("input[name=cycle_timeout]").val();
	var cheight = $("input[name=cycle_height]").val();
	
	$('ul.innerfade').innerfade({ animationtype: 'fade', speed: cspeed, timeout: ctimeout, type: 'sequence' });
	
	//vticker
	
	var tspeed = $("input[name=ticker_speed]").val();
	var ttimeout = $("input[name=ticker_timeout]").val();
	var titems = $("input[name=ticker_items]").val();
	
	$('div.vticker.small').vTicker({
		speed: tspeed,
		pause: ttimeout,
		showItems: titems,
		animation: 'fade',
		mousePause: false,
		height: 0,
		direction: 'down'
	});
	
	$('div.vticker.long').vTicker({
		speed: tspeed,
		pause: ttimeout,
		showItems: 4, 
		animation: 'fade',
		mousePause: false,
		height: 0,
		direction: 'up'
	});
	
	
});
