var composeDialogDiv;
var composeTinyMCEOptions;

function composeAjaxSubmit(args){
	
	if(typeof(args.errorMsg) == 'undefined')
		args.errorMsg = composeErrorMsg;
			
	var $ = jQuery;
	$.ajax({
		url: args.href,
		dataType: "json",
		data: args.params,
		success: function(data){
			if (data.success == true) {
				if (typeof(args.successMsg) != 'undefined') {
					var successDiv = $("#site-successes");
					if (successDiv.length == 0) {
						successDiv = $('<div id="site-successes"/>');
						$('#site-content').before(successDiv);
					}
					successDiv.html(args.successMsg + '<div class="ui-icon ui-icon-circle-close" onclick="jQuery(this).parent().fadeOut();">dismiss</div>');
					successDiv.fadeIn();
					setTimeout(function(){
						successDiv.fadeOut();
					}, 60000);
				}
				
				if (typeof(args.successCallback) == "function") 
					args.successCallback(data);
			}
			else {
				var errorDiv = $("#site-errors");
				if (errorDiv.length == 0) {
					errorDiv = $('<div id="site-errors"/>');
					$('#site-content').before(errorDiv);
				}
				errorDiv.html(args.errorMsg + '<div class="ui-icon ui-icon-circle-close" onclick="jQuery(this).parent().fadeOut();">dismiss</div>');
				successDiv.fadeIn();
				for (var i in data.errors) {
					$('<li/>').appendTo(errorDiv.find('ul')).text(data.errors[i]);
				}
				$("#site-successes").html('');
			}
		}
	});
	
}

function ajaxLogin(){
	var $ = jQuery;
	$.getJSON(
		location.href,
		{
			'user_login_id': $('#user_login_id').val(),
			'user_login_password': $('#user_login_password').val(),
			'special-action': 'only-login'
		},
		function(data){
			if(data.success == true){
				var successDiv = $("#site-successes");
				if(successDiv.length == 0) {
					successDiv = $('<div id="site-successes"/>');
					$('#site-content').before(successDiv);
				}
				successDiv.html(composeAjaxLoginSuccesDivHtml);						
				$("#site-errors").remove();
				$('#site-content').load(window.location.href, {}, function(data){$(this).html(data);});
				$('.currentUser-username').text(data.user.username);
				$('#user-links').load(window.location.href, {'special-action':'only-load-macro', 'load-macro':'currentUserLinks'});

			}
			else{
				var errorDiv = $("#site-errors");
				if(errorDiv.length == 0) {
					errorDiv = $('<div id="site-errors"/>');
					$('#site-content').before(errorDiv);
				}
				errorDiv.html(composeAjaxLoginErrorDivHtml);
				for(var i in data.errors) {
					$('<li/>').appendTo(errorDiv.find('ul')).text(data.errors[i]);
				}
				$("#site-successes").html('');
			}
		}
	);
	return false;
}

function ajaxLogout(){
	var $ = jQuery;
	var exdate=new Date();
	exdate.setDate(exdate.getDate()-365);
	document.cookie="action=;path="+composeCookiePath+";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	$('.quickManagementEditLink').fadeOut();
	$('.quickManagementTool').fadeOut();
	$.ajax({
		url: composeAjaxLogoutLoadUrl,
		success: function(){
			$('#user-links').load(
				window.location.href,
				{'special-action':'only-load-macro', 'load-macro':'currentUserLinks'}
			);
			$('.currentUser-username').text(composeGuestUsername);
			var successDiv = $("#site-successes");
			if(successDiv.length == 0) {
				successDiv = $('<div id="site-successes"/>');
				$('#site-content').before(successDiv);
			}
			successDiv.html(composeAjaxLogoutSuccesDivHtml);
			$('#site-content').load(window.location.href, {}, function(data){$(this).html(data);});
		}
	});
	return false;
}

function startQuickManagement() {
	var $ = jQuery;
	$('.quickManagementEditLink').fadeIn();
	$('.quickManagementTool').fadeIn();
	document.cookie="action=quick-management;path="+composeCookiePath+";";
	$('.currentUser-manage-site-link').hide();
	$('.currentUser-stop-manage-site-link').show();
	$('.quickManageable').each(function(){
		if(typeof $(this).data('quickManage') == 'function'){
			$(this).data('quickManage')();
		}
	});
}

function stopQuickManagement() {
	var $ = jQuery;
	$('.quickManagementEditLink').fadeOut();
	$('.quickManagementTool').fadeOut();
	$('.currentUser-manage-site-link').show();
	$('.currentUser-stop-manage-site-link').hide();
	document.cookie="action=;path="+composeCookiePath+";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	$('.quickManageable').each(function(){
		if(typeof $(this).data('stopQuickManage') == 'function'){
			$(this).data('stopQuickManage')();
		}
	});
}

/* from w3schools */
function getCookie(c_name) {
	if(document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if(c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if(c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
      	}
	}
	return "";
}

function composeInputLoadLabelVals(){
	var label = $(this).text();
	var target = $(this).attr("for");
	target = $("#" + target + ', input[name="' + target + '"], textarea[name="' + target + '"]');
	
	var setLabelVal = function(){
		$(this).data('label', label);
		if ($(this).val().length == 0) {
			$(this).val(label);
			$(this).addClass("composeHasNoValue");
		}
		
		$(this).focus(function(){
			if($(this).hasClass("composeHasNoValue") && $(this).val() == $(this).data('label')) {
				$(this).val('');
			}
			$(this).removeClass("composeHasNoValue");
		});
		
		$(this).blur(function(){
			if($(this).val().length == 0) {
				$(this).val(label);
				$(this).addClass("composeHasNoValue");
			}
		});
	};

	target.each(setLabelVal);
}

function composeClearLabelValues(element){
	element.find("input.composeHasNoValue, textarea.composeHasNoValue").each(function(){
		if ($(this).val() == $(this).data('label')) {
			$(this).val('');
		}
	});
}

function composeOpenDialog(){
	var titleNode = composeDialogDiv.find('h1').first();
	var title = titleNode.text(); 
	titleNode.remove();
	composeDialogDiv.attr('title', title);
	composeDialogDiv.dialog({width: 600, title: title});
	composeDialogDiv.dialog("option", "title", title);
}

function composeLoaded($){
	
	$.ajaxSetup({
		type:"POST"
	});
	
	composeTinyMCEOptions = {
		script_url : composeTinyMCEUrl,
	    
		// General options
		theme : "advanced", 
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", 
	
		// Theme options 
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect", 
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", 
		theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen", 
		theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak", 
		theme_advanced_toolbar_location : "top", 
		theme_advanced_toolbar_align : "left", 
		theme_advanced_statusbar_location : "bottom", 
		theme_advanced_resizing : true,
		
		// Code options
		convert_urls: false,
	    remove_linebreaks: false,
	    apply_source_formatting: false,
	    valid_elements: "*[*]",
		
		// Layout
	    // content_css: quickEditPageTinyMCEContentCss,
	    
		// Drop lists for link/image/media/template dialogs
		template_external_list_url: "lists/template_list.js",
	    external_link_list_url: "lists/link_list.js",
	    external_image_list_url: "lists/image_list.js",
	    media_external_list_url: "lists/media_list.js",
	    
		// Language
		language: composeLanguage,
	    
		file_browser_callback: composeTinyMCEFileBrowser
	};

	var div = $('#site-dialog');
	if (div.length == 0) {
		div = $('<div id="site-dialog"/>');
		div.appendTo("body");
	}
	composeDialogDiv = div;
	
	div = $('.ajaxStatusGlobal');
	div.ajaxSend(function(){
		div.children('.ajaxStatusComplete').fadeOut();
		div.children('.ajaxStatusLoading').fadeIn();
	});
	
	div.ajaxStop(function(){
		div.children('.ajaxStatusLoading').fadeOut();
		div.children('.ajaxStatusComplete').fadeIn();
	});
	
	/*$("body").ajaxComplete(function(){
		$(this).find("label").each(composeInputLoadLabelVals);
	});*/
	
	$("a[rel]").live("click", function(){
		target = $($(this).attr("rel"));
		target.load($(this).attr("href"));
		return false;
	});
	
	if (getCookie('action') == 'quick-management') {
		$('.currentUser-manage-site-link').hide();
		$('.currentUser-stop-manage-site-link').show();
		$('.quickManagementEditLink').show();
		$('.quickManagementTool').show();
	}
	
	$("label").each(composeInputLoadLabelVals);
	$("body").ajaxStop(function(){$("label").each(composeInputLoadLabelVals);});
	
	$(".composeToggleTinyMCE").live('click', function(){
		$('.composeTextEditor').each(function(){
			var textarea = $(this);
			if (typeof(textarea.data("autoResizeField")) == 'undefined' || textarea.data("autoResizeField") != true) {
				try {
					if (textarea.data('tinymceVisibility') == true) {
						textarea.tinymce().hide();
						textarea.data('tinymceVisibility', false);
					}
					else {
						textarea.tinymce().show();
						textarea.data('tinymceVisibility', true);
					}
				}
				catch(err){
					if (typeof(textarea.data('tinyMceOptions')) != 'undefined') 
						textarea.tinymce(textarea.data('tinyMceOptions'));
					else {
						textarea.tinymce(composeTinyMCEOptions);
					}
					textarea.data('tinymceVisibility', true);
				}
			}
		});
	});
	
	$(".compose-tabs").tabs();
}

function composeTinyMCEFileBrowser(fieldName, url, type, win){	
	tinyMCE.activeEditor.windowManager.open({
        file : 'http://'+composeSiteCallUrl+'/filedialog?caller=TinyMCE&fileType='+type,
        title : 'Compose File Dialog',
        width : 600,
        height : 500,
        resizable : "yes",
        inline : "yes",
        close_previous : "no"
    }, {
        window : win,
        input : fieldName
    });
	win.document.getElementById("filedialog_selected_file_url").value = url;
	
	return false;
}

jQuery(composeLoaded);

