$.fn.labelFader = function() {
	var f = function() {
		var $this = $(this)
		if ($this.val()) {
			$this.siblings("label").children("span").hide();
		} else {
			$this.siblings("label").children("span").fadeIn("fast");
		}
	};
		
	this.focus(f);
	this.blur(f);
	this.keyup(f);
	this.change(f);
	this.each(f);
	return this;
};

$.fn.inputInfo = function() {
	var f = function() {
		var $this = $(this)
		var $info_div = $('#'+$(this).attr('id')+'_info');
		if ($this.val()) {
			//$info_div.hide();
		} else {
			$info_div.show();
		}
	};

	var h = function() {
		var $this = $(this)
		var $info_div = $('#'+$(this).attr('id')+'_info');
		$info_div.hide();
	};

		
	this.focus(f);
	this.blur(h);
	//this.keyup(f);
	return this;
};
	
$(function() {
	
	/*if(!$.browser.msie){
		$('#quotes').cycle({
			fx: 'scrollLeft'
		});
	} else {
		$('#quotes img:eq(0)').remove();	
	};*/
	
	/*$('#quotes').cycle({
		fx: 'scrollLeft'
	});*/
	
	$('#sitename_id').val('');
	
	$('#sitename_id').focus( function() {
		$(this).parent('.labeled-input-site-title').addClass('focus');
	}).blur( function() {
		if($('#sitename_id').val()==''){
			$(this).parent('.labeled-input-site-title').removeClass('focus');
		} else {
			$(this).parent('.labeled-input-site-title').addClass('focus');
			$(this).next().removeClass('hidden').addClass('hidden'); 
		};
	}).keyup(function(event){
		if($('#sitename_id').val()==''){
			$(this).parent('.labeled-input-site-title').addClass('focus');
			$(this).next().removeClass('hidden').addClass('visible'); 
		} else {
			$(this).parent('.labeled-input-site-title').removeClass('focus');
			$(this).next().removeClass('visible').addClass('hidden'); 
		};
	});
	
	/*
	 *
	 */
	
	/*
	number of fieldsets
	*/
	var screenshotCount = $('#screenshots').children().length;
	
	/*
	current position of fieldset / navigation link
	*/
	var current 	= 1;
    
	/*
	sum and save the widths of each one of the fieldsets
	set the final sum as the total width of the steps element
	*/
	var screenshotsWidth	= 0;
	var widths 		= new Array();
	
	$('#screenshots .screenshot').each(function(i){
		var $screenshot		= $(this);
		widths[i]  		= screenshotsWidth;
		screenshotsWidth       += $screenshot.width();
	});
	
	$('#screenshots').width(screenshotsWidth);
	
	/*
	to avoid problems in IE, focus the first input of the form
	*/
	$('#formElem').children(':first').find(':input:first').focus();	
	
	/*
	show the navigation bar
	*/
	$('#screenshots-navigation').show();
	
	/*
	when clicking on a navigation link 
	the form slides to the corresponding fieldset
	*/
	$('#screenshots-navigation a').bind('click',function(e){
		var $this	= $(this);
		var prev	= current;
		$this.closest('ul').find('li').removeClass('selected');
		$this.parent().addClass('selected');
		/*
		we store the position of the link
		in the current variable	
		*/
		
		current = $this.closest('ul').find('li').index($this.parent()) + 1;
		/*
		animate / slide to the next or to the corresponding
		fieldset. The order of the links in the navigation
		is the order of the fieldsets.
		Also, after sliding, we trigger the focus on the first 
		input element of the new fieldset
		If we clicked on the last link (confirmation), then we validate
		all the fieldsets, otherwise we validate the previous one
		before the form slided
		*/
		
		$('#screenshots').stop().animate({
			marginLeft: '-' + widths[current-1] + 'px'
		},500,function(){
			$('#screenshots').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();	
		});
		e.preventDefault();
	});
	
	/*
	clicking on the tab (on the last input of each fieldset), makes the form
	slide to the next step
	*/
	$('#screenshots > screenshot').each(function(){
		var $screenshot = $(this);
		$screenshot.children(':last').find(':input').keydown(function(e){
			if (e.which == 9){
				$('#screenshots-navigation li:nth-child(' + (parseInt(current)+1) + ') a').click();
				/* force the blur for validation */
				$(this).blur();
				e.preventDefault();
			}
		});
	});
	
	/*
	 * Site type slider
	*/
	$('#screenshots').cycle({
	    fx:     'scrollLeft',
	    speed:  'slow',
	    timeout: 5000
	});
	
	/*
	 * Video
	 */
	$('#play_demo').click(function(){
		$('#screencast-panel').show();	
	});
	$('#screencast-cancel-btn').click(function(){
		$('#screencast-panel').hide();	
	});
	
	 $('#make-a-website').click(function(){
	        $('html, body').animate({scrollTop:0}, 'slow');
	        return false;
	});
	 
	/* New UI */
	$("#themes_container").carouFredSel({
		auto : false,
		circular: false,
		infinite: false,
		prev : {	
			button	: "#themes_container_prev",
			key	: "left"
		},
		next : { 
			button	: "#themes_container_next",
			key	: "right"
		},
		width	: 904
	});
	
	$("#iframe").load(function (){
		$('#theme_preview_block .big_loading').hide();
		$('#theme_preview_block').addClass('iframe_loaded');
	});

	$('ul.site_templates li').click(function(){
		// Get sitetype ID
		var type_id = $(this).attr('type_id');
		$('input#selected_type').val(type_id);
		$('ul.site_templates li').removeClass('selected');
		$(this).addClass('selected');
		$('#choose_template span').removeClass('selected');
		
		var $selected_theme = $('.theme_container_s .theme_detail_s.selected');
		if($selected_theme.length == 0) {
			$selected_theme = $('.theme_container_s:first');
			$('.theme_container_s:first .theme_detail_s').click();
		} else {
			$selected_theme = $('.theme_container_s .theme_detail_s.selected').parent('.theme_container_s');
		}
		var theme_id = $selected_theme.attr('theme_id');
		
		$('#sticky_note').hide();
		$('#theme_preview_block #iframe_container').show();
		$('#theme_preview_block .big_loading').show();
		$('#iframe').attr('src', "http://django."+$server_on+".com/theme/preview_by_type/"+theme_id+"/"+type_id+"/");
	});
	
	$('.theme_container_s').click(function(){
		$('.theme_detail_s').removeClass('selected');
		$('.theme_detail_s', this).addClass('selected');
		$('#choose_theme span').removeClass('selected');
		
		//Get theme ID
		var theme_id = $(this).attr('theme_id');
		$('input#selected_theme').val(theme_id);
		
		//Get site type ID
		var $selected_type = $('.site_templates li.selected');
		if($selected_type.length == 0) {
			$selected_type = $('.site_templates li:first');
			$('.site_templates li:first').click();
		}
		var sitetype_id = $selected_type.attr('type_id');
		$('input#selected_type').val(sitetype_id);
		
		$('#slideshow_container').hide();
		$('.preview_container').show();
		$('#theme_preview_block #iframe_container').show();
		$('#theme_preview_block .big_loading').show();
		$('#iframe').attr('src', "http://django."+$server_on+".com/theme/preview_by_type/"+theme_id+"/"+sitetype_id+"/");
		});
	
	$('input').livequery(function(){
		$(this).placeholder();
	      });
	
	$('.register a').click(function(){
		$('.modal-header.register').hide();
		$('.modal-header.login').show();
		$('#auth_choice').val('login');
		$('.signup_fields').removeClass('register').addClass('login');
		/*var $oldEmail = $('input#email');
		var $newEmail = $("<input type='text' required='required' tabindex='1' size='20' name='user[email]' maxlength='20' class='text_field' autocomplete='off' />").appendTo($oldEmail.parent());
		$oldEmail.remove();
		$newEmail.attr('id','email');*/
		$('input#name').val(' ');
		$("#new_account_form").data("validator").reset();
		
		$('input.email_username').focus(); 
	});
	
	$('.login a').click(function(){
		$('.modal-header.login').hide();
		$('.modal-header.register').show();
		$('#auth_choice').val('register');
		$('.signup_fields').removeClass('login').addClass('register');
		/*var $oldEmail = $('input#email');
		var $newEmail = $("<input type='email' required='required' tabindex='1' size='20' name='user[email]' maxlength='20' class='text_field' autocomplete='off' />").appendTo($oldEmail.parent());
		$oldEmail.remove();
		$newEmail.attr('id','email');*/
		$('input#name').val('');
		$("#new_account_form").data("validator").reset();
		$('input#name').focus();
	});
	
	/* Sign up/Sign in during site creation process*/
	/* when user is NOT LOGGED IN*/
	var $form = $("#new_account_form").validator({
		errorClass: 'acc_input_error',
		offset: [0, -205],
		position: 'center left'
		});
	
	$form.submit(function(e) {

		var form = $(this);
	
		// client-side validation passed
		if (!e.isDefaultPrevented()) {
			
			// submit the data to the server with AJAX
			$.post(form.attr("action"), form.serialize(), function(data) {
				
				// everything is ok. (the server returned true)
				if (data === 1)  {
					
					$('#create_new_account').attr('disabled', 'disabled');
					$('#create_new_account').text('Please wait...');
					
					//$('button#create_new_account').hide();
					//$('#signup_box .big_loading').show();
					
					/* TODO: Uncomment this when deploying 08/09/2011 */
					window.location = "http://"+form.serializeArray()[3].value+"."+$server_on+".com/site/load_content/?u="+form.serializeArray()[1].value+"&p="+form.serializeArray()[2].value;
				
				// server-side validation failed. use invalidate() to show errors
				} else {
					if(data.isauthorized){
						$('.creation_error_msg').text(data.isauthorized).show();
					} else {
						form.data("validator").invalidate(data);
					}
				}
			}, "json");
	
			// prevent default form submission logic
			e.preventDefault();
		}
	});
	
	/* Sign up/Sign in during site creation process*/
	/* when user is already AUTHENTICATED or LOGGED IN*/
	var $new_site_form = $("#new_site_form").validator({
		errorClass: 'acc_input_error',
		offset: [0, -205],
		position: 'center left'
		});
	
	$new_site_form.submit(function(e) {

		var new_site_form = $(this);

		// client-side validation passed
		if (!e.isDefaultPrevented()) {
	
			// submit the data to the server with AJAX
			$.post(new_site_form.attr("action"), new_site_form.serialize(), function(data) {
				
				// everything is ok. (the server returned true)
				if (data.success=='success')  {
					
					$('#create_new_account').attr('disabled', 'disabled');
					$('#create_new_account').text('Please wait...');
					
					/* TODO: Uncomment this when deploying 08/09/2011 */
					window.location = "http://"+new_site_form.serializeArray()[2].value+"."+$server_on+".com/site/load_content/?u="+new_site_form.serializeArray()[0].value+"&p="+new_site_form.serializeArray()[1].value;
				
				// server-side validation failed. use invalidate() to show errors
				} else {
					new_site_form.data("validator").invalidate(data);
				}
			}, "json");
	
			// prevent default form submission logic
			e.preventDefault();
		}
	});
	
	/* Sign in from sign in menu*/
	var $sigin_form = $("#signin_form").validator({
		errorClass: 'acc_input_error',
		offset: [0, -193],
		position: 'center left'
	});
	
	$sigin_form.submit(function(e) {
		var form = $(this);
		// client-side validation passed
		if (!e.isDefaultPrevented()) {
			// submit the data to the server with AJAX
			$.post(form.attr("action"), form.serialize(), function(data) {
				// everything is ok. (the server returned true)
				if (data.success === 'true')  {
					if(data.next === 'my-domain' || data.next === 'new-domain'){
						window.location = "https://secure."+$server_on+".com/checkout/"+data.next+"/?i="+data.i+"&s="+data.s;
					}else{
						window.location = "http://www."+$server_on+".com/dashboard/";
					}
				// server-side validation failed. use invalidate() to show errors
				} else {
					form.data("validator").invalidate(data);
				}
			}, "json");
			// prevent default form submission logic
			e.preventDefault();
		}
	});
	
	/* new slides */
	var window_width = $(window).width();
	$('ul#slides_list li').css('width', window_width+'px');
	
	$("#slides_list").carouFredSel({items:1, height:600, auto:{pauseDuration:5000}});
	
	//Cufon.replace('.big_title', { fontFamily: 'Museo 700' });
	//Cufon.replace('#general_ads_block h5', { fontFamily: 'Museo 500' });
	//Cufon.replace('ul.site_templates a', { fontFamily: 'Museo 500' })
	//Cufon.replace('h2.step_title', { fontFamily: 'Museo 500' });
	//Cufon.replace('h2.step_title span', { fontFamily: 'Museo 700' });
	
	/* new account modal window*/
	$(".fade_label input").labelFader();
        
    $(".fade_label input").inputInfo();
        
    $(".fade_label input").focus(function() {
        $(this).siblings("label").addClass("focus");
    }).blur(function() {
        $(this).siblings("label").removeClass("focus");
    }); 
    
	$('#continue_button').click(function(){
		var h = $(window).height();
		var t = $(window).scrollTop();
		$('#signup_modal').css('top', Math.round(t + h/2) + 'px');
		$('.modal_overlay').show();
		$('#signup_modal').show();
		$('input#name').focus();
		$('div.info').show();
	});
	
	$('.modal_overlay').live('click', function(){
		$('#signup_modal').hide();
		$('div.error').hide();
		$('div.info').hide();
		$(this).hide();
	});
	
	$('.close_modal').live('click', function(){
		$('.modal_overlay').click();
	});
	
	$('.mini-modal-btn-close').live('click', function(){
		$('.mini-modal-overlay').hide();
		$('.mini-modal-inner iframe').remove();
	});
});
