// JavaScript Document
/* smart client behaviors - load non semantic stuff */
$(document).ready(function() {
	
	$("#upperMenu.piped li a:not(:last)").after("<span class='pipe'>|</span>");
	
	$("#languageMenu.piped li a:not(:last)").after("<span class='pipe'>|</span>");
	
	if($.browser.msie && $.browser.version.substr(0,1) == '6') {
		
		$("#_submenuServicii.piped li a:not(:first):not(:last)").after("&nbsp;&nbsp;|").before("&nbsp;&nbsp;");
		$("#_submenuPortofoliu.piped li a:not(:first):not(:last)").after("&nbsp;&nbsp;|").before("&nbsp;&nbsp;");
		
		$("#_submenuServicii.piped li a:first").before("&nbsp;").after("&nbsp;&nbsp;|");
		$("#_submenuPortofoliu.piped li a:first").before("&nbsp;").after("&nbsp;&nbsp;|");
		
		$("#_submenuServicii.piped li a:last").before("&nbsp;&nbsp;");
		$("#_submenuPortofoliu.piped li a:last").before("&nbsp;&nbsp;");
		
	} else {
		$("#_submenuServicii.piped li a:not(:last)").after("<span class='pipe'>|</span>");
		$("#_submenuPortofoliu.piped li > a:not(:last)").after("<span class='pipe'>|</span>");
	}
	
	$("#footerMenu.piped li a:not(:last)").after("<span class='pipe'>|</span>");
	
	$("#timeBox").remove().prependTo("#additionalToolbar");
	$("#languageMenu").remove().prependTo("#additionalToolbar");
});

// hide sitemap
$(document).ready(function(){
	$(".sitemapOnly").hide();
});

// build multilevel menu
$(document).ready(function() {
	$("#upperMenu .hasSubmenu").each(function() {
		submenuId = '_' + $(this).attr("id");
		$(this).append( $("#" + submenuId).clone() );
		$("#" + submenuId).hide().css("float", "left").css("position", "absolute").css("top", "100px").css("left", "240px");
	});
});

$(document).ready(function() {
	$("#upperMenu .hasSubmenu").hover(
		function() {
			submenuId = '_' + $(this).attr("id");
			$("#" + submenuId).show().css("margin-top", "-2px").css("padding-top", "2px");
		},
		function() {
			submenuId = '_' + $(this).attr("id");
			$("#" + submenuId).hide();
		}
	);
});

// setup thumbs tooltips
$(document).ready(function() {
	setupTooltips();
});

function setupTooltips() {
	$("#recentProjectsList li a, .thumbsList li a").tooltip({
		delay: 0,
			showURL: false,
			bodyHandler: function() {				
  				return "<div class='portfolioInnerContent'><div class='bordering'><div style='background: url(" + $(this).children("img").attr("src").replace(portfolios_dir,tooltip_thumbs) + ") center center no-repeat;'>&nbsp;</div></div><span class='title'>" + $(this).children("span.projectTitle").html() + "</span><span class='description'>" + $(this).children("span.projectDescription").html() + "</span></div>";
			},
		track: true,
		opacity: 0.5,
		fixPNG: true,
		extraClass: "portfolioTooltip"
	});
}


// prepare hidden div to store temporary content
$(document).ready(function() {
	$('body').append('<div style="display: none; width: 0; height: 0; overflow: hidden;" id="temporaryHolder"></div>');
});

// callback function for ajax remote
function remoteCallback(element) {	

	//alert(isFirstTime + ' ' + doAnimate);
	
	// animate content
	$('#content').css('overflow', 'hidden');
	
	// setup page title
	titleValue = $('#temporaryHolder').find('page_title').attr('value');
	$('#temporaryHolder').find('page_title').remove();
	document.title = titleValue;
	
	// setup selected menu item
	if( $('#temporaryHolder').find('parent').length > 0 ) {
		parentValue = $('#temporaryHolder').find('parent').attr('value').replace(/\s/g, '_');
		$('#temporaryHolder').find('parent').remove(); 
		$(".currentPageLink").removeClass("currentPageLink");
		$('#upperMenu li a[href="#' + parentValue + '"]').addClass("currentPageLink");
	}
	
	if( $(element).hasClass('portfolioItem') ) { // portfolio items have circular animation
		if( $(element).hasClass('previous') ) { // previous items go one way
			animatePortfolioRight();
		} else if( $(element).hasClass('next') ) { // next items go the other way
			animatePortfolioLeft();
		}
	} else { // regular links
		if(doAnimate){
			animateLeft();
		} else {
			showContentWithoutAnimation();
		}
	}
}

function animatePortfolioLeft() {
	$('#innerContent').animate({ left: "-740px" }, 'medium', function() {
		$("body").unblock();
		$('#innerContent').css('left', '740px');
		
		$('#innerContent').html( $('#temporaryHolder').html() ).animate({ left: "0px" }, 'medium', function() {	
			pageLoadCallback();
		});
	});
}

function animatePortfolioRight() {
	$('#innerContent').animate({ left: "740px" }, 'medium', function() {
		$("body").unblock();
		$('#innerContent').css('left', '-740px');
		
		$('#innerContent').html( $('#temporaryHolder').html() ).animate({ left: "0px" }, 'medium', function() {	
			pageLoadCallback();
		});
	});
}

function animateLeft() {
	$('#innerContent').animate({ left: "-740px" }, 'medium', function() {
		$("body").unblock();

		$('#innerContent').html( $('#temporaryHolder').html() ).animate({ left: "0px" }, 'medium', function() {			
			pageLoadCallback();
		});
	});
}

function showContentWithoutAnimation() {
	$('#innerContent').html( $('#temporaryHolder').html() );
	
	isFirstTime = false;
	doAnimate = true;
	
	pageLoadCallback();
}

// initial load fix
function showContent() {
	// 
	if( $('#cssLoadFix').length > 0 ) {
		$('#cssLoadFix').remove();
		$('#content').css('visibility', 'visible');
	}
}

function pageLoadCallback() {
	refreshAjaxifiedLinks();
	setupTooltips();
	
	if(!contactIsSet && !$.browser.msie) {
		setupContactValidation();
		contactIsSet = true;
	} else if($.browser.msie) {
		setupContactValidation();
	}
	
	$('#content').css('overflow', 'hidden');
}

// change default links to support ajax history
$(document).ready(function() {
	$("a:not('.noAjax'):not('.remote')").each(function() {
		$(this).addClass("remote").remote('#temporaryHolder', function() { remoteCallback(this) } );
	});
});

var callCounter = 0;
function prepareContentLoad() {
	if(!doAnimate) return;
	
	//$("#upperMenu").block({message: ''});
	$("#innerContent").block({message: ''});
	$("#content").block({message: '<div class="uiBlockLoader">' + dictionary['loader_info_loading'] + '...</div>'});
}

function refreshAjaxifiedLinks() {
	$("a:not('.noAjax'):not('.remote')").addClass("remote").remote('#temporaryHolder', function() { remoteCallback(this) } );
}

// setup the timer
function setCurrentDate() {
	currentDate = new Date();
	
	$("#dayDate").html( currentDate.format("d mmm, yyyy") );
	$("#dayTime").html( currentDate.format("HH:MM:ss") );
	
	// shouldn't be here but we don't want multiple timers
	if($.browser.msie) {
		checkAnchor();
	}
	
	setTimeout("setCurrentDate()", 1000);
}

$(document).ready(
	function() {
		setCurrentDate();
	}
);

/* history */
/* ajax history */
$(document).ready(
	function() {
		$.ajaxHistory.initialize();
	}
);

/* generic confirmation function */
function confirmAction(message) {
	return confirm(message);
}


/* generic javascript output function */
var magenta = '#ec008c';
var white = '#fff';
var speed = 350;
function shout(message, inputId) {
	
	if( $('#' + inputId + ' + span.contactError').length > 0 ) { // error message already exists
		$('#' + inputId + ' + span.contactError').html(message);
		if( message != '&nbsp;' ) { // for stylistic spacing don't flash input
			$('#' + inputId).animate( { backgroundColor: magenta }, speed ).animate({ backgroundColor: white }, speed);
		}
	} else {
		if( message != '&nbsp;' ) { // for stylistic spacing don't flash input
			$('#' + inputId).animate({ backgroundColor: magenta }, speed).animate({ backgroundColor: white }, speed);
		} 
		$('#' + inputId).after('<span class="contactError">' + message + '</span>');
	}
}

function silence(inputId) {
	$('#' + inputId + ' + span.contactError').hide(speed, function(){ $('#' + inputId + ' + span.contactError').remove() });
}

function lookBusy( action ) {
	if( action ) {
		$('#document').css('cursor', 'wait');
	} else {
		$('#document').css('cursor', 'default');
	}
}

/* control page load workflow */
var ajaxSemaphore = true;
var previousHref = '';
$(document).ajaxStart(function() {
	ajaxSemaphore = false;					   
});

$(document).ajaxStop(function() {
	addSafeContact();
	setTimeout("checkAnchor()", 1000);
	
	// hide possible forgotten tooltip
	$('#tooltip').hide();
	
	ajaxSemaphore = true;
	showContent();
});

/* safe email address */
function safeContact() {
	var a = "office";
	var c = "@";
	var b = "cratima.com";
	
	return (a+c+b); 
}

function addSafeContact() {
	$(document).ready(function() {
		// if it's the contact page, add safe data
		if( $('#contactInfoBox').length > 0 ) { // yes it is
			if( $('#appendedContact').length === 0 ) { // it's not added yet
				$('#contactInfoBox').append('<p id="appendedContact"><strong>Email:</strong> <a href="mailto:' + safeContact() + '" class="noAjax">' + safeContact() + '</a></p>');
			}
		}
	});
}

// load animation
$(document).ready(function() {
	$("#rightExtendable").html('<img id="media" src="images/clepsidra.jpg" alt="Cratima - It\'s deadline, it\'s done!" title="Cratima - It\'s deadline, it\'s done!" />');
	swfobject.embedSWF("media/loader.swf", "media", "225", "730", "9.0.0", '', {}, { wmode: "opaque", menu: "false" });
});

$(document).ready(function() {
	$('#upperMenu a').removeAttr('title');
});

$(document).ready(function() {
	if( window.location.hash == '' ) {
		showContent();
		setupContactValidation();
	} else if($.browser.safari) {
		showContent();
	}
});

var existingAnchor = '';
function checkAnchor() {
	//console.log(window.location.hash);
	
	if(window.location.hash != existingAnchor) {
		$('a[href$="' + window.location.hash + '"]').trigger('click');
		existingAnchor = window.location.hash;
	}
}