;(function($){
   $(document).ready(function() {

     var searchform = $('#search');
		 var s = $('#searchinput', searchform);
		 var focusrel = 'focused';
		 var defaultvar = '';
		 s.bind('focus', function(event) {
			 if(s.attr('rel') != focusrel) {
				 defaultval = s.attr('value');
				 s.attr('value', '');
				 s.attr('rel', focusrel);
			 }
		 });
		 s.bind('blur', function(event) {
			 if(s.attr('value') == '') {
				 s.attr('value', defaultval);
				 s.attr('rel', '');
			 }
		 });
		 searchform.bind('submit', function(event) {
       if(s.attr('value') == '' || s.attr('rel') != focusrel) {
				 window.console && console.log('Search input has no user defined value. Stopping form submission.');
				 event.preventDefamant();
				 return false;
			 }
     });




/************************ Start Rebuilding the wp-menu **********************
    $('#nav').attr("class", null);
    $('#menu-primary').attr("class", null);
    $('#menu-primary').children("li").each(function(){
        var _a_ = $(this, "li").children("a");
        $(this, "li").attr("id", _a_.html());
        $(this, "li").attr("class", null);

        var _ul_ = $(this, "li").children("ul");
        if(_ul_.html()){
            $('#wrapper').append('<div class="megamenu-container" id="menu_'+_a_.html()+'"></div>');
//            $('#menu_'+_a_.html()).append('<div class="megamenu-left"><ul class="sub-menu">'+_ul_.html()+'</ul></div>');
//            $('#menu_'+_a_.html()).append('<div id="megamenu-right-'+_a_.html()+'-contents" class="megamenu-right"></div>');

            /************* renaming the ids of sub manus *******************
            var i = 1;
            $(this, "li").children("ul").children("li").each(function(){
                $(this).attr("id", _a_.html()+'_'+i);
                $(this).attr("class", null);
                i ++;
            });
            $('#menu_'+_a_.html()).append('<div class="megamenu-left"><ul class="sub-menu">'+_ul_.html()+'</ul></div>');
            $('#menu_'+_a_.html()).append('<div id="megamenu-right-'+_a_.html()+'-contents" class="megamenu-right"></div>');
            i = 0;
            $(this, "li").children("ul").children("li").each(function(){
                if (i == 0)
                    $(this).attr("class", 'first');
                else
                    $(this).attr("class", null);
                i ++;
                $('#megamenu-right-'+_a_.html()+'-contents').append('<div class="megamenu-item-wrapper" id="content_'+_a_.html()+'_'+i+'"></div>');
                
                var page_name = $(this).children("a").attr('href');
                if (page_name.substr(-1,1) == "/"){
                    page_name = page_name.substr(0, page_name.length-1);
                }
                page_name = page_name.split("/").pop();
                $('#content_'+_a_.html()+'_'+i).load('a.php?c='+page_name); //$(this).children("a").attr('href')
            });
            $(this).html('<a href="'+_a_.attr('href')+'">'+_a_.html()+'</a>'); // removing all the submenus
            /************* end renaming the ids of sub manus ***************
        }
    });
  /************************ Comment Form Input Focus **************************/
	// Comment Form Focus
	 var inputs = $('#comments form span input, #comments form span textarea');
	 $.each(inputs, function(index, element) {
     element = $(element);
		 var parent = element.parent();
		 window.console && console.log(parent.get(0).tagName.toLowerCase());
		 if(parent.get(0).tagName.toLowerCase() == 'span') {
			 element.bind('focus', function(event) {
         $(parent).addClass('input-focus');
       });
			 element.bind('blur', function(event) {
         $(parent).removeClass('input-focus');
       });
		 }
   });
	 // If an element has the id of #load-focus, give that element focus on page now (eg. NOW).
	 // Make sure this is executed AFTER the focus and blur events are binded to the inputs.
	 if($('.load-focus')) {
		 $('.load-focus').focus();
	 }
  /************************ End Rebuilding the wp-menu **************************/
   $('#featured').cycle({
		  'next':  '#featured-next',
			'prev':  '#featured-prev',
			'pager': '#featured-pager'
    });
   

      $('#topMenu').superfish({'autoArrows': false,'speed':1,'delay':0});
      $('#region').superfish({'autoArrows': false,'speed':1,'delay':0});
         
		var containers = '.cycle-container';
		setCycleContainers(containers);
		$.each($(containers), function(index, element) {
			element = $(element);

			// Create an element to house the slide navigation links in.
			var pager = $('<div class="cycle-pager" id="cycle-pager-' + index + '" />');
			element.after(pager);
			var id = element.parent().attr('id');

			// Activate the cycle on the containers.
			element.cycle({
				'pager': '#cycle-pager-' + index,
				'containerResize': false,
				'prev': '#cycle-prev-' + id,
				'next': '#cycle-next-' + id,
				'pause': true
			});

			// Position pager inside the slideshow container after slides have been created.
			element.append(pager);
		});
/*****************************************MEGAMENU START*********************************/
	var item_top;
	var item_left;
	var item_bottom;
	var item_right;
	/***********************************Hover over the top menu********/
	$("#nav ul li").hoverIntent(
		function(){
		//Get active item boundaries
		item_top = $(this).offset().top;
		item_left = $(this).offset().left;
		item_bottom = item_top +  ($(this).height()-2); //adds a bit of leaway for ff
		item_right = item_left + $(this).width();

		if($(this).attr("class")!="nav_active"){
		$("#nav ul li").each(function(){$(this).removeClass("nav_active")});
		$(this).addClass("nav_active");
		$("#menu_"+$(this).attr("id")).fadeIn("fast");
                   
				    $(".item_activated").each(function(){
                            $(this).removeClass("item_activated");
                    });
					
					var id = $(this).attr("id");
					
					$(this).addClass("item_activated");
					$("#"+id+"_1").addClass("item_activated");
					$("#content_"+id+"_1").fadeIn();
					
                 /* switch($(this).attr("id"))
                  {
                     case "out":
                     //check if element exists, then show default submenu
                     if($("#content_out_1").length)
                     {
                        $("#content_out_1").fadeIn();
                        $("#out_1").addClass("item_activated");
                     }
                     break;
                     case "con":
                      if($("#content_con_1").length)
                      {
                         $("#content_con_1").fadeIn();
                         $("#con_1").addClass("item_activated");
                      }
                     break;
                     case "tra":
                     if($("#content_tra_1").length)
                     {
                        $("#content_tra_1").fadeIn();
                        $("#tra_1").addClass("item_activated");
                     }
                     break;
                     case "sec":
                     if($("#content_sec_1").length)
                     {
                        $("#content_sec_1").fadeIn();
                        $("#sec_1").addClass("item_activated");
                     }
                     break;
                  }*/
		}

		},
		function(e){
		// if it is leaving item on the bottom probably wants to check out the menu
		if((e.pageY>=item_bottom)&&(e.pageX>item_left)&&(e.pageX<item_right)){
                  //do nothing
		}
		else
		{
			$(this).removeClass("nav_active");
			$("#menu_"+$(this).attr("id")).fadeOut("fast");
		}
		});
	/***********************************Hover over the big container********/
	var megamenu_top;
	var megamenu_left;
	var megamenu_bottom;
	var megamenu_right;
	var element;
	$(".megamenu-container").hover(function(){
		element = $(this).attr("id").split("_");
		//element boundaries
		megamenu_top = $(this).offset().top;
		megamenu_left = $(this).offset().left;
		megamenu_bottom = megamenu_top + $(this).height();
		megamenu_right = megamenu_left + $(this).width();
		},function(e){
		//moved outside the parent item boundaries
		if((e.pageX>item_right)||(e.pageX<item_left)&&(e.pageY<item_bottom)){
			$(".item_activated").each(function(){
			$(this).removeClass("item_activated");
                        var split = $(this).attr("id").split("_");
			$("#content_"+element[1]+"_"+split[1]).fadeOut();
			});
			$(this).hide();
			$("#"+element[1]).removeClass("nav_active");
		}
		//moved outside the megamenu display
		if((e.pageX<megamenu_left)||(e.pageX>megamenu_right)||(e.pageY>megamenu_bottom)){
			$(".item_activated").each(function(){
			$(this).removeClass("item_activated");
                        var split = $(this).attr("id").split("_");
			$("#content_"+element[1]+"_"+split[1]).fadeOut();
			});
			$(this).fadeOut("fast");
                        $("#"+element[1]).removeClass("nav_active");
		}

	})
	/***********************************Hover over sub menu********/
	$(".megamenu-left ul li").hoverIntent(function(){
		var activated = false;
		if(($(this).attr("class")=="item_activated")||($(this).attr("class")=="first item_activated")){activated=true;}
		if(!activated){
		$(".item_activated").each(function(){
                        var split = $(this).attr("id").split("_");
			$(this).removeClass("item_activated");
			$("#content_"+split[0]+"_"+split[1]).fadeOut();
		});
		$(this).addClass("item_activated");
                var split = $(this).attr("id").split("_");
		$("#content_"+split[0]+"_"+split[1]).fadeIn();
		}
		},function(){
		});

   /*********************** Regions Menu ******************/
   /*$('#region li li a').bind('click', function(event) {
      
      $("#region_sel").text($(this).attr("title"));
      
      var reg_pos = $('#region').width();
      reg_pos = 200-reg_pos;
      
      $("#sub_regions").css("left", -reg_pos);
      return false;
   });*/
   
   var reg_pos = $('#region').width();
   reg_pos = 200-reg_pos;
      
   $("#sub_regions").css("left", -reg_pos);

/*****************************************MEGAMENU END*********************************/
/*****************************************SLIDER***************************************/
	var clicked = 0;
$(".slideme-please").click(function(){
		clicked++;
		var opened = true;
		var h1 = $(this).find("h1");
		var one = $(this);
		if(clicked<2){
		$(this).find("div").slideToggle(500,function(){clicked = 0;
		if(h1.attr("class")!=="orange"){
			h1.addClass("orange");
		}else{
			h1.removeClass("orange");
		}});
		}
	});
/*****************************************SLIDER END***********************************/


	/************************************** CAREERS PAGE ********************************/
	$("select.multiselect").each(function(){
		var element = $(this);	
		var returnstring = "";
		var listelements = new Array();
		element.find("option").each(function(){
			var selected = $(this).attr("selected");
			if(selected){
			listelements.push($(this).val()+"_sel_"+$(this).text());	
			}
			else{
			listelements.push($(this).val()+"_"+$(this).text());		
			}
		});
			
			element.parent().append('<div class="'+element.attr("id")+'"></div>');
			
			returnstring = '<div class="searchbox"><ul>';
			
			$.each(listelements, function(i,v){
				
				var curritem = v.split("_");
				if(curritem.length<3){
				returnstring += '<li id="'+curritem[0]+'">'+curritem[1]+'</li>';
				}
				else{
				returnstring += '<li id="'+curritem[0]+'" class="selected">'+curritem[2]+'</li>';	
				}
				
				});
			
			returnstring += '</ul></div>';
			element.hide();
			$("."+element.attr("id")).append(returnstring);
	});
	$(".searchbox li").click(function(){
		var searchboxid = $(this).parent().parent().parent().attr("class");
		var object = $(this);
		object.parent().find(".selected").removeClass("selected");
		object.addClass("selected");
		//now get the multiselect box and select exactly the same option
		var tobeselected = object.attr("id");
		$("#"+searchboxid).find("option").each(function(){
			if($(this).val() == tobeselected){
				$(this).attr("selected","selected");	
			}
		});
		
	});
  });/*DOC READY END*/

	/**
	 * Setup Cycle Containers
	 * Grab each cycle container, and set the maximum height for it.
	 *
	 * @access public
	 * @return void
	 */
	function setCycleContainers(containers) {
		var containers = $(containers);
		$.each(containers, function(index, element) {
			element = $(element);
			var cycles = $('> *', element);
			var height = 0;
			$.each(cycles, function(cindex, celement) {
				celement = $(celement);
				if(celement.outerHeight() > height) {
					height = celement.outerHeight();
				}
				element.height(height);
			});
 		});
	}

})(jQuery);


/**************************************HOVERINTENT*********************************************/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

function senddata(url)
{
   if($('#form-given-name').val() == "" || $('#form-family-name').val() == "" || $('#form-job-title').val() == "" || $('#form-company').val() == "" || $('#form-email').val() == "")
   {
      alert('Sending email unsuccesful.');
   }
   else
   {
	data = {
		'form-given-name' : $('#form-given-name').val(), 
		'form-family-name' : $('#form-family-name').val(), 
		'form-job-title' : $('#form-job-title').val(), 
		'form-company' : $('#form-company').val(), 
		'form-email' : $('#form-email').val(), 
		'form-updates' : $('#form-updates').val()		
	};	
	$.post(
		url,
		data,
		function (data) { 
			if (data.result == 'sent')
			{
				$('#registerform').fadeOut("fast", function(){
                                    $('#registerdone').fadeIn("fast");
                                 });
			}
			else
			{
				alert('Sending email unsuccesful.');
			}
	},
		'json'
	);
   }
}

function setCookie(c_name, value, expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString())+';path=/';
}

function setregion(region_id)
{
	setCookie('region-id', region_id, 30);
	location.reload()
	// alert('here');
}
