$( document ).ready( function(){		

	var validator = $("#c-emailform").validate({ 
        rules: { 
            cemail: { 
                required: true, 
                email: true 
            } 
        } 
    }); // end validate email form
	
	$('.icon-sizer').click( function(){
		
		var imgw = $(this).parent().find(".pwidth").val();
		var imgh = $(this).parent().find(".pheight").val();
		
		$(this).parents("form").find("#photowidth").val(imgw);
		$(this).parents("form").find("#photowidth").change();
		$(this).parents("form").find("#photoheight").val(imgh);

	});

	$('a.toggleft').click( function(){
		var box = $(this).next('div.feedtypearticles');
		if (box.is(":hidden")){
			box.slideDown(200);
			$(this).addClass("selectedtoggle");
		}
		else{
			box.slideUp(200);
			$(this).removeClass("selectedtoggle");
		}

	});

	$('a.c-theme-icon')
		.click( function(){
			savingMessage();
		});


	$('a.c-bit-link-edit, a.c-bit-type-add')
		.click( function(){
			var bar = $(this).parent().parent();
			var box = bar.next('.c-bit-box');
			var content = box.next('.c-bit-content');
			
			if (box.is(":hidden")){
				bar.css("border-bottom-width","0px");
				box.slideDown("fast");
				content.slideUp("fast");
			}
			else {
				box.slideUp("fast");
				content.slideDown("fast");
				bar.css("border-bottom-width","1px");
			}
		});
	
	// Photo gallery element - get width of bit and set it
	
	$('a.setphotowidth')
		.click( function(){
			var bitwidth = parseInt($(this).parents(".bit.photo").css("width"));
			$(this).parent().siblings("input#photowidth").val(bitwidth);
			$(this).parent().siblings("input#photowidth").change();
			return false;
		});

	$('input#photowidth')
		.change( function(){
			var bitwidth = parseInt($(this).parents(".bit.photo").css("width"));
			var curwidth = $(this).val();
			if(curwidth > bitwidth){
				$(this).addClass("error");
				$(this).siblings("label").find("a").after('<span style="color:red;"><br />Warning, this width is larger than recommended, try <strong>'+bitwidth+'</strong> instead.</span>');
			}
			else{
				$(this).removeClass("error");
				$(this).siblings("label").find("span").hide();
			}
			return false;
		});

	// BREAKING NEWS
	$('.c-bulletin a.c-close-bulletin')
		.click( function(){
			$('.c-bulletin').hide();
		});

	
	$('.c-blink')
		.focus( function(){
			if ( $( this ).attr('value') == $( this ).attr('title') ) {
				 $( this ).attr({ 'value': '' });
				 $( this ).addClass('c-black');
			}
		})
		.blur( function(){
			if ( $( this ).attr('value') == '' ) {
				$( this ).attr({ 'value': $( this ).attr('title') });
				$( this ).removeClass('c-black');
				$( this ).removeClass('error');
			}
		});
		
	$('input.makeurl')
		.blur( function(){
			var newURL = $( this ).attr('value').toLowerCase();
			newURL = newURL.replace(/[^a-z0-9]/g,"-"); // find only letters and numbers
			newURL = newURL.replace(/-+/g,"-"); // remove duplicate dashes
			
			if ( $( this ).parent().parent().find('input.geturl').val() == ""){	
				$( this ).parent().parent().find('input.geturl').val( newURL );		
			}
		});

	$('input#eventhastime')
		.click( function(){
			if($(this).is(':checked')){
				$(this).parent().parent().find(".selecteventstarttime").show();
				$(this).parent().parent().find(".selecteventendtime").show();
			}
			else{
				$(this).parent().parent().find(".selecteventstarttime").hide();
				$(this).parent().parent().find(".selecteventendtime").hide();
			}
		});

	$('input.check.blogfeed')
		.click( function(){
			var curid = $(this).attr("id");
			if($(this).is(':checked')){
				$(this).siblings('.c-feedtype-author').find('.c-author-'+curid).show();
				$(this).siblings('.c-feedtype-tag').find('.c-tag-'+curid).show();
			}
			else{
				$(this).siblings('.c-feedtype-author').find('.c-author-'+curid).hide();
				$(this).siblings('.c-feedtype-author').find('.c-author-'+curid+ ' input').attr('checked','');
				$(this).siblings('.c-feedtype-tag').find('.c-tag-'+curid).hide();
				$(this).siblings('.c-feedtype-tag').find('.c-tag-'+curid+ ' input').attr('checked','');
			}
		});


	// feed type select changes

	$('select#feedtype')
		.change( function(){
			 var selected = $(this).find('option:selected');       
			 if(selected.val() == "author"){  
				$(this).parent().find('div.c-feedtype-tag').hide();
				$(this).parent().find('div.c-feedtype-author').show();
			 }  
			 else if(selected.val() == "tag"){
				$(this).parent().find('div.c-feedtype-author').hide();
				$(this).parent().find('div.c-feedtype-tag').show();
			 }
			 else{
				$(this).parent().find('div.c-feedtype-author').hide();
				$(this).parent().find('div.c-feedtype-tag').hide();
			 }
		});
		
	
	// form items
	
	$('.c-bit-box .form-item input, .c-bit-box .form-item select, .c-bit-box .form-item textarea')
		.focus( function(){
			$('.c-bit-box .form-item').removeClass("selectedfi");
			if( !$(this).hasClass("c-addtags") ){
				$(this).parent().addClass("selectedfi");
			}
		});
	
	$('.c-bit-box .form-item')
		.click( function(){
			$('.c-bit-box .form-item').removeClass("selectedfi");
			if( !$(this).hasClass("choose-tags") && !$(this).hasClass("blurb") ){
				$(this).addClass("selectedfi");
			}
		});

	$('.c-bit-box .form-item.makeurl a.saveurl')
		.click( function(){
			if($(this).siblings("input.geturl").hasClass("editurl")){
				$(this).siblings("input.geturl").removeClass("editurl");
				$(this).html("edit url");
				var curtable = $(this).parent().parent().siblings("input.c-curtable").val();
				var curid = $(this).parent().parent().siblings("input."+curtable+"id").val();
				var curvalue = $(this).siblings("input.geturl").val();
				$.ajax({
					type: "POST",
					url: "../resources/include/ajax.php?a=savefield&table="+curtable+"&id="+curid+"&field=url",
					data:  "value="+curvalue 
				});			

			}
			else{
				$(this).siblings("input.geturl").addClass("editurl");
				$(this).html("save");
				
			}
		});
	
	
	var curblogid= $('input.curblogid').val();
	$('input.c-addtags').autocomplete( '../resources/include/ajax.php?a=gettags&blog='+curblogid, {selectFirst:false} );
	//$('input.c-addtags').autocomplete( ['reviews','newbie','oldbie'] );
	
	$('input.c-addtags').bind('keypress', function(e) {
			if(e.keyCode==13){
				var blogid = $(this).prev('input.curblogid').val();
				var curvalue = $(this).val();
				var exists = false;
				var newid = "";
				var theinput = $(this);
				$.ajax({
					type: "POST",
					url: "../resources/include/ajax.php?a=addnew&table=tag&blog="+blogid,
					data:  "tagname="+curvalue,
					dataType: "text",
					success: function(msg){
						 //alert( "New ID: " + newid );
						 var msgarr = msg.split(",");
						 if (msgarr[0] == "old"){
						 	exists = true;
						 }
						 newid = msgarr[1];
					
						theinput.val("");
						if (exists){
							theinput.siblings('.c-tag').find('input#tag'+newid).attr("checked","checked");
							theinput.siblings('.c-tag').find('input#tag'+newid).next("label").addClass("c-checkedoff");
						}
						else{
							theinput.siblings('.c-tag-box').append('<div class="c-tag"><input class="check" type="checkbox" value="'+newid+'" name="tag'+newid+'" id="tag'+newid+'" checked="checked"/><label class="c-checkedoff" for="tag'+newid+'">'+curvalue+'</label></div>');
						}
							
							
					}
				});

				return false;
			}
	});
	
	$('.c-tag label')
		.click( function(){
			if( $(this).hasClass("c-checkedoff") ){
				$(this).removeClass("c-checkedoff");
				$(this).prev("input").val("");
			}
			else{
				$(this).addClass("c-checkedoff");	
				$(this).prev("input").val( $(this).prev("input").attr("title") );
			}
	
		});



		// JQUERY UI elements


		

		// Make bit headers sortable		

		$(".contentarea").sortable({
			items:'.bit:not(.add, .article, .event)',
			handle:'.c-bit-bar:not(.add, .article, .event) .c-drag-drop',
			placeholder: 'c-empty-sort-box',
			forcePlaceholderSize: true,
			stop: function(event, ui) { 
				var bits = $(this).sortable("serialize");
				savingMessage();
				window.location="../resources/include/action.php?a=bitswap&"+bits;
			}
			/*
			update: function(event, ui) { 
				var bits = $(this).sortable("serialize");

				//alert(bits);	
				$.ajax({
					   type: "POST",
					   url: "../resources/include/ajax.php?a=bitswap&"+bits
					 });			
			}
			*/
			//connectWith: '.contentarea'
		});
		
		//Datepicker
		$('input.datepick').datepicker({showOn:'focus', dateFormat: 'yy-mm-dd'});

		$(".c-bit-bar")
			.hover(
			function() {
				$(this).find('.c-drag-drop').show();												  
				$(this).find('.c-bit-link-edit').addClass('c-is-brighter');												  
			},
			function() {
				$(this).find('.c-drag-drop').hide();
				$(this).find('.c-is-brighter').removeClass('c-is-brighter');												  
			}
			);


		$(".c-bit-bar").addClass("ui-widget ui-helper-clearfix ui-corner-all")
			.find(".c-bit-bar")
				.addClass("ui-widget-header ui-corner-all")
				.prepend('<span class="ui-icon ui-icon-plusthick"></span>')
				.end()
			.find(".c-bit-content");

		
});	


// FOR CMS
tinyMCE.init({
	mode : "specific_textareas",
	editor_selector : "c-editor",
	plugins : "inlinepopups,imagemanager,safari,media",
    dialog_type : "modal",
	width : "100%",
	theme : "advanced",
	//theme_advanced_layout_manager : "RowLayout",
	//theme_advanced_containers : "toolBar1,toolBar2,toolBar3,toolBar4",
	theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,undo,redo,bullist,numlist",
	theme_advanced_buttons3 : "formatselect,styleselect",
	theme_advanced_buttons4 : "link,anchor,|,insertimage,media,|,code",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_toolbar_align : "left",
	theme_advanced_toolbar_location : "top",
	theme_advanced_resizing : true,
	theme_advanced_resize_horizontal : false,
	theme_advanced_styles : "Image Right=imageright;Image Left=imageleft;Color 1=txtcolorone;Color 2=txtcolortwo;Color 3=txtcolorthree",
	extended_valid_elements : "a[style|class|id|name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],div[class|id],ul[class|id],font[face|size|color|style],span[class|align|style],iframe[src|style|width|height|frameborder|scrolling],script[language|type|src]"
});




// FOR COMMENT FORMS
tinyMCE.init({
	mode : "specific_textareas",
	editor_selector : "c-comment",
	plugins : "inlinepopups,safari",
    dialog_type : "modal",
	width : "430px",
	theme : "advanced",
	theme_advanced_buttons1 : "bold,italic,underline",
	theme_advanced_buttons2 : "",
	theme_advanced_buttons3 : "",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	extended_valid_elements : ""


});

function savingMessage(){
		$('.c-admin-header').append('<div id="c-dark-overlay"><p>');
		$('#c-dark-overlay p').html('saving...');
}

function selectFormItem(obj){
		$('.c-bit-box .form-item').removeClass("selectedfi");
		obj.addClass("selectedfi");
}


function toggleDrawer(){
	$( "#c-admin-drawer" ).slideToggle("slow");
}

function previewPage(){
	if ($("a.c-preview-page").hasClass("c-edit-page")){
		$( ".c-p" ).show("slow");
		$("a.c-preview-page").removeClass("c-edit-page");
	}
	else {
		$( ".c-p" ).hide("slow");
		$("a.c-preview-page").addClass("c-edit-page");
	}
}

/*
function toggleBit(id, type){
		
	if ($(  "#c-"+type+"-box"+id ).is(":hidden")){
		$( "#c-"+type+"-bar"+id).css("border-bottom-width","0px");
		
		$( "#c-"+type+"-content"+id ).slideUp("fast");
		$( "#c-"+type+"-box"+id ).slideDown("fast");
	}
	else {
		$("#c-"+type+"-box"+id ).slideUp("fast");
		$("#c-"+type+"-content"+id ).slideDown("fast");
		$("#c-"+type+"-bar"+id ).css("border-bottom-width","1px");
	}

}
*/

function deletethis(i, s, p, table){
	var theanswer = confirm('Are you sure you want to delete this?');
	if(theanswer){
		window.location = "../resources/include/action.php?a=delete&table="+table+"&del="+i+"&site="+s+"&page="+p;
	}
}
function deleteimg(i, s, p, slideshow){
	var theanswer = confirm('Are you sure you want to delete this image?');
	if(theanswer){
		window.location = "../resources/include/deleteimage.php?show="+slideshow+"&page="+p+"&site="+s+"&del="+i;
	}
}

function settime (time) {
	var hour= ( document.getElementById(time+'hour').value == 12 ? 0 : document.getElementById(time+'hour').value);
	hour = ( document.getElementById(time+'p').value == 'PM' ? parseInt(hour) + 12 : hour );
	document.getElementById(time).value = hour +":"+ document.getElementById(time+'min').value +":00";
}


