/***
Author : Teddy Moussignac
Purpose: Overall site client functionalities
****/

$(document).ready(function(){
	
	$('.popup').popupWindow({ 
		height:900, 
		width:1200, 
		top:50, 
		left:50,
		centerScreen:1, 
		location:1,
		scrollbars:1,
		status:0
	}); 
	
	//external
	$('.feed_list a').attr('rel','external');

	//nav starts
	$("#nav li:last-child").addClass("last");
	$('#nav li').mouseenter(function(){
		$(this).find('.dropdown').show();
	}).mouseleave(function(){
		$(this).find('.dropdown').hide();
	});
	//nav ends
	
	//delete buttons starts
	$('.del_sub').unbind('click').click(function(){
		var r=confirm("This Data Will be Forever Deleted");
		if (r==true){
  			return true;
  		}else{
  			return false;
  		}
	});
	//delete button ends
	
	$('li.entry img, .search_res li img, .teaser img, .content img').parent().attr({href : 'javascript://'});
	//post category field ends;
	
	//admin bar starts
	
	
	$('#admin_bar .item').mouseenter(function(){
		$(this).find('.item-menu').slideDown();
	}).mouseleave(function(){
		$(this).find('.item-menu').slideUp();
	});
	//admin bar ends
	
	//block info starts
	$('#path_click').toggle(function(){
		$('.block_info').show();
		$('.block_info').parent().addClass("obj_size");
		//$('.edit').show();
		$.cookie("edit_mode", "true", { path: '/', expires: 10 });
		
	}, function(){
		$('.block_info').hide();
		$('.block_info').parent().removeClass("obj_size");
		//$('.edit').hide();
		$.cookie("edit_mode", null, { path: '/', expires: 10 });
	});
	
	if($.cookie("edit_mode") == "true"){
		$('.block_info').show();
		$('.block_info').parent().addClass("obj_size");
	}else{
		$('.block_info').hide();
		$('.block_info').parent().removeClass("obj_size");
	}
	
	
	$('#admin_bar_switch').toggle(
		function(){
			$.cookie("switch_on", "true", { path: '/', expires: 10 });	
			$('#admin_bar').show();
			$(this).removeClass('off');
		},
		function(){
			$.cookie("switch_on", null, { path: '/', expires: 10 });
			$('#admin_bar').hide();
			$(this).addClass('off');
		}
	);
		//$('#admin_bar').slideToggle();
	
	if($.cookie("switch_on") == "true"){
		$('#admin_bar').show();
		$('#admin_bar_switch').removeClass('off');
	}else{
		$('#admin_bar').hide()
		$('#admin_bar_switch').addClass('off');
	}
	
	//block editor scripts
	$('.block_info').unbind('click').click(function(){
		
		//block mini form edit
		$('body').append('<div id="block_form_loader"></div>');
		$('#block_form_loader').find('.loading_gif').remove();
		$('#block_form_loader').append('<span class="loading_gif b"></span>');
		$.post('/ajax/block/edit/?block_id='+ $(this).attr('href'), function(res){
			$('#block_form_loader').html(res);
			if($.browser.mozilla){
				$('.rounded').corner();
			}
			if($.browser.safari){
				if($.browser.version >= parseInt('531.21.8') ){
					$('.rounded').corner();
				}
			}
			$('.mini_block_editor textarea').wysiwyg();
			$('.mini_block_editor .close').click(function(){
				$('#block_form_loader').remove(); 
			});
			
			$('#update_block_btn').unbind('click').click(function(){
				$('.mini_block_editor').find('.loading_gif, .success').remove();
				$('#update_block_btn').after('<span class="loading_gif b"></span>');
				$.post('/ajax/block/update/?block_id='+ $(this).attr('href'), $('#mini_block_editor_form').serialize(), function(data){
					$('#update_block_btn').after(data);
					$('.loading_gif').remove();
				});
				return false;
			});
			
			$('.mini_block_editor .txt').focus(function(){ $(this).addClass('active') }); 
			$('.mini_block_editor .txt').blur(function(){ $(this).removeClass('active') }); 
			
			$('.block_type_input li').click(function(){
				var type_item = ($(this).find('.value').val());
				if( type_item == 'query'){
					$('#query_field').removeClass("hide");
				}else{
					$('#query_field').addClass("hide");
				}
			});
			
			$('.mini_block_editor .txt').corner();
			$('.mini_block_editor textarea').parent().find('.wysiwyg iframe:not(.processed)').TextAreaResizer();
			$('#block_form_loader .mini_block_editor iframe').css({'min-height' : $('#block_form_loader').height() - 220});
			
		});
		
		return false;
	});
	
	//post editor scripts
		//create
	$('.post_create').unbind('click').click(function(){
		
		//block mini form edit
		$('body').append('<div id="block_form_loader"></div>');
		$('#block_form_loader').find('.loading_gif').remove();
		$('#block_form_loader').append('<span class="loading_gif b"></span>');
		$.post('/ajax/get_block/?path=/apps/marie/post_editor', function(res){
			$('#block_form_loader').html(res);
			$('.loading_gif').remove();
			if($.browser.mozilla){
				$('.rounded').corner();
			}
			if($.browser.safari){
				if($.browser.version >= parseInt('531.21.8') ){
					$('.rounded').corner();
				}
			}
			$('.mini_block_editor textarea').wysiwyg();
			$('.mini_block_editor .close').click(function(){
				$('#block_form_loader').remove(); 
			});
			//post datas starts
			$('#create_block_btn').unbind('click').click(function(){
				$('.mini_block_editor').find('.loading_gif, .success, .error').remove();
				$('#create_block_btn').after('<span class="loading_gif b"></span>');
				if($('#post_title').val() != ''){
					if($('#mini_block_editor_form #block_txt').val() != ''){
						$.post('/ajax/posts/new/', $('#mini_block_editor_form').serialize(), function(data){
							$('#create_block_btn').after(data);
							$('.loading_gif').remove();
						});	
					}else{
						$('#mini_block_editor_form #block_txt').after("<span class='error'>Content cannot be empty</span>");
					}
				}else{
					$('#post_title').after("<span class='error'>Title cannot be empty.</span>");
				}
				return false;
			});
			//post dats ends
			$('.mini_block_editor .txt').focus(function(){ $(this).addClass('active') }); 
			$('.mini_block_editor .txt').blur(function(){ $(this).removeClass('active') }); 
			
			$('.block_type_input li').click(function(){
				var type_item = ($(this).find('.value').val());
				if( type_item == 'query'){
					$('#query_field').removeClass("hide");
				}else{
					$('#query_field').addClass("hide");
				}
			});
			
			$('.mini_block_editor .txt').corner('5px');
			$('.mini_block_editor textarea').parent().find('.wysiwyg iframe:not(.processed)').TextAreaResizer();
			$('#block_form_loader .mini_block_editor iframe').css({'min-height' : $('#block_form_loader').height() - 240});
			
			$('#post_title').blur(function(){
    				$.post('/ajax/title_auth/', $('#mini_block_editor_form').serialize(), function(res){
    				$('#edit_post').find('.error').remove();
					$('#post_title').after(res);
				});
    		});
			
		});
		
		return false;
	});
		//edit
	$('.post_edit').unbind('click').click(function(){
		
		//block mini form edit
		$('body').append('<div id="block_form_loader"></div>');
		$('#block_form_loader').find('.loading_gif').remove();
		$('#block_form_loader').append('<span class="loading_gif b"></span>');
		$.post('/ajax/get_block/?path=/apps/marie/post_editor&post_id='+$(this).attr('href') + '&type=' + $(this).attr('title'), function(res){
			$('#block_form_loader').html(res);
			$('.loading_gif').remove();
			if($.browser.mozilla){
				$('.rounded').corner();
			}
			if($.browser.safari){
				if($.browser.version >= parseInt('531.21.8') ){
					$('.rounded').corner();
				}
			}
			$('.mini_block_editor textarea').wysiwyg();
			$('.mini_block_editor .close').click(function(){
				$('#block_form_loader').remove(); 
			});
			
			$('#update_block_btn').unbind('click').click(function(){
				$('.mini_block_editor').find('.loading_gif, .success').remove();
				$('#update_block_btn').after('<span class="loading_gif b"></span>');
				$.post('/ajax/posts/edit/?id='+ $(this).attr('href'), $('#mini_block_editor_form').serialize(), function(data){
					$('#update_block_btn').after(data);
					$('.loading_gif').remove();
					$('.set_teaser').text('+ set new teaser');
				});
				return false;
			});
			
			$('.mini_block_editor .txt').focus(function(){ $(this).addClass('active') }); 
			$('.mini_block_editor .txt').blur(function(){ $(this).removeClass('active') }); 
			
			$('.block_type_input li').click(function(){
				var type_item = ($(this).find('.value').val());
				if( type_item == 'query'){
					$('#query_field').removeClass("hide");
				}else{
					$('#query_field').addClass("hide");
				}
			});
			
			$('.mini_block_editor .txt').corner();
			$('.mini_block_editor textarea').parent().find('.wysiwyg iframe:not(.processed)').TextAreaResizer();
			$('#block_form_loader .mini_block_editor iframe').css({'min-height' : $('#block_form_loader').height() - 240});
			
			
			$('.set_teaser').click(function(){
				$(this).text("+ New teaser was successfully set.");
				$('.mini_block_editor input#posts_teaser').val(getSelectedText());
			});
			
		});
		
		return false;
	});	
	
	//post scripts end
	//block info ends
	
	//refresh
	$('.refresh').click(function(){
		location.reload();
	});
	
	
	$('.pop').unbind('click').click(function(){
		$('#data_loader').remove();
		$(this).parent().append('<div id="data_loader"><img src="#" alt="" /></div>');
		$('#data_loader').corner();
		$('#data_loader').css({'top' : $(this).position().top - 50});
		$('#data_loader').find('img').fadeIn().attr({src : $(this).attr('href')});
		return false;
	});
			
	$('.image_list').mouseleave(function(){
		$('#data_loader').fadeOut();
	});
	//photo menu init ends
	
	/*** search page functions start ***/
	
	//search input
	$('.search_input').click(function(){
		if($(this).val() == 'search'){
			$(this).val('');
		}
	});
	$('.search_input').blur(function(){
		if($(this).val() == ''){
			$(this).val('search');
		}
	});
	
	//advanced search
	$('.customize_res').find('input').each(function(){
		var item = "#" + $(this).attr('id') + "_block";
		$(this).change(function(){
			if($(this).is(':checked')){
				$(item).show();
			}else{
				$(item).hide();
			}
		});
		
		//default
		if($(this).is(':checked')){
			$(item).show();
		}else{
			$(item).hide();
		}
	});
	/*** search page function end ***/
	
	//rounded
	if($.browser.mozilla){
		$('.rounded, #login_bar, #register_user, #forgot_pswd_form, #disable_account_form, .rt_rail .block li, .rt_rail .block li .num, #user_settings_loader, .pager li a, .customize_res fieldset, .search_page .page ul.photo_res li, .block_title, h3.admin, body.marie .report, body.marie table.blocks, body.marie .form_editor, #marie_ct h4').corner();
		$('#admin_bar, #admin_bar .item-menu, #admin_bar_switch').corner('top');
		$('body.marie .text,  body.marie .txt').corner('5px');
		//$('body.marie .form_editor').corner('bottom');
	}
	
	if($.browser.safari){
		if($.browser.version >= parseInt('531.21.8') ){
			$('.rounded, #login_bar, #register_user, #forgot_pswd_form, #disable_account_form, .rt_rail .block li, .rt_rail .block li .num, #user_settings_loader, .pager li a, .customize_res fieldset, .search_page .page ul.photo_res li, .block_title, h3.admin, body.marie .report, body.marie table.blocks, body.marie .form_editor, #marie_ct h4').corner();
			$('#admin_bar, #admin_bar .item-menu,  #admin_bar_switch').corner('top');
			$('body.marie .text,  body.marie .txt').corner('5px');
			//$('body.marie .form_editor').corner('bottom');
		}
	}
	
	
	
	/*** comments form starts ***/
	//add
	$('#comment_edit #comment_sub').click(function(){
		if(($('#comment_content').val() != "") && ($('#comment_content').val().length > 5)){
					
		//action
			$.post('/ajax/comments/?add=true', $('#comment_edit').serialize(),function(){
				$('#comment_list').append('<li class="rounded"><p class="content">'+ $('#comment_content').val() +'</p><div class="clearer"></div></li>');	
				$('#comment_edit').find('span.error').remove();
				$('#comment_edit #comment_user').val('');
				$('#comment_edit #comment_content').val('');
				$('#comment_edit').find('.wysiwyg').slideUp();
				$('#comment_edit').append('<span class="success">Your comment was added!</span>');
				if($.browser.mozilla){
					$('.rounded').corner();
				}
				if($.browser.safari){
					if($.browser.version >= parseInt('531.21.8') ){
						$('.rounded').corner();	
					}
				}
			});
					
		}else{
			$('#comment_edit').find('span.error').remove();
			$('#comment_content').after('<span class="error">Comment cannot be empty</span>');
		}
		return false;
	});
	
	//delete
	$('#comment_list li .del_sub').unbind('click').click(function(){
		$.post('/ajax/comments/?delete=true&comment_id=' + $(this).parent().find('.cmt_id').val());
		$(this).parent().fadeOut();
		return false;
	});	
	/*** comments form ends ***/
	
	/** upload form load effect starts **/
	//upload_file_form
	$('#upload_file_form .submit').click(function(){
		$('#upload_file_form').before('<span class="loading_gif b"></span>');
	});
	/** upload form load effect ends **/
	
	
    //wysig blog_txt
    $('.wysig').wysiwyg();
	$('.blog_txt').wysiwyg();
	
	$('textarea.resizable').parent().find('.wysiwyg iframe:not(.processed)').TextAreaResizer();
	$('textarea.resizable_single').TextAreaResizer();
	
	/***** validator ****/
	//register form validator starts
    $('#register_user').validate({
    	rules: {
    		user_password: {
				required: true,
				minlength: 5
			},
			user_password_2: {
				required: true,
				minlength: 5,
				equalTo: "#user_password"
			},
			user_name: {
				required: true
			},
			user_email: {
				required: true,
				email: true
			}
    	},
    	messages: {
    		user_password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long"
			},
			user_password_2: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long",
				equalTo: "Please enter the same password as above"
			},
			user_name: "Please enter a display name",
			user_email: "Please enter a valid email address"
    	},
    	submitHandler: function(form) {
   			//form.submit();
			$.post('/ajax/user/create/',  $("#register_user").serialize(), function(result){
    			$('.res_status').val(result);
    			$('#register_user').hide();
    			$('.register_user_conf').fadeIn();
    		});
		 }
    });
    //register form validator ends
		
	//contact validate
    $('#contact_us').validate({
    	rules: {
    		email: {
				required: true,
				email: true
			},
			name: {
				required: true
			},
			message: {
				required: true
			}
    	},
    	messages: {
    		email: "Please enter a valid email",
			name: "Please enter your name",
			message: "Please enter your message"
    	},
    	submitHandler: function(form) {
    		$('#contact_us').find('p.status').html('Sending');
    		$.post('/ProcessContact.do',  $("#contact_us").serialize(), function(result){
    			$('#contact_us').find('p.status').fadeIn('slow').html(result);
    			$("#contact_us .txt").val("");
    			$('.contact_form').animate({right: '-=50px'}).fadeOut();
    		
    		});
		 }
    });
    
    //post editor
    $('#post_title').blur(function(){
    	$.post('/ajax/title_auth/', $('#edit_post').serialize(), function(res){
    		$('#edit_post').find('.error').remove();
			$('#post_title').after(res);
		});
    });
	$('#edit_post').validate({
    	rules: {
			title: {
				required: true,
				minlength: 3
			},
			category : { required : true },
			content: {
				required: true,
				minlength: 40
			}
    	},
    	messages: {
    		category : "Please enter a tag",
			title: "Please enter a title",
			content: "Please enter content"
    	},
    	submitHandler: function(form) {
   			form.submit();
		 }
    });
    
    //gallery validator
    $('#gallery_form').validate({
    	rules: {
			gallery_title: {
				required: true,
				minlength: 3
			}
    	},
    	messages: {
    		gallery_title : "Please enter a Title"
    	},
    	submitHandler: function(form) {
   			form.submit();
		 }
    });
    
    //theme validator
    $('#theme_form').validate({
    	rules: {
			theme_name: {
				required: true,
				minlength: 3
			},
			theme_directory: {
				required: true
			}
    	},
    	messages: {
    		theme_name : "Enter a Theme name",
    		theme_directory : "Select the directory"
    	},
    	submitHandler: function(form) {
   			form.submit();
		 }
    });
    
    //photo validator
    $('#photo_form').validate({
    	rules: {
			photo_title: {
				required: true,
				minlength: 3
			},
			photo_url: {
				required: true
			}
    	},
    	messages: {
    		photo_title : "Enter photo title",
    		photo_url : "Select image file"
    		
    	},
    	submitHandler: function(form) {
   			form.submit();
		 }
    });
    
    //user login
    $('#login_form').validate({
    	rules: {
    		user_name: {
				required: true
			},
			user_pswd: {
				required: true
			}
    	},
    	messages: {
    		user_name: "Please enter your username",
			user_pswd: "Please enter your password"
    	},
    	submitHandler: function(form) {
   			form.submit();
		 }
    });
    
    //user login
    $('#login_init').click(function(){
    	$('#user_login_form').fadeIn();
    });
    $('body').click(function(){
        $('#user_login_form').fadeOut();
 	});
 	$('.login, #user_login_form').click(function(event){
   		event.stopPropagation();
	 });
	 $('#user_login_form').parent().click(function(event){
   		event.stopPropagation();
	 });
	 
    $('.logout_init').click(function(){
    	$.post('/ajax/logout/');
		location.reload();
    });
    
    $('#logger').click(function(){
    	$('#user_login_form').find('.error').remove();
    	$('#user_login_form').append('<span class="loading_gif b"></span>');
    	$.post('/ajax/login/', $('#user_login_form').serialize(), function(res){
    		var log_res = res;
			$('#user_login_form').prepend(log_res);
			if($(log_res).attr('class') != 'error'){
				location.reload();
			}
			$('.loading_gif').remove();
		});
    });
    
    //forgot password
    $('#forgot_pswd_form .checker').click(function(){
    	$('#forgot_pswd_form').prepend('<span class="loading_gif b"></span>');
    	$.post('/ajax/email_auth/', $('#forgot_pswd_form').serialize(), function(res){
			$('#forgot_pswd_form').find('#request_res').html(res);
			$('.loading_gif').remove();
			$.getScript("/resources/scripts/utils.js");
		});
    });
    //username auth
    $('#register_user #user_name').blur(function(){
    	$('#register_user').prepend('<span class="loading_gif b"></span>');
    	$.post('/ajax/username_auth/', $('#register_user').serialize(), function(res){
    		$('#register_user').find('.error').empty();
    		$('#register_user').find('.success').empty();
			$('#register_user').prepend(res);
			$('.loading_gif').remove();
			//$.getScript("/resources/scripts/utils.js");
		});
    });
    //useremail auth
    $('#register_user #user_email').blur(function(){
    	$('#register_user').prepend('<span class="loading_gif b"></span>');
    	$.post('/ajax/useremail_auth/', $('#register_user').serialize(), function(res){
    		$('#register_user').find('.error').empty();
    		$('#register_user').find('.success').empty();
			$('#register_user').prepend(res);
			$('.loading_gif').remove();
			//$.getScript("/resources/scripts/utils.js");
		});
    });
     //disable account
    $('#disable_account_form .checker').click(function(){
    	$.post('/ajax/password_auth/', $('#disable_account_form').serialize(), function(res){
			$('#disable_account_form').find('#request_res').html(res);
			$.getScript("/resources/scripts/utils.js");
		});
    });
	
	
});

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
	var anchor = anchors[i];
	if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
	}
}
window.onload = externalLinks

function href(url){
	window.location.href=url;
}

function getSelectedText() {
	var iframe= document.getElementById('block_txtIFrame');
	var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility
	var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;

	
    if (iwin.getSelection) {
        return iwin.getSelection();
    }
    else if (idoc.selection) {
        return idoc.selection.createRange().text;
    }

    return '';
}

