var eid, p;
$(function() {


	$(window).scroll(function(e){
		var scrollTop = $(window).scrollTop();
		var cpTopOffset = 22;

		var h = $('#highlighter');
		h.css({ top: h.data('orig-top') - scrollTop });

		var cp = $('.cp-active');
		//cp.css({ position: 'fixed', top: cp.data('orig-top') + scrollTop });
		var cpParent = cp.parent();
		//cp.css({ position: 'fixed', top: cpParent.offset().top - scrollTop + cpParent.outerHeight() - cpTopOffset });
		cp.css({ position: 'fixed', top: h.top + cpParent.outerHeight() - cpTopOffset });
	});

	$('.site_view').each(function() {
		var myself = $(this);
		myself.data('orig-z-index', myself.css('z-index'));
	});
	
	$(".site_view").hover(
		function (e) {
			var borderSize = 4;
			var fadeTime = 200;
			var cpTopOffset = 22;

			var me = this;
			var editElement = $(me);
			var editElementOffset = editElement.offset();
			var editElementOuterHeight = editElement.outerHeight();
			var editElementOuterWidth = editElement.outerWidth();
	
			var highlighter = $('#highlighter');
			var highlighterZ = highlighter.css('z-index');

			// Elevate the z-index for the editable element
			editElement.css('z-index', highlighterZ + 1);

			// Move highlighter around it and fade in.
			highlighter.css({
				height: editElementOuterHeight + 'px',
				width: editElementOuterWidth + 'px',
				top: editElementOffset.top - $(window).scrollTop() - 2,
				left: editElementOffset.left - 2
			}).fadeIn(fadeTime
			).data('orig-top', editElementOffset.top
			).bind('mouseout', function() {
					//alert('out1');
					//$(me).css('z-index', $(me).data('orig-z-index'));
					//$(me).children('.cmsControlPanel').hide();
					//$(this).fadeOut(fadeTime);
			});

			// Activate child control node
			editElement.children(".cmsControlPanel").css({
				position: 'fixed',
				top: editElementOffset.top - $(window).scrollTop() + editElementOuterHeight - cpTopOffset,
				left: editElementOffset.left + 4,
				border: 'none',
				background: 'none',
				'z-index': highlighterZ + 1
			}).each(function() {
				var cp = $(this);
				cp.data('orig-top', cp.offset().top);
			}).addClass('cp-active').show();
		},
		function (e) {
			var me = this;
			var editElement = $(me); //alert('fadeOut');
			$('#highlighter').hide(); //fadeOut(fadeTime);
			editElement.children('.cmsControlPanel').removeClass('cp-active').hide();
			editElement.css('z-index', myself.data('orig-z-index'));
		}
	);
	
	
	/*$(".site_view").hover(
		function() {
			console.log("hover");
			$(this).children(".cmsControlPanel").show();
			$(this).css("cursor", "pointer");
		}
	);*/
	
	
	
	$("#cmsTree").click(
		function() {
			var $treeTab = $("#cmsTree");
			$treeTab.animate({
				left: parseInt($treeTab.css('left'),10) == -200 ? 0 : -200,
				height: parseInt($treeTab.css('height'),10) == 450 ? 40 : 450
			});
		});
	//$(".checked").click( function() {alert("123");});
	
	$(".addViewButton").click(function() {
		showViewList(this.id);
	});

	
	
	$(".CMS_configureView").click(function() {
		configureView(this.id);
	});

	$(".CMS_moveUp").click(function() {
		par = $(this).attr("class").split("^")[0];
		moveUpDown("up", this, par);
	});
	$(".CMS_moveDown").click(function() {
		par = $(this).attr("class").split("^")[0];
		moveUpDown("down", this, par);
	});
	
	$(".CMS_removeView").click(function() {
		par = $(this).attr("class").split("^")[0];
		removeView(this.id, par);
	});
});

function showControls() {
	childs = $(this).children;
	$(childs).last().show();
}
function hideControls() {
	childs = $(this).children;
	$(childs).last().hide();
}

function enableTogglingOfViewList() {
	$(".toggleTable").toggle(
		function () {
			$(this).removeClass("closed");
			$(this).addClass("opened");
			//$(this).siblings(".manageViewList").slideDown("fast");
			$(this).siblings(".manageViewList").show();
		},
		function () {
			$(this).removeClass("opened");
			$(this).addClass("closed");
			//$(this).siblings(".manageViewList").slideUp("fast");
			$(this).siblings(".manageViewList").hide();
		}
	);
}

function removeView(id, viewName) {
	element_id = id;
	eid = element_id;
	the_parent = viewName;
	//alert("name: " + this.id);
	//alert("parent: " + the_parent);
	
	if(confirm("Are you sure you want to delete this section?")) {
		//document.write(ui);
		$.ajax({
			type: "POST",
			url: "/json?ServiceId=CMSPersistentObjectService&Action=removeView&parent="+the_parent+"&removeView="+element_id,
			success: function(msg) {
				//alert(eid);
				$("[id*=--"+eid+"]").remove();
			}
		});
	}
}

function deleteCMSCategory(cat_id, displayName) {
	if(confirm("Are you sure you want to delete " + displayName + "?")) {
		//document.write(ui);
		$.ajax({
			type: "POST",
			url: "?ServiceId=AbstractTableService&Action=deleteNode&ResponseView=JSONServiceResultView&node=CategoryDataItem-"+cat_id,
			success: function(msg) {
				$("#"+cat_id).hide();
			}
		});
	}
}

function editCMSCategory(cat_id) {
	//the tr
	var currentName = $("#" + cat_id + " .catname").html();
	
	$("#" + cat_id + " .catname").html("<b>old:</b> " + currentName + "<br/><b>new:</b> <input id='" + cat_id + "_newCatName'></input>");
	$("#" + cat_id + " .editCatLink").html("<span id='" + cat_id + "_editLinks'><a href='javascript:;' onclick='updateCMSCategoryName("+cat_id+")'>Save</a> • <a href='javascript:;' onclick='cancelEditCMSCategory(" + cat_id + ",\"" + currentName + "\")'>Cancel</a></span>");
}

function cancelEditCMSCategory(cat_id, cat_name) {
	/*$("#"+ cat_id + "_newCatName").html(cat_name);
	$("#" + cat_id + "_editLinks").html("<a href='javascript:;' onclick='editCMSCategory(\"" + cat_id + "\")'>Edit</a> &bull <a href='javascript:;' onclick='deleteCMSCategory(\"" . $category['idCMSCategory'] . "\", \"" . $category['DisplayName'] . "\")'>Delete</a>)
	*/
	window.location.reload();
	
}

function updateCMSCategoryName(cat_id) {
	var newName = $("#" + cat_id + "_newCatName").val();
	
	$.ajax({
		type: "POST",
		url: "?ServiceId=AbstractTableService&Action=updateNode&ResponseView=JSONServiceResultView&node=CategoryDataItem-"+cat_id + "&DisplayName=" + newName,
		success: function(msg) {
//			$("#" + cat_id + "_newCatName").replaceWith("<td class='catname'>"+newName+"</td>");
			window.location.reload();
		}
	});
}
/**** THIS NEEDS SOME WORK****/
function assignLayoutCategory(layout_id) {
	var newLayout = $("#layoutCat").val();
	//alert(layout_id);
	
	$.ajax({
		type: "POST",
		url: "?ServiceId=CMSService&Action=UpdateCMSLayoutCategory&ResponseView=JSONServiceResultView&id="+layout_id + "&keyName=" + newLayout,
		success: function(msg) {
//			$("#" + cat_id + "_newCatName").replaceWith("<td class='catname'>"+newName+"</td>");
			//window.location.reload();
			window.close();
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
} //window.close();
		}
	});
}

function moveUpDown(upORdown, obj, the_parent) {		
	$.ajax({
		type: 'POST',
		url: "/json?ServiceId=CMSPersistentObjectService&Action=updateOrder&parent="+the_parent,
		data: {viewName : obj.id, updown: upORdown},
		cache: false,
		dataType: 'html',
		success: function(html) {
			window.location.reload();
		}
	});
}

function getDialogOpts(viewId, title) {
	return {
		"modal":true,
		"width":"auto",
		"title": title,
		"height":"auto",
		"minWidth":"auto",
		"close": function() {$('#'+viewId).dialog('destroy');$('#'+viewId).remove();}
	}
}

function showOptions() {
	$.ajax({
		type: "POST",
		url: "/json?ServiceId=CMSPersistentObjectService&Action=addViews&objectName="+parent+"&location="+loc,
		data: {newViews : fd},
		success: function(msg) {
			window.location.reload();
				//$('.ajaxLoader').hide();
				/*if (!ui.item.find('.removeView').length) {
						u = ui;
						ui.item.append("<div style='float: right' class='removeView' onclick='removeView(\""+ name +"\", \""+ loc +"\", \"" + ui.item.attr("id") + "\")'>x</div>");
				}*/
		}
	});
}
	
function configureView(id) {
	var theId = id;
	$.ajax({
		type: 'POST',
		url: "/viewConfigure",
		data: {viewName : theId},
		cache: false,
		dataType: 'html',
		success: function(html) {
			$('body').append('<div id="viewConfigure" style="display: none">' + html + '</div>');
			var vcDialogOpts = getDialogOpts("viewConfigure", "Configure this section");
			$("#viewConfigure").dialog(vcDialogOpts);
			
			//Syntax Highlighting
			var vclass = theId.split("|");
			vclass = vclass[0];
			if(vclass == "CMSLayoutDataItem")
			{
				var editor = CodeMirror.fromTextArea("layoutArea",
				{
					parserfile: ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js"],
					path: "/js/base/CodeMirror-0.67/js/",
					stylesheet: ["/js/base/CodeMirror-0.67/css/jscolors.css", "/js/base/CodeMirror-0.67/css/csscolors.css", "/js/base/CodeMirror-0.67/css/xmlcolors.css", "/js/base/CodeMirror-0.67/css/docs.css"]
				});
			}
		}
	});
}

var fd,par;
function addViews(formData) {
	fd = formData;
	//alert(sectionId);
    args = sectionId.split("__");
    loc = args[0];
	parent = args[1];
    scope = args[2];
	
	$.ajax({
		type: "POST",
		url: "/json?ServiceId=CMSPersistentObjectService&Action=addViews&parent="
            + parent + "&location=" + loc + "&scope=" + scope,
		data: {newViews : fd},
		success: function(msg) {
			window.location.reload();
		}
	});      
}

var sectionId;
function showViewList(id) {
	//alert(dialogOpts);
	sectionId = id;
	
	//alert(sectionId);
	$.ajax({
		type: 'POST',
		url: "/viewListDialog",
		cache: false,
		dataType: 'html',
		success: function(html) {
			$('body').append('<div id="viewList" style="display: none"><form id="viewListerForm" onsubmit=\"addViews($(\'#viewListerForm\').serializeArray());return false;\">' + html + '<button type="submit" class="CMSButton">Add Selected Views</button></form></div>');
			var vlDialogOpts = getDialogOpts("viewList", "Select views to add to this section");
			$("#viewList").dialog(vlDialogOpts);
		}
	});
}

/*function saveNav(formId, objName) {
	fdata = $("#"+formId).serializeArray();
	fd = fdata;
}*/

function addAnotherLink(formId, in_ex, url, id, title)
{
	if(id == undefined) {
		id = "00";
	}
	if(in_ex == "in") {
		dis = "readonly='true'";
		base = "";
	}
	else {
		dis = "";
		if(url == "") {
			base = "http://";
		}
		else {
			base = "";
		}
	}
	//alert(base);
	var d=new Date();
	wrap_id = d.getTime();
	url_raw = url;
	url_id = url_raw.replace(/\//g, "_");
	url_id = url_id.replace(/\./g, "");
	url_id = url_id.replace(/\:/g, "");
	
	var inputs = '<div class="navLinkWrapper" id="'+wrap_id+'"><label>Url:</label><input id="'+url_id+wrap_id+'__url" '+dis+'" name="linkUrl[]" /><label>Link Text:</label><input id="'+url_id+wrap_id+'__txt" name="linkText[]"><input name="idLink[]" type="hidden" value="NavLink-'+id+'"><div class="removeView controls" style="height: 20px; float: right" onclick="removeLink(\'NavLink-'+id+'\', '+wrap_id+')"></div></div>';
	$("#saveNav").attr("disabled", "");
	$("#"+formId).append(inputs);
	//alert(url_id);
	$("#"+url_id+wrap_id+'__url').val(base + url_raw);
	//alert(title)
	$("#"+url_id+wrap_id+'__txt').val(title);
}

function removeLink(node, wrap_id) {
	alert(wrap_id);
	if(node == "00") {
		$("#"+wrap_id).remove();
	}
	else {
		$.ajax({
			type: 'POST',
			url: "/?ServiceId=AbstractTableService&Action=deleteNode&node=" + node,
			cache: false,
			dataType: 'html',
			success: function(html) {
				$("#"+wrap_id).remove();
			}
		});
	}
}

function removeNav(node, wrap_id) {
	//alert(wrap_id);
	if(node == "00") {
		$("#"+wrap_id).remove();
	}
	else {
		$.ajax({
			type: 'POST',
			url: "/?ServiceId=LeftNavService&Action=deleteNav&node=" + node,
			cache: false,
			dataType: 'html',
			success: function(html) {
				$("#"+wrap_id).remove();
			}
		});
	}
}
var lin;
function editNav(idNavSection, links, objName, formId, navName)
{
/*	$('body').append('<div style="display: none"><form id="editNavSectionForm"><input type="hidden" name="ServiceId" value="LeftNavService" /><input type="hidden" name="Action" value="editNavigation" /><input type="hidden" name="objName" value="'+objName+'" /><input type="hidden" name="node" value="NavSection-'+idNavSection+'" /><button>Save Changes</button></form></div>');
*/
	$("#navEditPanel").tabs("select", "#createNewWrapper");
	lin = links;
	for(idx in links) {
		if(links[idx].url.indexOf("www") != -1 || links[idx].url.indexOf("http") != -1) {
			//alert("ex" + " " + links[idx].title);
			addAnotherLink(formId, "ex", links[idx].url, links[idx].idNavLink, links[idx].title);
		}
		else {
			addAnotherLink(formId, "in", links[idx].url, links[idx].idNavLink, links[idx].title);
		}
	}
	$("#navSectionAction").val("editNavigation");
	$("#navTitle").val(navName);
	$("#linkForm").append('<input type="hidden" name="node" value="NavSection-'+idNavSection+'">');
	//$("#navChooserForm").submit();
}

function CMSADMIN_enableControls(pmode) {
    pmode = pmode || 'page';
    $.ajax({
		url  : "",
		type : "GET",
        data : {
            ServiceId : 'CMSPersistentObjectService',
            Action : 'setAdminMode',
            mode :  pmode},
        success : function () {
			
			alert("Controls Enabled");
			
			}
    });
}

function CMSADMIN_disableControls() {

    $.ajax({
		url : "",
		type: "GET",	
        data : {
            ServiceId : 'CMSPersistentObjectService',
            Action : 'setAdminMode',
            mode :  'disabled'},
        success : function () { 
				alert("Controls Disabled");
			}
    });
}



function CMSADMIN_showMetaControl(btn) {
	if($("#CMSADMIN_Meta").is(":hidden")) {
		$("#CMSADMIN_Meta").slideDown("slow");
		$("#CMSADMIN_Metabtn").html("Hide Metadata");
	} else  {
		$("#CMSADMIN_Meta").hide();
		$("#CMSADMIN_Metabtn").html("Show Metadata");
	}
	
}

   // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
   function urlEncode(s)
   {
      return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
   }
   
  function urlDecode(s)
   {
      return decodeURIComponent( s.replace( /\+/g, '%20' ).replace( /\%21/g, '!' ).replace( /\%27/g, "'" ).replace( /\%28/g, '(' ).replace( /\%29/g, ')' ).replace( /\%2A/g, '*' ).replace( /\%7E/g, '~' ) );
   }

function CMSADMIN_manageFiles() {
	window.SetUrl=(function(id){
		return function(value)
		{
			//alert(value);
			value=value.replace(/[a-z]*:\/\/[^\/]*/,'');
			editor.insertIntoLine(editor.cursorLine(), editor.cursorPosition().character, value);
		}
	})(this.id);

	var kfm_url='/lib/kfm/index.php';
	window.open(kfm_url,'kfm','modal,width=600,height=400');
}

function MakeEditable(divId) {
	var config = {
	resize_enabled: false,
	width: 725,
	bodyId: "ckeContent",
	toolbar:
	[
            ['Source'],
	    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript', 'HorizontalRule'],
	    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
	    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
	    ['SpellChecker', 'Image', 'Link', 'Unlink'],
	    ['Styles','Format','Font','FontSize']
	]
    };
    //$("#"+divId).ckeditor(config);
    CKEDITOR.replace(divId, config);
}

function closeEditable(instance, wrapper) {
	instance = eval(instance);
	instance.destroy();
	$("#"+wrapper).dialog("destroy");
	$("#"+wrapper).remove();
}

function destroyCKEs() {
	for(inst in CKEDITOR.instances) {
	    instant = eval("CKEDITOR.instances." + inst);
	    instant.destroy();
	}
}



					function AddInternalLink(list,top,objId)
						{
							var pid = $('#CMSAdmin_Url'+objId).val();
							if(pid > 0)
							{
								$.ajax({
										type:"GET",
										url: "",
										dataType : "json",
										data: { 
												ServiceId : "CMSService",
												Action : "GetLinkUrl",
												ResponseView : "JSONServiceResultView",
												idCMSPage : pid
											},
										success : function(data) {
											var url =data.Details.url;
											var title = data.Details.title;
											CreateLinkItem(list,url,title,top,objId);
		
										}
											
								});
							} else  {
								alert("Select a node on the Site Map");
							}
						}
					function CMSDeleteLink(lid)
					{
						if(confirm("Are You Sure You Want to Delete"))
						{
							$("#"+lid).remove();
						}
					}	
					function CreateLinkItem(list,url,title,ext,objId)
					{
						//list = list+objId;
						var num = $("#"+list+ " > li ").length + 1;
						
						var html = '<li id="OBJ'+objId+'LID'+num+ext+'">Title: <input name="Title_'+num+ext+'" style="width:167px" value="'+title+'">  '+
											' Url: <input name="Url_'+num+ext+'" style="width:200px" value="'+url+'"> '+
											'	<button type="button" class="CMSButton" onclick="CMSDeleteLink(\'OBJ'+objId+'LID'+num+ext+'\')">Del</button>			';
						if(!ext)
						{
							html += 	'	<button type="button" class="CMSButton" id="OBJ'+objId+'LID'+num+ext+'_ASB" onclick="CMSAddSubNav(\'OBJ'+objId+'LID'+num+ext+'\',\''+objId+'\')">Add Sub</button>	'+
										'	<div id="OBJ'+objId+'LID'+num+ext+'_SubDiv" style="border:1px solid #CCCCCC;padding:2px;"></div>';
						}
						
						html += "</li>";
						
						$("#"+list).append(html);
					}
					
					function CMSAddSubNav(list,objId)
					{
						
						$('#'+list+"_SubDiv").html(
									'<h2>Sub Nav:</h2> ' +
									'		<ul id="CMSAdmin_LinkRow_'+list+'_Sub"></ul> '+
									'<button type="button" class="CMSButton" onclick="AddInternalLink(\'CMSAdmin_LinkRow_'+list+'_Sub\',\'_'+list+'_Sub\',\''+objId+'\')">Add Internal Link</button>'+
									'<button type="button" class="CMSButton" onclick="CreateLinkItem(\'CMSAdmin_LinkRow_'+list+'_Sub\' , \'\', \'\',\'_'+list+'_Sub\',\''+objId+'\')">Add External Link</button>' +
									'<button type="button"  class="CMSButton" onclick="DeleteSubNav(\''+list+'\')">Delete Sub Nav</button>'
									
									);
									
						$('#'+list+'_ASB').attr('disabled', true);
						$('#CMSAdmin_LinkRow_'+list+'_Sub').sortable({revert: true});
						
					}
					
					function DeleteSubNav(subdiv)
					{
						if(confirm("Are you sure you want to delete"))
						{
							$('#'+subdiv+"_SubDiv").html("");
							$('#'+subdiv+'_ASB').removeAttr('disabled');
						}
					}

					function CMS_SaveNav(objId)
					{
						if(!$('#CMSAdmin_navName'+objId).val())
						{
							alert('Please enter a name');
						} else  {
							var qstr = $('#CMSAdmin_LinkSetForm'+objId).serialize();
							$.ajax({
								type:"POST",
								url: "#",
								dataType : "json",
								data : "ServiceId=LeftNavService&Action=SetLinkSet&ResponseView=JSONServiceResultView&"+qstr,
								success : function(data) {
									$('#CMSAdmin_navListEdit'+objId).tabs('select',0);
									$('#CMSAdmin_NavSelected'+objId).val(data.Details.navId);
									$('#CMSAdmin_LinkRow'+objId).html("");
									$('#CMSAdmin_navName'+objId).val("");
								}
								
							});
						}
					}
					
				function CMSAdmin_SetLinkset(linkset,objId,pageId)
				{
					linkset = linkset+objId;
					var curset = $('#'+linkset).val();
					
					
					$.ajax({
							type: "POST",
							url: "#",
							dataType:"json",
							data : {
										ServiceId : "LeftNavService", 
										Action:"SetNavSectionPageObject",
										ResponseView: "JSONServiceResultView",
										idCMSPage : pageId,
										idObject  : objId,
										idNavSection : curset 
							},
							success: function(data)
							{
								var curtext= $('#'+linkset+' :selected').text()
								$('#'+ linkset + '_Cur').html(curtext);
								$('#CMSAdmin_NavSelected'+objId).val(curtext);
								window.location.reload();
							}
					});
				}
				
				function CMSAdmin_setLinkPreview(nid,preview)
				{
					$.ajax({
							type: "GET",
							url : "",
							dataType: "json",
							data : {
								ServiceId: "LeftNavService",
								Action : "GetNavSectionLinks",
								ResponseView: "JSONServiceResultView",
								idNavSection : nid
							},
							success: function(data)
							{
									var lid,pid,title,url;
									var subnavStr ="";
									var navStr="";
									$.each(data.Details.links, function(key,value)
									{
										lid = value.idNavLink,
										pid = value.idLinkParent,
										title = value.title,
										url = value.url			
									
										if(pid > 0) 
										{
											if(subnavStr.length < 1)
											{
												subnavStr="<ul>";
											}
											subnavStr += "<li><a href='"+url+"' target='_blank'>"+title+"</a></li>";
										} else  {
											if(subnavStr.length > 1)
											{
												navStr += subnavStr+"</ul></li>";
												subnavStr = "";
											} else  {
												navStr += "</li>";
											}
											navStr +="<li><a href='"+url+"' target='_blank'>"+title+"</a>";	
										}
									
									});
									if(navStr.length > 0)
									{
										if(subnavStr.length > 1)
										{
											navStr += subnavStr+"</ul></li>";
											subnavStr = "";
										} else  {
											navStr += "</li>";
										}
									}
									$('#'+preview).html(navStr);
									
									
							}
							
						});
				}
				
				function CMSAdminShowNav(objId)
				{
					$('#CMSAdmin_navListEdit'+objId).dialog({
							width : 1000,
							title : "List Navigation Edit"+ objId,
							close : function(){
									$('#CMSAdmin_navListEdit'+objId).dialog('destroy');
									window.location.reload(true);
								}
						
						});
				}
				
				function CMSAdmin_EditLinkset(nid,tabs,objId)
				{					
					var idx = $("#"+tabs).tabs("length");
					if(idx < 4){
						$("#"+tabs).tabs("add","#CMSAdmin_navListCreate"+objId,"Edit Navigation",idx);
						idx +=1;
					}
					$('#CMSAdmin_NavEditSelected'+objId).val(nid);
					$('#CMSAdmin_EditNavId'+objId).val(nid);
					$("#"+tabs).tabs("select",idx-1);
				}
				
					

