/*----------------------------------------------------

	JSONLOAD.JS

----------------------------------------------------*/

$(document).ready(function(){

	var bodyid = $('body').attr('id');
	
	// A. Close Response Messages
	//------------------------------------------------------------------------------------------

	$('#msg-response').bind("click", function(){
		if(!$('#msg-response').find('a').length){
			if($('#msg-response').is(':visible')){
				$("#msg-response").slideUp();
			}
		}
	});
	if($('#msg-response').find('a').length){ $("#msg-response span").hide(); }
	
	
	// B. Banner Cycle
	//------------------------------------------------------------------------------------------
	
	if(bodyid == "index"){
		eval($('#banner')
			.cycle({
				fx: 'fade',
				speed: 2000,
				timeout: 8000,
				pause: true,
				pager: '#banner-paging span'
		}));
	}
	
	// C. In Page Links
	//------------------------------------------------------------------------------------------
	
	$('a.in-link').click(function(){  
 		if(location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname){
			var $target = $(this.hash);
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if($target.length){
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 900);
				return false;
			}
		}  
  	});

	
	// D. Jobs Tab/Navigation
	//------------------------------------------------------------------------------------------

	if(bodyid == "index"){
		$('.jobs').hide();
		$('.jobs:first').show();
		$('#nav-jobs').prepend('<ul></ul>');
		$('.jobs').each(function(){
			var val = $(this).attr('id')+'-num'
			var num = document.getElementById(val).value
			//num = ""
			if(!num) num = 0;
			var shownjobs = $(this).children('ul').children('li').size();
			$(this).prepend('<p class="jobtotal">Currently showing '+shownjobs+' of '+num+' jobs found</p>');
			$('#nav-jobs ul').append('<li><a id="nav-'+$(this).attr('id') +'">'+$(this).attr('title')+'</a></li>');
		});
		$('#nav-jobs li:first').addClass('current');
		$('#nav-jobs ul a').bind('click', function(){
			$('.jobs').hide();
			var navitem = $(this).attr('id');
			$('#'+navitem.replace("nav-","")).show();
			$('#nav-jobs ul .current').removeClass('current');
			$(this).parent().addClass('current');
		});
	}
	
	$('.moreinformation-container').hide();
	$('.moreinformation-container').before('<a class="more-information">More Information</a>');
	$('.more-information').bind('click', function(){
		if($(this).siblings('div').is(':hidden')){
			$('.more-information').removeClass('hide');
			$(this).addClass('hide');
			$('.more-information').html('More Information');
			$(this).html('Hide Information');
			$('.more-information ~ div').hide();
			$(this).siblings('div').show();
		}else{
			$(this).removeClass('hide');
			$('.more-information').html('More Information');
			$('.more-information').removeClass('hide');
			$(this).siblings('div').hide();
		}
	});
	
	// E. Job Info
	//------------------------------------------------------------------------------------------
	$('#activeposts-jobinfo #job-content div > ul').hide();
	$('#activeposts-jobinfo #job-content div > div').hide();
	$('#activeposts-jobinfo #job-content div > h3').addClass('hidden');
	$('#activeposts-jobinfo h3').addClass('show-hide');
	$('#activeposts-jobinfo h3').bind('click', function(){
		if($(this).next('ul').is(':hidden')){
			$('#activeposts-jobinfo #job-content div > ul').slideUp();
			$('#activeposts-jobinfo #job-content div > div').slideUp();
			$(this).next('ul').slideDown();
		}else{
			$(this).next('ul').slideUp();	
		}
		if($(this).next('div').is(':hidden')){
			$('#activeposts-jobinfo #job-content div > ul').slideUp();
			$('#activeposts-jobinfo #job-content div > div').slideUp();
			$(this).next('div').slideDown();
		}else{
			$(this).next('div').slideUp();	
		}
	});
	
	
	// G. Mail Inline
	//------------------------------------------------------------------------------------------	
	$('.mail-inline form').hide();
	$('.mail-inline').prepend('<a class="write-message">Write a Message</a>');
	$('.write-message').bind('click', function(){
		if($(this).siblings('form').is(':hidden')){
			$('.write-message ~ form').slideUp();
			$(this).siblings('form').slideDown();
		}else{
			$(this).siblings('form').slideUp();
		}
	});
	
	// H. Initiate Colorbox
	//------------------------------------------------------------------------------------------

	if(bodyid == 'job-profile' || bodyid == 'my-account'){
		$(".colorbox").colorbox();
	}
	
		
	// I. Sliders
	//------------------------------------------------------------------------------------------
	
	var sliders = $('.sliders select');
	for(var i = 0; i < sliders.length; i++){
		$('#' + sliders.eq(i).attr('id')).selectToUISlider();
		$(sliders).hide();
	}
	
		
	// J. Add Passport
	//------------------------------------------------------------------------------------------
	
	$('#passport1').hide();
	$('#passport1').before('<p class="add-new"><a id="add-passport">Add Second Passport</a></p>');
	$('#add-passport').bind('click', function(){
		if($('#passport1').is(':hidden')){
			$('#passport1').slideDown();
			$('#add-passport').text('Remove Second Passport');
		}else{
			$('#passport1').slideUp();
			$('#add-passport').text('Add Second Passport');		
		}
	});	
	
		
	// K. Sign up
	//------------------------------------------------------------------------------------------	
	
	$('input[title=\'continue\']').hide();
	toggleSignup();
	$('#typeid').bind('change', function(){
		toggleSignup();
		$("#msg-response").slideUp();
	});
	
	
	// L. Headers
	//------------------------------------------------------------------------------------------
	
	var num = Math.floor(Math.random()*16);
	$("h1:has(span)").addClass('num_' + num);
	
	
	// M. I'm Interested
	//------------------------------------------------------------------------------------------

	$("#index .jobs form").submit(function() {

		
		var obj = this;
		var jobid = $(this).children('input[name=jobid]').val();
		var agency = $(this).children('input[name=agency]').val();

		/*var url = $(this).attr('action');
		var obj = this;
		$.post(url, getInputs(this),
			function(){
				$(obj).fadeOut();
				$(obj).before('<p class="interest-confirmed" style="display:none">Interest Confirmed</p>');
				$('.interest-confirmed').fadeIn();
			});
		return false;*/
		
		$.ajax({
			url: "/include/functions.php",
			cache: false,
			type: "GET",
			data: 'interestajax=true&jobid='+jobid+'&agency='+agency,
			success: function(html){
				if(html != ''){
					$('#msg-response').remove();
					$(obj).parents('li').append('<div id="msg-response"><div class="msg-error"><span>&nbsp;</span></div></div>')
					$('#msg-response div').html(html);
					$('#msg-response').show();			
				}else{
					$(obj).fadeOut();
					$(obj).before('<p class="interest-confirmed" style="display:none">Interest Confirmed</p>');
					$('.interest-confirmed').fadeIn();
				}
			}
		});
		return false;
		
	});
	
	// N. Input Hints
	//------------------------------------------------------------------------------------------	

	$('input[type="text"]').each(function(){
		var old_val = $(this).val();
		if(old_val == $(this).attr('title')){
			this.value = $(this).attr('title');
			$(this).focus(function(){
				if(this.value == $(this).attr('title')) {
					this.value = '';
				}
			});
			$(this).blur(function(){
				if(this.value == '') {
					this.value = $(this).attr('title');
				}
			});
		}
	})

	
	// O. New Popup
	//------------------------------------------------------------------------------------------	
	
	//if($('.staging').length > 0){
		
		var today=new Date()
		var expire=new Date('2012/5/1');
		
		if((!getCookie('popup24') && !getCookie('popupperm')) && (today.getTime()<=expire.getTime())){
			
			var style = $("link[media='screen']").attr("href");
			if(style.indexOf("screen.css") > 0 || style.indexOf("account.css") > 0){				
				$('body').append('<div class="new-popup"><div class="new-popup-outer"><div class="new-popup-inner"><h1>New</h1><h2>Exciting new features on yotspot</h2><h3>the right crew, first time, everytime!</h3><div class="column"><h4>Latest Jobs</h4><p>Post any job or position <strong>Live</strong> on our homepage absolutely <strong>Free</strong></p><a href="http://www.yotspot.com/my-account/post-a-position.html" class="link-clickhere">Click Here</a></div><div class="column"><h4>Unlock</h4><p>Unlock <strong>all</strong> professional crew contact details that apply for only &euro;99</p><a href="http://www.yotspot.com/my-account/active-posts.html" class="link-clickhere">Click Here</a></div><div class="column"><h4>Annual Subscription</h4><p>Search our entire crew database (2500+ members) 24/7 utilising our unique Yotspot&trade; filter and matching system</p><a href="http://www.yotspot.com/my-account/membership.html" class="link-clickhere">Click Here</a></div><form><input type="checkbox" name="hide" id="hide"><label for="hide">Tick to hide permanently</label></form><span class="new-popup-close">Close</span></div></div></div>');
				$('.new-popup').delay(1000).animate({bottom: '20px'}, 2500);
				setCookie('popup24','1','1');
				
				var mouse_is_inside = false;
				$('.new-popup').hover(function(){ 
					mouse_is_inside=true; 
				}, function(){ 
					mouse_is_inside=false; 
				});
				function closePopup(mouse){
					if(mouse == 1){
						if(mouse_is_inside == false ){ $('.new-popup').animate({bottom: '-290px'}, 1000); }	
					}else{
						$('.new-popup').animate({bottom: '-290px'}, 1000);
					}
				}
				$('.new-popup-close').click(function() {
					closePopup(0);
				});
				$('.new-popup form input').change(function() {
					setCookie('popupperm','1','365');
					closePopup(0);
				});
				$(document).click(function() {
					closePopup(1);
				});
				
			}
		}
	//}

	
	// P. Job Map
	//------------------------------------------------------------------------------------------	
	
	if($('.job-map-inline').length > 0){
		var map = $('.job-map-inline').remove();
		$('#job-content').before(map);
		$('.job-map-inline').wrap('<div class="job-map"></div>').removeClass('job-map-inline');
		$('.job-map').wrapInner('<div class="map-container"></div>');
		$('.job-map').prepend('<h5>View Map <span>Showing Current Location, Destination and Homeport</span></h5>');
		$('.map-container').append('<div><h6>Key</h6><p>H = Homeport<br />C = Current Location<br />D = Destination</p></div>');
		$('.map-container').hide();
		$('.job-map h5').click(function(){
			if($('.map-container').is(':hidden')){
				$('.map-container').slideDown();
				$('.job-map h5').html('Hide Map');
			}else{
				$('.map-container').slideUp();
				$('.job-map h5').html('View Map <span>Showing Current Location, Cruising Itinerary and Homeport</span>');
			}
		});
	}
	
});


// 01. toggleInputbox
//------------------------------------------------------------------------------------------

function toggleInputbox(id,text,userevent){

	var obj = document.getElementById(id);
	if(obj.value == text && userevent != "blur"){
		obj.value = "";
		$('#'+id).addClass("active");
	}else if(obj.value == text){
		$('#'+id).removeClass("active");
	}else if(trim(obj.value) == ""){
		obj.value = text;
		$('#'+id).removeClass("active");
	}else{
		obj.value = trim(obj.value);
	}
	
}

// 02. trim
//------------------------------------------------------------------------------------------

function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}


// 03. toggleSignup
//------------------------------------------------------------------------------------------

function toggleSignup(obj){
	if($('#typeid').val() != ''){
		if($('#typeid').val() != '2'){
			$('#employee').hide();
			$('#employer').show();
			$('#emp_typeid').val($('#typeid').val())
		}else{
			$('#employer').hide();
			$('#employee').show();
			$('#e_typeid').val($('#typeid').val())
		}
	}else{
		$('#employee').hide();
		$('#employer').hide();
	}
}


// 04. getInputs
//------------------------------------------------------------------------------------------
	
function getInputs(obj){
	postdata = {}
	$(obj).find('input').each(function(){
		name = $(this).attr("name");
		value = $(this).val();
		if(name)
			postdata[name] = value;
	});
	return postdata;
}

/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 J?rn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><p></p><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('p',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);

$(function() {
	$('.help-point').tooltip({ 
		track: true, 
		delay:0,
		showURL: false
	});
});

/* Cookies */
function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

