var baseCrmUrl= 'http://socialcrmbusdev.techlightenment.com/socialcrm/serviceinterface/';

window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

// return the splitted data
var splitter = function(data,item){
	return data.split(item);
}

var randomNumber = function(inputNumber){
	return Math.round(Math.random()*(inputNumber-1));
}

var mobile = /mobile/i.test(navigator.userAgent);
var is_iphone = ( /iphone/i.test(navigator.userAgent) || /ipod/i.test(navigator.userAgent) );

jQuery.fn.doOnce = function(func){
	this.length && func.apply(this);
	return this;
}

$(function() {
	$.easing.custom = function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	}

	var trigger = '';
	var indexModel = 0;

	var aside = $('aside');
	
	is_iphone && !pageYOffset && !location.hash && setTimeout(function () { 
		window.scrollTo(0, 1);
	}, 1000);
	
	if (is_iphone){
		
		$('header').append('<a href="#" class="iPhoneMenu">Menu</a>');
		
		$('a.iPhoneMenu').click(function(e) {
			$('nav ul').toggle(); 
			e.preventDefault();
		});
	}

	/* !previewOverlay: show the overlay and manage the next/prev images */ 
	var previewOverlay = $("#overlay").overlay({
		api: true,
		onLoad: function(){

			if (mobile){
				var pos = $('article.portfolio').offset();
				window.scrollTo(0, pos.top-10);
				$('#overlay').css({ 'top':pos.top-40 + 'px',position:"absolute" });
			} 
			
			if(!mobile){
				$("#overlay").css({boxShadow:"0 1px 64px rgba(0, 0, 0, 0.75)"});
			}

			$(".scrollable").data("scrollable").seekTo(indexModel,'5s');
		}
		
	});

	$('.portfolio')
		.delegate('a', 'touchstart click', function(e) { 
			indexModel = $(this).data('count');
			previewOverlay.load();
			e.preventDefault();	
		 })
		 .each(function(index) {
			var tempImage = '';
				$('.gallery').each(function(index) {
					tempImage += '<div><img src="'+$(this).find('a').attr('href')+'" /></div>';
				});
				$('.model .items').prepend(tempImage);
				$('.scrollable').scrollable({easing: 'custom'});
		 });
  
	// initialize validator and add a custom form submission logic
	$("#register").doOnce(function() {
		$(this).submit(function(e) {
	
		var form = $(this);
		
		var email = $(form).find('#email').val();

		var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/; 
		
		var test = filter.test(email);
		
		if( test ){
		
			// client-side validation OK.
			if (!e.isDefaultPrevented()) {
				
				$('#register,#error,.error').hide(); 
				$('.loader').show();
	
				var dataString =  form.serialize();
				$.ajax({
					//this is the php file that processes the data and send mail
					url: "/script/index.php",	
					
					//GET method is used
					type: "post",
		
					//pass the data
					data: dataString,
					
					//Do not cache the page
					cache: false,
					
					//success
					success: function (data) {
						//if process.php returned 1/true (send mail success)
						if (data == 'error_duplicate'){
							$('.loader').hide();
							$('#error').fadeIn(1000);
							$('#register').show(); 
		
							return false;
						}
		
						if (data == 1) {
							//hide the form
							$('p.infos, #register, .loader, #error,.error').fadeOut(100,function(){
								//show the success message
								$('.done').fadeIn('slow');
							} );
	
						//if process.php returned 0/false (send mail failed)
						} else {
							alert('Ops, unexpected error. Please try again later.');
							$('.loader').hide();
							$('#error').fadeIn(1000);
							$('#register').show(); 
						}
					}		
				});
	
				// prevent default form submission logic
				e.preventDefault();
			}
		} else {
			$('.error').show();
			e.preventDefault();
		}
		})	
	});


	/* !subscribeOverlay: show the poup */ 
	var subscribeOverlay =  $('#subscribeOverlay').overlay({
		api: true,
		onBeforeLoad: function(){
			$('#error, .done').hide();
			$('#register').show();
		},
		onBeforeClose: function(){
			$('.error').hide();
		}
	});
	

	/*
	$('.countdownTimeInternal').countdown(
		{until: new Date(2011, 12-1, 6, 23, 59, 00) , format: 'dhms',
		labels1: ['y', 'm', 'w', 'd','h','m','s'],
		layout:'<div><span class="countdown_amount">{dn}</span></div>'
	}); */
		
	/* !changenationOverlay: show the overlay to choose the country */ 
	var changeLanguage =  $('#changeLanguage').overlay({
		api: true,
		onLoad: function(){
			var wrap = this.getOverlay();

			$(wrap).find('#list a').unbind('click').click(function(e) {
				var me = $(this);
				
				// store the chosen language
				store.set( 'chosenLanguage', me.data('language') );
		
				window.location = me.attr('href');
				
				e.preventDefault();
			});
			
		}
	});
	
	/* !changenationTrigger the uploader overlay */ 
	$('#language a').click(function(e) {
		var me = $(this);
		
		// store the chosen language
		store.set( 'chosenLanguage', me.data('language') );
	
		window.location = me.attr('href');
	});
	
	aside
		.each(function(index) {
			if (adv.length){
				var myRandom = randomNumber(adv.length),
					myImage  = adv[myRandom].image,
					myLink	 = adv[myRandom].link,
					myTitle	 = '/ADV/' + adv[myRandom].title;
			
				$('<img />', {  
					id: 'advArea',
					'class': 'advArea',
					'src': myImage,
					click: function(){
						log('ADV Clicked');
						
						_gaq.push(['_trackEvent', 'advertising','clickInnerADV']);
						_gaq.push(['_trackPageview', myTitle]);
						
						window.open(myLink);
						
					}
				}).prependTo('aside');
			}
		})
		.find('h2 a.subscribe').click(function(e) {
			subscribeOverlay.load();
			e.preventDefault();
		})
		.end()
		.find('.randomGirl')
			.each(function(index) {
			  	var obj = $(this);
				$.getScript(jsonUrl, function(data, textStatus){
		
				var myRandom = randomNumber(randoModels.length);
				$(obj)
					.find('span.randomImage img')
					.attr({src:randoModels[myRandom].image})
				.end()
					.find('span.randomName')
					.html(randoModels[myRandom].name)
				.end()
					.find('a.website')
					.attr({href:randoModels[myRandom].url});
				});
			})
		.end()
		.find('.modelsFeed')
			.each(function(index) {
		  $(this).load(modelsFeed);
		});
		
		

	// show random image in the header of the page, adding the reflex effects
	function randomSplash(target){
		
		var newImage = models[myRandom].image;
		
		$(target).fadeOut('normal',function(){
			$(this).hide();
			$(this).attr("src", newImage).fadeIn();
		});
		
		var myText = 'Model: ' + models[myRandom].model + '<br/>';
		   myText += photoCredit + models[myRandom].photographer;
		
		$('#splash-infos').html(myText);
		
		if (myRandom == models.length-1)
			myRandom = 0
		else 
			myRandom++;
	}
	
	/* move the baloon in the wannabe models page */
	if ( $('.aboutMe h3') && !is_iphone) {
		setTimeout( function() {
		var obj = ($('.aboutMe h3').width()) +20;
		
		if (obj < 200) 
			obj = 200;
		else if (obj> 400)
			obj = 400;
		var baloon = $('nav.headFinal .baloon');	
		baloon.css({'left':obj}).fadeIn();
	  }, 100);
	  }
  
	// localization string for caledar's extra languages
	$.tools.dateinput.localize("zh-t",  {
		months:        '一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月',
		shortMonths:   '一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月',
		days:          '日,一,二,三,四,五,六',
		shortDays:     '日,一,二,三,四,五,六'
	});
	$.tools.dateinput.localize("zh-s",  {
		months:        '一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月',
		shortMonths:   '一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月',
		days:          '日,一,二,三,四,五,六',
		shortDays:     '日,一,二,三,四,五,六'
	});
	
});

