//MODALBOXY
	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;	
	}
	


	
	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();
	}
	
	
	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(); 
	}
	
	function modalBoxBinding() {// BINDING
		
		//close login dialog
		$(".closeloginbox").click(function() { closeModal(this); });
		
		$("input.userregister").click(function() { 
													  
						$(this).parents("form").validate({	
							onclick: false,
							onkeyup: false,
							onfocusout: false,
							onsubmit: true,	
							rules: { email: { required: true, email: true } },
							submitHandler: function() { userreg($("input.userregister")); }
						});
					});
	}


// jQuery scripts for Intsok
jQuery.fn.labelOver = function(overClass) {
	return this.each(function(){
		var label = jQuery(this);
		var f = label.attr('for');
		if (f) {
			var input = jQuery('#' + f);
			
			this.hide = function() {
			  label.css({ textIndent: -10000 })
			}
			
			this.show = function() {
			  if (input.val() == '') label.css({ textIndent: 0 })
			}

			// handlers
			input.focus(this.hide);
			input.blur(this.show);
		  label.addClass(overClass).click(function(){ input.focus() });
			
			if (input.val() != '') this.hide(); 
		}
	})
}
	
function stepsBinding() {																	  
	
	var formid = $("form","div.loginbox_content").attr("id");
	if (formid == "createuser") { 	
	$("input[type=submit]").click(function() {
		
		var pass01 = $("#passworded").val();
		var pass02 = $("#confpassword").val();
		
		$("input.val").each(function(i) {
					if ($(this).val().length < 3) {
							$(this).addClass("error");
					} else {
							$(this).removeClass("error");
					}
		});	
	
	//check for matching passwords
	if ($("#passworded").val() != $("#confpassword").val()) {
		$("#confpassword").addClass("error");
	} else {
		$("#confpassword").removeClass("error");
	}
	
	//if there are an error, show error box
	if ($("input.val").hasClass("error") || $("#confpassword").hasClass("error")) {
			$("div#createusermsg").show();
			return false;
	}
		
	});
	
	} else {
		
		$("input.userregister").click(function() { 
				$(this).parents("form").validate({	
					onclick: false,
					onkeyup: false,
					onfocusout: false,
					onsubmit: true,	
					rules: { email: { required: true, email: true } },
					submitHandler: function() { userreg($("input.userregister")); }
				});
		});
	
	}
	
	$(".closeloginbox").click(function() { closeModal(this); });
	
	$("table.sortable").tablesorter({ widgets: ['zebra'] });

	$("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]","table#multicompanyselect").click(function() {
					$("tr.selectedrow").removeClass("selectedrow");
					$(this).parent().parent().addClass("selectedrow");
															 });
}

//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.loginbox_content").animate({opacity:0}, 200);
				$("#ajaxloader").show(); 
				$("a.closeloginbox").fadeOut(100);
			},
		success: function(data) {
					//clone wrapper
					$("div.loginbox_content").clone(true).insertAfter("div.loginbox_content").addClass("hidden").hide()
					//animate previous and remove
					.prev().animate({opacity:0}, 100, function() { $("#ajaxloader").fadeOut(100); }).slideUp(1000, function() { 
							$(this).remove();
							$("a.closeloginbox").fadeIn(300);						
							$("div.loginbox_content.hidden").animate({opacity:100}, 1).html(data).removeClass("hidden").slideDown(1000);
							
							//binding
							stepsBinding();
							
					});//end slide callback
				
				}
			});
}

//send address with ajax (used for fav etc)
function sendAjax(url) { $('#ajaxload').load(url); }

$(document).ready(function(){
						   
	//AJAX SETUP
	$.ajaxSetup({
  		dataType: "html",
		type: "GET",
		timeout: 60000,
		error: function() { console.log("Error loading document"); }
	});

	//USER REG
	$("input.userregister").click(function() { userreg(this); } );
	
	//DRP DOWN SUCKERFISH STYLE
    $("div.sfclicker").click(function() {
					$(this).children("ul.sdropdown").toggle();	
					$(this).toggleClass("openMenu");
									})
	
	$("body").click(function(e) {
                var clicked = $(e.target); //which element is clicked
                if (clicked.is('.menuitem') || clicked.parents().is('.menuitem') || clicked.is('.sfclicker') || clicked.parents().is('.sfclicker')) {
				} else {   
					$('ul.sdropdown').hide();
					$("div.sfclicker").removeClass("openMenu");
				}
        });

	
	//HOVER FOR MAIN MENU
    $("div.mainMenu ul li").hover(
      function () {
        $(this).addClass("hover");
      }, 
      function () {
        $(this).removeClass("hover");
      }
    );
	
	//When click on input in login form hide label
	$('div.loginBubble label').labelOver('over-apply');
	$('tr#addnewuserrow label').labelOver('over-apply');	
	
	// 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 != "32pxpx") {	$("div.loginBubble").animate({top: "32px"}, 400); }
		
		//if cluetip is visible then we must hide it!
		if ($("#cluetip:visible")) { $("#cluetip").hide(); }
		
	});
	
	//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'
	});

	nextclass = "";
	firstnum = "";

	//first letter for companylist
	$("table#companylist tbody tr").each(function() {
						var firstclass = $(this).attr("rel");
						
						if (isNaN(firstclass)) {
							if(firstclass != nextclass) {
									nextclass = firstclass;
									$(this).attr("id",firstclass) //before("<tr id='"+firstclass+"' class='alpharow'><td>"+firstclass+"</tr></tr>");
									$("div#alphalist").find("a[title="+firstclass+"]").addClass("active").attr("href","#"+firstclass);								
								}
						} else {
							
							if (firstnum != 1) {
									$(this).attr("id","num");
									$("div#alphalist").find("a[title=num]").addClass("active").attr("href","#num");
									firstnum = 1;		
							}
						}
											  });
	
	//call of plugin for sort tables
	$("table.sortable").tablesorter({
				  	widgets: ['zebra'],
					textExtraction: 'simple'
							}); 
	
	$("table.mypageTable").tablesorter({
				  	widgets: ['zebra']
							});
	
	$("table.sortme").tablesorter({
					widgets: ['zebra']
						});
		
	//message of update
	$("#blank").animate({opacity:100}, 1500, function() {
														if ($("#updatemsg").hasClass("changedcompaymsg")) {} else {
														 $("#updatemsg").fadeOut("slow")
														}
														 });
	
	//toggle blur function
	$("#searchblur").click(function () {
								$("span.blur","#searchblur").toggle();
									if( $("span.blur.off","#searchblur").is(":hidden") ) {
											$("input[name='searchonblur']").val("1");
											$("form[name='searchform_inline']").submit();
									} else {
										$("input[name='searchonblur']").val("0");;
									}
								});
	
	
	//keywords show/hide
	$("#searchkeywords").click(function() {
									$("div.searchcheck").slideToggle();
									$("span.blur","#searchkeywords").toggle();
											if( $("span.blur.off","#searchkeywords").is(":hidden") ) {
												$("input[name='includekeywords']").val("1");
											} else {
												$("input[name='includekeywords']").val("0");
											}
										 });
	
	$("input[name='search']").blur(function () {
							if($("span.blur.off","#searchblur").is(":hidden")) {
								$("form[name='searchform_inline']").submit(); }
							});
	
	$("input[type='checkbox']").click(function () {
							if($("span.blur.off","#searchblur").is(":hidden")) {
								$("form[name='searchform_inline']").submit(); }
							});
	
	// a href to submit forms
	$("a.submitform").click(function () { $(this).submit(); });
	
	//hover over article items on my favoruites
	$("ul.favs li.articlelistitem").hover(
      function () {
        $(this).children().find("div.deletefav").show();
      }, 
      function () {
        $(this).children().find("div.deletefav").hide();
      }
    );
	
	//delete favourite btn
	$("div.deletefav").click(function() {
								   $(this).parent().parent().fadeOut("slow");
								   });
	
	//scroll to top with ease
	$("a.scrolltop").click(function() { $.scrollTo({top:0}, 400); });
	
	//scroll sign in down
	$("a.eventsignin").click(function(e) { var fromtop = e.pageY-85; $("div.loginBubble").animate({top:fromtop}, 400); });
	
	//CHECK IS COMPANY NAME ON MY PAGE IS CHANGED
	var compval = $("input[name='company']").val();
	
	$("input[@name='sendit']").click(function() {
			if ($("input[name='company']").val() != compval) {

				$("div.changedcompanymsg").show();
				$("div.changedcompanymsg ul li input").click(function() {
					$("#updateMyPage").submit();
																			})
				return false;
				}
											  });
	
		// CLUETIPS
		$.cluetip.setup ({
			  insertionType:    'appendTo', // how the clueTip is inserted into the DOM
											// possible values: 'appendTo', 'prependTo', 'insertBefore', 'insertAfter'
			  insertionElement: 'body'      // where in the DOM the clueTip is to be inserted 
			});
		
		//CLUETIP		
		$('a.loadlocal').cluetip({local:true, cursor: 'pointer', activation: 'click', topOffset: 20, dropShadow: false, width:270, leftOffset: -190, positionBy: 'fixed'});
		$('a.tip').cluetip({cluetipClass: 'jtip', local: false, cursor: 'question', activation: 'hover', topOffset: 20, dropShadow: false, width:270, leftOffset: -100, positionBy: 'fixed'});
	
	//read more for reports under country
	$("a.readmore_reports").click(function() {
			$(this).parent().parent().next().toggle();										  
										  });
	
	//MODALBOX
	$(".getModal").click(function() { getModal(this); });
	
	//add and delete from favourites
	$("a.fav").click(function() {
				//diff animation to make it slide and then show everything
				$("a.fav").toggle();
				$("#favalert p").hide();
				
				var w = $(this).attr("id");
				var href = $(this).attr("href");
				
				$("."+ w +"_text").show();
				$("#favalert").slideDown(500, function() { $("#favalert").animate({opacity:100}, 500, function() { $("#favalert").slideUp(500, function (){ }); }); });				 		 
	
				sendAjax($(this).attr("href"));
				return false;
	});
	
	$("img.togglesub").click(function() {
					$(this).parents("tr").find("img.togglesub").toggle();	
					$(this).parents("tr").find("div.subsidiaries").toggle();
									  });
	
	//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();
												  });
	
	// '''''''' SUPER USER ''''''''''
	//Delete users when you are a super user
	$("a#deleteusers").click(function() {
				$("td.editcell","table.colleaguestable").children().hide();	
				$("td.editcell","table.colleaguestable").children("img.deletebtn").show();
									  });
	
	$("img","th.editrow").click(function() {
				$("div#editmodemsg").fadeOut(500);												   
												   });
	
	$("a#deleteusers","th.editrow").click(function() {
				$("span","div#editmodemsg").remove();
				$("div#editmodemsg").append("<span>You are now in edit mode</span>");
				$("div#editmodemsg").fadeIn(500);
												   });
												   
	$("a.head","div.iorcollapse").click(function() {
		$(this).toggleClass("open");
		$(this).parents("div.iorcollapse").find("div.iorchild").toggle();
		});
	
	
	//Cycling plugin for image roattor
	$("#imageRotator").cycle();
	
});