/*
 * UMarketing
 */
var UMarketing = {};

/* 
 * Contact form validation 
 */
UMarketing.home = function(){
	swfobject.embedSWF('temp/welcome.swf','home-swf',960,500, '9.0.0');
};
UMarketing.contactForm = function(){
	var $form = $('#contact-form'),
	    $emailField = $('#f-email'),
	    $messageField = $('#f-message');
	
	var 
		$select = $form.find('select'),
		$options = $('<ul class="dropdown-a"/>').hide(),
		$control = $('<p class="select-a"><a href="#" class="nonav"/></p>');
	
	//hide default select, together with parent paragraph
	$select.parent().hide(); 
	
	//click on the "select" control should open the dropdown and close on the next click
	$control.find('a').click(function(e){
		e.preventDefault();
		if ($options.is(':visible')) {
			$(document).unbind('click',documentClick);			
		}
		else {
			$(document).bind('click',documentClick);			
		}
		$options.toggle();
		$options.find('a.current').trigger('focus');		
	});
		
	var documentClick = function(e){
		if ($(e.target).parents('.contact .col-a').length === 0) {
			$(document).unbind('click',documentClick);
			$options.hide();
		}
	};
	
	//click on the dropdown item should close it and change value
	var optionClick = function(e){
		e.preventDefault();
		$options.hide();
		$(document).unbind('click',documentClick); //cleanup
		
		$control.find('a').text($(this).text());
		$select.val($(this).data('value'));
	};
	
	//populate data
	$select.find('option').each(function(){
		var option = $('<a href="#" class="nonav">'+$(this).text()+'</a>');
		option.data('value',$(this).attr('value'));		
		option.click(optionClick);
		
		var li = $('<li/>');
		li.append(option)
		$options.append(li);		
	});
	
	//activate first option
	$options.find('a:first').triggerHandler('click');
	
	//append controls to document
	$select.parent().after($control,$options);
	
	//VALIDATION	
	
	function validateEmail(str){
		return (/^[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,6}$/i).test(str);
	}		
		
	$form.submit(function(e){
		//remove previous validation error
		$form.find('.error').remove();
		
		var email = $.trim($emailField.val()),
		    message = $.trim($messageField.val());
		
		if (message === '' || email === '' ||	validateEmail(email) === false){
			e.preventDefault();
			$form.find('.col-b').prepend('<p class="error">Oops! Please fill in all fields and make sure provided email is valid.</p>');
		}		
	});
};

/* 
 * Login form validation
 */
UMarketing.loginForm = function(){
	var $form = $('#login-form'),
	    $loginField = $('#f-login'),
	    $passField = $('#f-password');
				
	$form.submit(function(e){
		window.open($(this).attr('action'));
		return false;
		//remove previous validation error
		$form.find('.error').remove();
		
		var login = $.trim($loginField.val()),
		    password = $passField.val();
		
		if (login === '' || password === ''){
			e.preventDefault();
			$form.prepend('<p class="error">Please provide both login and password.</p>');
		}		
	});
};

/* 
 * Our work gallery 
 */
UMarketing.gallery = function(){
	var $gallery = $('#gallery'),
	    $large = $gallery.find('.large'),
	    $thumbs = $('#thumbnails .thumbs a'),
			swfLink = $large.find('.swf').attr('href');

	if (swfLink) {
		$large.width(570);
		$large.html('<span id="galleryLargeWrapper" />');
		swfobject.embedSWF(swfLink,'galleryLargeWrapper',570,440, '9.0.0');		
	}

		
	var displayImage = function(src){
		//do nothing if the same image was clicked
		if ($large.find('img').attr('src') === src) {
			return false;
		}

		//set explicit height
		$large.height($large.height());
		
		//hide curent image
		$large.find('img,object').fadeOut('fast',function(){
			$(this).remove();
		});

		var $img = $('<img src="'+src+'" alt="'+$(this).attr('title')+'" style="display: none;">');
		$large.append($img);		


		//laod new image
		var imgObj = new Image();		
		imgObj.onload = function(){
			$large.animate({ 'height' : $img.height() });
			$img.fadeIn('fast');
		};	

		imgObj.src = src;		
	};
	
	var displaySWF = function(src){
		//do nothing if the same image was clicked
		if ($large.find('object').attr('data') === src) {
			return false;
		}

		//set explicit height
		$large.height($large.height());
		
		//hide curent image
		$large.find('img,object').fadeOut('fast',function(){
			$(this).remove();
			$large.width(570);
			$large.html('<span id="galleryLargeWrapper" />');
			swfobject.embedSWF(src,'galleryLargeWrapper',570,440, '9.0.0');			
		});
	};
	$thumbs.click(function(e){
		e.preventDefault();
		var src = $(this).attr('href');
		var extension = /\.([a-z]+)$/i.exec(src);
		extension = extension[1];
		if (extension.toLowerCase() === 'swf') {
			displaySWF(src);
		}
		else {
			displayImage(src);
		}
		return false;
	});
};

/* 
 * Javascript navigation and loader
 */
UMarketing.Loader = {
	hash : null,
	initialize : function(){		
		this.preload();
		this.hashCheck();			
		this.navigation();		
	},
	/*
	 * Load and parse content of a webpage, fetching only necessary content
	 */
	activatePage : function(hash){
		var 
			self = this,
			instant = arguments[1] || false;			
	
		this.hash = hash;		
		
		$.ajax({
			url: hash + '.html',
			data : {
				'ajaxrequest' : true	
			},
			type : 'POST',
			dataType: "html",
			success: function(data, status){
				var 
					title = $(data).find('#title').html(),
					$root = $(data);
						
				self.updateContents($root, title, instant);
			},
			error : function(){
				window.location.href = '404.html';
			}
		});
	},
	/*
	 * Update page content with provided HTML
	 */
	updateContents : function($root, title, instant) {
		if (title) {
			document.title = title;
		}	
		
		switch (instant) {
			case 'all':
				$('#root').html($root.html());	
				$('#footer').css('display','block');				
			break;
		
			//run after a click on the top nav
			case 'top':
				$('#content').fadeOut('fast',function(){
					$root.find('#content').hide();
					$('#root').html($root.html());
					$('#content').fadeIn('fast');
					$('#footer').fadeIn('fast');
				});				
			break;
		
			//run after a click on the sidebar nav
			case 'navigation':
				$('#root').find('.wrapper-a').fadeOut('fast', function(){
					$root.find('.wrapper-a').hide();
					$('#root').html($root.html());					
					$('.wrapper-a').fadeIn('fast');
				});				
			break;
		
			case 'frame':
				$('#root').find('.wrapper-a .main').fadeOut('fast', function(){
					var $main = $root.find('.wrapper-a .main').hide();						
					$(this).html($main.html());					
					$('.wrapper-a .main').fadeIn('fast');
				});			
			break;
			
			default : 
			$('#footer').fadeOut('fast');
				$('#root').fadeOut('fast',function(){
					$('#footer').fadeIn('fast');
					$(this).html($root.html()).fadeIn('fast');
				});				
			break;			
		}			
	},
	/*
	 * Adds an overlay until all contents of the page have been loaded
	 */
	preload : function(){
		var is404 = /404\.html/i.test(window.location.href);
	
		//update overlay height for IE6
		if ($.browser.msie && $.browser.version === '6.0') {
			$('#overlay').height($(document).height());
		}
	
		var checkpoints = {};
	
		$(document).bind('preload.add',function(e, checkpoint){				
			checkpoints[checkpoint] = false;
		});
	
		$(document).bind('preload.check',function(e, checkpoint){
			checkpoints[checkpoint] = true;				

			for (var index in checkpoints){
				if (checkpoints.hasOwnProperty(index)){
					//exit if any of preloading checkpoints are still false
					if (checkpoints[index] === false) {						
						return;
					}
				}
			}				

			//we can append all events for content here
			$(document).trigger('contents.loaded');									

			//remove preloaders once the content has been resized
		
			$('body').addClass('loaded');					
		
			$('#overlay').fadeOut(1000, function(){		
				$(this).remove();
			});								
		});		
	
		//do not display overlay on the 404 page
		if (is404) {
			$('#overlay').remove();
			return;
		}
	
		//fade in overlay and make sure it's fully visible before fadeIng it out again
		$(document).trigger('preload.add',['overlay']);
		$('#overlay').fadeIn(500,function(){
			$(document).trigger('preload.check',['overlay']);
		});
	},
	/* 
	 * checks URL hash and looks for updated content
	 */		
	hashCheck : function(){		
	
		var _interval, currentHash, self = this;
		$(document).trigger('preload.add',['hash']);
	
		function execute(){
			//hash in the URL is matching the current hash, no action
			if (currentHash === window.location.hash) {
				return;
			}

			//update current hash
			currentHash = window.location.hash;

			//remove # from hash or set it to "home" if no hash is set
			var hash = ( window.location.hash !== '') ? window.location.hash.substr(1) : 'index';

			self.activatePage(hash,'all');
		}		
	
		//start hash check 
		$(document).bind('hashCheck.start', function(){
			_interval = window.setInterval(function(){
				execute();
			}, 500);
		}).triggerHandler('hashCheck.start');
	
		//stop hash check
		$(document).bind('hashCheck.stop', function(){
			window.clearInterval(_interval);
		});
	
		//set current hash to another one (during transitions)
		$(document).bind('hashCheck.set',function(e,hash){
			currentHash = hash;
		});		
	
		//no hash in the url
		if (window.location.hash === '') {
		
			if (/\/$/.test(window.location.pathname.substr(-1))) {
				currentHash = '#index';
			}
			else {
				var matches = /\/?([a-z0-9\-]+)\.html$/i.exec(window.location.href);
				if (matches) {
					currentHash = '#'+matches[1];
				}
			}
		
			window.location.hash = currentHash;			
		}	
	
		$(document).trigger('preload.check',['hash']);					
	},
	/*
	 * change navigation for all inbound links to based on hrefs and sliding
	 */
	navigation : function(){
		var self = this;
			
		var host = window.location.href.replace(window.location.pathname + window.location.hash,'')+'/';
		
		//target all inbound links			
		$('body').click(function(e){
			
			var target = $(e.target);
			if (e.target.nodeName.toUpperCase() !== 'A') {
				return false;
			}
			//alert($(target).attr('href'))
			//some links should not trigger navigation
			if ($(e.target).hasClass('nonav')) {
				return;
			}
			
			//open external links in a new window
			
			if (target.attr('rel') === 'external') {
				//alert($(target).attr('href'))
				window.open($(target).attr('href'));
				return false;
			}
					
			//alert('happen.')
			e.preventDefault();								
					
			var 
				isMainNav = target.is('#nav a'),
				isSideNav = target.is('.aside-b a,#bow-nav a'),
				isBowNavInline = target.is('#bow-nav a.inline');			 
		
			//simulate instant state change on these links
			if (isMainNav || isSideNav) {
				target.parent('ul').find('a').removeClass('active');
				target.addClass('active');
			}

			var instant = 'top';
		
			if (isSideNav) {
				instant = 'navigation';
			}
			
			if (isBowNavInline) {
				instant = 'frame';
			}
			
		
			var href = target.attr('href');
			if ($.browser.msie === true) {
				href = href.replace(host,'');
			}
			
			var hash = (/\/?([_a-z0-9\-]+)\.html/i).exec(href)[1];
		
			//same page, do nothing
			if (hash === self.hash) {
				return;
			}

			self.activatePage(hash,instant);							

			$(document).trigger('hashCheck.stop');					
			window.location.hash = hash;
			$(document).trigger('hashCheck.set',[window.location.hash]);
			$(document).trigger('hashCheck.start');
		});				
	}
};

UMarketing.fixes = {
	corners : function(){
		if ($.browser.msie === false || $.browser.version != '6.0') {
			return;
		}
		
		$(window).resize(function(){
			var 
				width = $(document).width() < 1000 ? 1000 : $(document).width() - 21;
				height = $(document).height() < 650 ? 650 : $(document).height() - 4;

			$('#corners, #corners span').height(height).width(width);			
		});		
	}
};

jQuery(function($) { 
	UMarketing.Loader.initialize();	
	//UMarketing.fixes.corners();
});