/*--------------------------------------------------------------------------------
WriteMaps Application Behavior Layer
Author: Scott Jehl
Updated: april 08
--------------------------------------------------------------------------------*/
//writemaps live
var baseURL = '';



//canvas height function
function setCanvas(){
		if($('#viewPort').size()>0) $('#viewPort').height($(window).height() - ($('#viewPort').get(0).scrollTop+ $('#footer').height() +150)); 	
}

//ZOOM SLIDER
function zoomSlider(){	
	$('#area').slider({
		handle: '#knob',
		startValue: 50,
		slide: function(e, ui){
			$('#sitePages').css('font-size', ui.value+50 + '%');
			scrollMap();
		}
	});
}


//Get the width of the sitemap UL and set it as an inline style so the floats don't wrap   --------------------------------------------
function hugSiteMap(){
	if($('#sitemap').size()>0){
		$('#sitemap').width(($('#sitemap li:eq(0)').width()+200)/10+'em');
	}
}

//scroll sitemap to proper position (left for outline, center for map)
function scrollMap(){
	var viewWidth = $('#viewPort').width();
	var formWidth = $('#sitePages').width();
	if(view.getState() == 'map'){
		if(formWidth>viewWidth){
			var pxFromCenter = (viewWidth - (viewWidth * (viewWidth / formWidth))+60)/2;
			$('div#viewPort').scrollLeft(pxFromCenter);
		}
	}
	else {$('div#viewPort').scrollLeft(0);}
	$('div#viewPort').scrollTop(0);
}


// Loop the li's and add first,last--------------------------------------------
function cleanMapStructure(){
	$('ul:empty').parent().find('div.section:eq(0)').removeClass('section').parent().find('ul:empty').remove();
	$('li.page').each(function(){
				//clean up the ID structure
				var thisInt = 1;
				var parentID = 'page';
				var siblingID = '';
				var thisLi = $(this);
				if(thisLi.prev().size()>0){
					siblingID = thisLi.prev().attr('id');
					thisInt = parseInt(siblingID.substring(siblingID.lastIndexOf('_') + 1), 10) + 1;
				}
				thisInt = PadDigits(thisInt, 3);
				
				//if there's an LI parent, grab its id, otherwise use 'page'
				if(thisLi.parents('li.page').size()>0) {parentID = thisLi.parents('li.page').attr('id');}
				thisID = parentID + '_' + thisInt;
				thisLi.attr('id', thisID).find('input:eq(0)').attr('name', thisID);
				thisLi.find('input:eq(1)').attr('name', thisID+'_url');
				thisLi.find('textarea:eq(0)').attr('name', thisID+'_notes');

				//attach first, last, and solo classes
				var thisDiv = thisLi.find('div:eq(0)');
				thisDiv.removeClass('first last solo').parents('ul:eq(0)').removeClass('solo');
				if(thisLi.is(':first-child')){thisDiv.addClass('first');}
				if(thisLi.is(':last-child')){thisDiv.addClass('last');}
				if(thisLi.is(':only-child')){thisDiv.addClass('solo').parents('ul:eq(0)').addClass('solo');}});
}


//validate url
String.prototype.validateUrl = function(url){
	if(this.length>0){
		var j = new RegExp("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");
		return j.test(this) ? true : false;
	}
	else {return false;}
}


//PadDigits function: accepts an integer and pads it with a variable number of leading zeroes to meet a total string length
function PadDigits(n, totalDigits) { 
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) { 
		for (i=0; i < (totalDigits-n.length); i++) { 
			pd += '0'; 
		} 
	} 
	return pd + n.toString(); 
}


function assignPageEvents(){
	//SECTION TOGGLES
	$('.toggleSection').livequery("click", function(){  
			if($(this).is('.sectionCol')){
				$(this).parents('li.page:eq(0)').find('ul:eq(0)').css('opacity', 0).show(500, function(){
					$(this).fadeTo(500, 1.0);
				});
				$(this).parents('li.page:eq(0)').find('div.connectContain:eq(0)').addClass('section');
				$(this).removeClass('sectionCol');
				$(this).html('<img src="'+imgs.bullet_toggle_minus+'" />');
				$(this).attr('title', 'Collapse This Section');
			}
			else{
				$(this).parents('li.page:eq(0)').find('ul:eq(0)').fadeTo(100, 0.0001, function(){$(this).hide(800);});
				$(this).parents('li.page:eq(0)').find('div.connectContain:eq(0)').removeClass('section');
				$(this).addClass('sectionCol');
				$(this).html('<img src="'+imgs.bullet_toggle_plus+'" />');
				$(this).attr('title', 'Expand This Section');
			}
			return false;
	});
	//KILL FORM SUBMIT
	$('form#mapForm').submit(function(){//prevent false http form submits
		return false;
	});
	//INPUT AND TEXTAREAS KILL FOCUS
	$('#sitePages input, #sitePages textarea, #sitePages input.titleText').livequery("focus", function(){
		$(this).blur();
		return false;
	});


$.fn.positionInfo = function(){
			var thisParent = $('#'+$(this).attr('parentID'));
			var parentCenter = thisParent.width() / 2;
			var parentLoc = thisParent.offset();
			$(this).css('top', (parentLoc.top - 120 + $('#viewPort').get(0).scrollTop) / 10 + 'em');
			if(view.state == 'map'){
				$(this).css('left', (parentLoc.left + parentCenter - 140 + $('#viewPort').get(0).scrollLeft) / 10 + 'em');
				
			}
			else{
				$(this).css('left', (parentLoc.left - 50) / 10 + 'em');
			}
			return $(this);
}

//INFO ICON TOGGLES
	$('a.metaToggle').livequery("click", function(){
		var thisPageMeta = $(this).next();
		var parentLiId = $(this).parents('li:eq(0)').attr('id');		
		var thisUrlVal = thisPageMeta.find('input:eq(0)').val();
		var tempPageMeta = thisPageMeta.clone(true).insertAfter('#sitemap').attr('parentID', parentLiId).addClass('tempMeta').positionInfo().fadeIn(400);
		tempPageMeta.find('input:eq(0)').val(thisUrlVal); //safari needed a double check, input val wasn't updating visually
		tempPageMeta.find('a.metaClose:eq(0)').click(function(){
			var tempPageMeta = $(this).parent();
			var tempURL = tempPageMeta.find('input:eq(0)').val();
			var tempNotes = tempPageMeta.find('textarea:eq(0)').val();
			thisPageMeta.find('input.pageUrl').val(tempURL);
			
			thisPageMeta.find('textarea:eq(0)').text(tempNotes);
			//insert click url if valid
			if(tempPageMeta.find('a.openUrl').size()>0) {
				thisPageMeta.find('a.openUrl').remove();
				thisPageMeta.find('input:eq(0)').after('<a href="javascript://" onclick="window.open(\''+tempURL+'\');" class="openUrl" title="View URL in New Window">View</a>');
			}

			if(tempURL != '' && tempURL != 'http://' && tempURL != 'http&#x3A;&#x2F;&#x2F;'){
				thisPageMeta.prev().find('img').attr('src', imgs.information);
			}
			else if( tempNotes != '' && tempNotes != 'No notes as of yet!' && tempNotes != 'No%20notes%20as%20of%20yet!'){
				thisPageMeta.prev().find('img').attr('src', imgs.information);
			}
			else {
				thisPageMeta.prev().find('img').attr('src', imgs.information_off);
			}
			//kill the clone
			tempPageMeta.fadeOut(400, function(){$(this).remove();});
			return false;
		});
		return false;
	});



	/*----------------------------------
	APPLICATION MENU BAR
	----------------------------------*/
	//MENU CLICK
	$('li.appMenu').click(function(){
		if($(this).is('.open')){$(this).removeClass('open');}
		else {
			$(this).addClass('open');
			$(this).siblings('li').removeClass('open');
		}
		return false; 
	});
	//MENU MOUSEOUT
	$('li.appMenu').mouseout(function(){
		var timer = setTimeout(function(){$('li.appMenu').removeClass('open');}, 300);
		$(this).mouseover(function(){clearTimeout(timer);});
	});
	//CLICK AWAY
	$(document).click(function(){$('li.appMenu').removeClass('open');});
	//FILE MENU
	//NEW
	$('#new a').click(function(){
		window.location = baseURL+'/sitemaps/mapBuilder/';
		
	return false; 
	});
	//OPEN
	$('#open a').click(function(){
		openMap();
		return false; 
	});
		
	//SAVE AS
	$('#saveAs a').click(function(){
		saveMapAs();
		return false; 
	});
	//print button
	$('#print a').click(function(){
		printMode.enable();
		return false; 
	});
	//XML SITEMAP EXPORT
	$('#exportXML a').click(function(){
		var xmlData = xmlMap();
		modalBox.create('<h2>XML Sitemap for SEO</h2>', '<p>Here\'s your Sitemap data in XML format as specified at sitemaps.org, this can be used to help google find the pages on your site more easily. <a href="http://www.sitemaps.org" onclick="window.open(\'http://www.sitemaps.org\'); return false;" title="Open in New Window">More info on XML Sitemaps</a></p> <textarea name="xmlData" id="xmlData">'+xmlData+'</textarea>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');

		return false; 
	});
	//LOCAL BACKUP EXPORT
	$('#exportJSON a').click(function(){
		var jsonData = mapData(true);
		var tempArray = [];
		var interval = 56;
		for(var i =0; i<jsonData.length; i+=interval){
			tempArray.push(jsonData.substring(i, i+interval));
		}
		jsonData = tempArray.join('</span><span class="jsonLine">');

		modalBox.create('<h2>Export Local Backup (JSON)</h2>', '<p>To save a local backup of this sitemap, copy the source code below and save it in a text file.</p> <pre><code><span class="jsonLine">'+jsonData+'</span></code></pre>',  '<a href="javascript://" id="mbCancel" title="Close">Close</a>');

		return false; 
	});
	//LOCAL BACKUP IMPORT
	$('#importJSON a').click(function(){
		modalBox.create('<h2>Import Local Backup (JSON)</h2>', '<p>To restore to a local backup, paste the sitemap source code into the field below. <strong>Reminder:</strong> Only valid WriteMaps JSON schema will be accepted.</p><form action="#"><fieldset><label for="map_source">SiteMap Source: </label><input type="text" id="map_source" name="map_source" /></fieldset></form>', '<a href="javascript://" id="mbCancel">Cancel</a><a href="javascript://" id="mbSave">Import</a>' );
		$('#mbSave').click(function(){
			var jsonData = $('#mbContent form input#map_source').val();
			if(jsonData != ''){
				appHistory.addToUndo('Import Backup');
				jsonData = JSON.parse(jsonData);
				buildMap(jsonData);
			    saveStatus.unsave();
			}
			else {
				$('#mbContent form input#map_source').val('Paste source code here').focus(function(){$(this).val('');});
			}
			return false;
		});
		return false;
	});	
	//SHARING PREFERENCES
	$('#share a').click(function(){
		modalBox.create('<h2>Sharing Preferences</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		if(getMapID()){
			$.ajax({
			   type: "GET",
			   url: baseURL+"/mapfunctions/sharing_preferences?map_id="+getMapID(),
			   success: function(msg){sharingData(msg);}
			 });			 
		}
		else if(getShareID()) {
			$('#mbContent').html('<p>Sharing preferences can not be changed from within a shared sitemap.</p>');
		}
		else{
			$('#mbContent').html('<p>You must save this sitemap before you can share it.</p>');
		}
		return false;
	});
		
	//close button
	$('#close, #close a').click(function(){
		return true;
	});
	//OVERLAY CLOSE/CANCEL
	$('#mbCancel, #mbClose').livequery("click", function(){
			modalBox.kill();
			return false;
	});
	//HELP
	//WHATS NEW IN WMS
	$('#whatsNew a').click(function(){
		modalBox.create('<h2>What\'s New in WriteMaps</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		$.ajax({
		   type: "GET",
		   url: "http://writemaps.com/mapfunctions/help_whatsNew/",
		   success: function(msg){$('#mbContent').html(msg);}
		 });
		 return false;
	});
	//USING WMS
	$('#usingWriteMaps a').click(function(){
		modalBox.create('<h2>Using WriteMaps</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		$.ajax({
		   type: "GET",
		   url: "http://writemaps.com/mapfunctions/help_usingWriteMaps/",
		   success: function(msg){$('#mbContent').html(msg).pngFix();;}
		 });
		 return false;
	});

	
	/*----------------------------------
	BUTTON BAR
	----------------------------------*/
	//TOGGLE MAP VIEW
	$('#mapView').click(function(){
		view.map();
		return false;
	});	
	//TOGGLE OUTLINE VIEW
	$('#outlineView').click(function(){
		view.outline();
		return false;
	});
}
	

//VIEW STATE TRACKING
var view = {
	state: 'map',
	map: function(){
		$('#viewPort, #viewToggles ul').addClass('map').removeClass('outline');
		$.cookie('view', 'map');
		this.state = 'map';
		hugSiteMap();
		scrollMap();
		if($('div.tempMeta').size()>0){$('div.tempMeta').positionInfo();}},
	outline: function(){
		$('#viewPort, #viewToggles ul').addClass('outline').removeClass('map');
		$.cookie('view', 'outline');
		this.state = 'outline';
		hugSiteMap();
		scrollMap();
		if($('div.tempMeta').size()>0){$('div.tempMeta').positionInfo();}},
	toggle: function(){
		if(this.state == 'map') {this.outline();}
		else {this.map();}},
	loadView: function(){
		//check cookie for map vs outline
		var viewName = $.cookie('view');
		if(viewName){
			if (viewName == 'outline') {view.outline();}
			else {view.map();}}
		else {view.map();}},
	getState: function(){
		return this.state;
	}
};

	






var printMode = {
	 savedMode: '',
     enable: function(){
     		
        var screenPrint = $('link[title=screenPrint]').get(0);
	     screenPrint.disabled = true;
	     screenPrint.disabled = false;
	     if($.browser.msie && $.browser.version < 7){$('#sitemap img.pageIcon').attr('src', imgs.page_iePrint);}
         $('#sitemap').draggable({handle: $('#printCrop'), cursor: 'move' });
         $('#viewPort').css('overflow', 'hidden');
     },
     disable: function(){
	     var screenPrint = $('link[title=screenPrint]').get(0);
	     screenPrint.disabled = true;
	     if($.browser.msie && $.browser.version < 7){$('#sitemap img.pageIcon').attr('src', imgs.page);}
        $('#sitemap').draggable('destroy').css({'position': 'relative', 'left': 'auto', 'top': 'auto'});
        $('#viewPort').css('overflow', 'auto');
        hugSiteMap();
        scrollMap();
        	
     }
  }  

function whControls(){
	$('#printControls #pageWidth').keyup(function(){
		var w = parseInt($(this).val());
		$('#printCrop').width(w+'in');
	});
	$('#printControls #pageHeight').keyup(function(){
		var h = parseInt($(this).val());
		$('#printCrop').height(h+'in');
	});
	$('#printPrintView').click(function(){
		window.print();
		return false;
	});
	$('#closePrintView').click(function(){
		printMode.disable();
		return false;
	});
}









//ADD PAGE FUNCTION
function addPage(insertLoc, ID, pageName, pageUrl, pageNotes, addType){
	// Setup Parent Node --------------------------------------------
	//assign the insertLoc var to an element with that id
	if(insertLoc) {
		if($('#'+insertLoc).size() <1){//if no parent node
				var tempID = insertLoc.lastIndexOf('_');
				var thisParentID =  insertLoc.substring(0, tempID);
				var addType = "user";
				addPage(thisParentID,null,'Recovered Page',null,null,addType);
				saveStatus.srcStatus = 'unstable';
		}
		insertLoc = $('#'+insertLoc);
	}
	else {insertLoc = $('#page_001');}
	// if the parent is not the fieldset, make parent into a section
	if(insertLoc.is('#sitePages')){}
	else {insertLoc.find('div.connectContain:eq(0)').addClass('section');}
	// Assign Page ID --------------------------------------------
	//assign thisID var either through parent or from passed var
		var thisID = '';
		if(!ID){
			var thisInt = 1;
			var siblingID = '';
			var parentID = '';
			if(insertLoc.find('ul').size() != 0){
				siblingID = insertLoc.find('ul:eq(0) li:last').attr('id');
				thisInt = parseInt(siblingID.substring(siblingID.lastIndexOf('_') + 1), 10) + 1;
			}
			thisInt = PadDigits(thisInt, 3);
			if(insertLoc.attr('id') == 'sitePages'){ parentID = 'page';}
			else {parentID = insertLoc.attr('id');}
			thisID = parentID + '_' + thisInt;
		}
		else{thisID = ID;}
		// Assign Page Name Var --------------------------------------------
		var pageNameINDefault = '';
		var pageClass = 'titleText';
		var addButtonMessage = '';

		if(!pageName || pageName == '' || pageName == null){	
			pageName = pageNameINDefault;
			pageClass = 'titleText defaultText';
			addButtonMessage = 'Add a Page Inside This Section';
			if(addType != 'user') {
				pageName = 'New Page';
			}
		}
		else{addButtonMessage = 'Add a Page To The ' + pageName + ' Section';}
		//if there's no UL parent for the new page, make one
		if(insertLoc.find('ul').size() == 0){
			var ulAttrs = '';
			if($('#sitemap').size() < 1){ ulAttrs = ' id="sitemap" ';}
			insertLoc.append('<ul'+ulAttrs+' class="solo"></ul>');
		}
		else{insertLoc.find('ul:eq(0)').removeClass('solo');}
		//create the New Page Li
		var liID = ' id="'+thisID+'"';

		//status of url/notes:
		var metaStatus = false;
		//url
		var thisURL = 'http://';
		var urlLink = '';
		if(pageUrl && pageUrl != '{page_url}' && pageUrl != thisURL && pageUrl != 'http&#x3A;&#x2F;&#x2F;') {
			thisURL = pageUrl;
			metaStatus = true;
			if(thisURL.validateUrl()) urlLink = '<a href="javascript://" onclick="window.open(\''+thisURL+'\');" class="openUrl" title="View URL in New Window">View</a>';
		}

		//notes
		var thisNotes = 'No notes as of yet!';
		if(pageNotes && pageNotes!= '{page_notes}' && pageNotes != thisNotes && pageNotes != 'No%20notes%20as%20of%20yet!'){ 
			thisNotes = pageNotes;
			metaStatus = true;
		}

		var infoIcon = metaStatus ? imgs.information : imgs.information_off;
		//class
		var liClass = 'class="page"';
		if(insertLoc.find('ul:eq(0)').is('#sitemap')){ liClass = ' class="root page"';}
		var safariWipe = $.browser.safari ? '<div class="safariWipe"></div>' : '';

		

		
				//INSERT NON-EDITABLE PAGE
			insertLoc.find('ul:eq(0)').append('<li'+liID+liClass+'>'+
				'<div class="connectContain">'+
					'<div class="vLine"><div class="line"></div></div>'+
					'<div class="pageContain">'+
						'<img src="'+imgs.page+'" />'+
						'<a href="javascript://" class="toggleSection" title="Collapse Section"><img src="'+imgs.bullet_toggle_minus+'" /></a>'+
						'<h3><input type="text" name="'+thisID+'" title="Page Title" class="'+pageClass+'" value="'+pageName+'" maxlength="250" />'+safariWipe+'</h3>'+
						'<a href="javascript://" class="metaToggle" title="Page Info"><img src="'+infoIcon+'" /></a>'+
						'<div class="page_meta">'+
							'<h4>Page Info: '+pageName+'</h4>'+
							'<label for="'+thisID+'_url">Page URL</label>'+
							'<input type="text" name="'+thisID+'_url" id="'+thisID+'_url" value="'+thisURL+'" class="pageUrl" title="Page URL" maxlength="250" />'+urlLink+
							'<label for="'+thisID+'_notes">Page Notes</label>'+
							'<textarea name="'+thisID+'_notes" id="'+thisID+'_notes" class="pageNotes" title="Page Notes" maxlength="250">'+thisNotes+'</textarea>'+
							'<a href="javascript://" class="metaClose">Done</a>'+
						'</div>'+
					'</div>'+
				'</div>'+
			'</li>');
			
		cleanMapStructure();
		hugSiteMap();
				
}



//MAP DATA
// Package Map data to JS object (json boolean returns JSON string, otherwise, returns JS object) --------------------------------------------
function mapData(json, noEncode){
	cleanMapStructure();
    var mapData = {};
	mapData.pages = [];
	$('#sitePages li').each(function(i){
		mapData.pages[i] = {};
		mapData.pages[i].id = $(this).attr('id');
		//page name
		if($(this).find('input.titleText:eq(0)').is('.defaultText')){ mapData.pages[i].name = '';}
   	else {
   		if(!noEncode){ mapData.pages[i].name = encodeURIComponent($(this).find('input:eq(0)').val()); }
   		else {mapData.pages[i].name = $(this).find('input:eq(0)').val(); }
   	}
   	//page url
   	if(!noEncode) {mapData.pages[i].url = encodeURIComponent($(this).find('input.pageUrl:eq(0)').val()); }
   	else {mapData.pages[i].url = $(this).find('input.pageUrl:eq(0)').val(); }
   	//page notes
   	if(!noEncode) {mapData.pages[i].notes = encodeURIComponent($(this).find('textarea.pageNotes:eq(0)').val()); }
   	else {mapData.pages[i].notes = $(this).find('textarea.pageNotes:eq(0)').val(); }
	});
	if(json) {mapData = $.toJSON(mapData);}
	return mapData;
}

//CONVERT TO HTML ENTITIES
String.prototype.htmlEntities = function(){
  var chars = ['&',' ','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<','>','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','­','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾'];
  var entities = ['amp','agrave','aacute','acirc','atilde','auml','aring','aelig','ccedil','egrave','eacute','ecirc','euml','igrave','iacute','icirc','iuml','eth','ntilde','ograve','oacute','ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc','uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc','Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute','Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde','Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave','Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig','lt','gt','cent','pound','curren','yen','brvbar','sect','uml','copy','ordf','laquo','not','shy','reg','macr','deg','plusmn','sup2','sup3','acute','micro','para','middot','cedil','sup1','ordm','raquo','frac14','frac12','frac34'];
  newString = this;
  for (var i = 0; i < chars.length; i++){
    myRegExp = new RegExp();
    myRegExp.compile(chars[i],'g');
    newString = newString.replace (myRegExp, '&' + entities[i] + ';');
  }
  return newString;
};

//RETURN XML SITEMAP
function xmlMap(){
	var xmlDocument = '';
	var doctype = '<?xml version="1.0" encoding="UTF-8"?>';
	//doctype = doctype.htmlEntities();
	xmlDocument+=doctype+"\n";

	var urlSet = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
	//urlSet = urlSet.htmlEntities();
	xmlDocument+=urlSet+"\n";
	var urlSetClose = '</urlset>'+"\n";
	//urlSetClose = urlSetClose.htmlEntities();
	var urls = [];
$('#sitePages li').each(function(i){
		var thisUrl = $(this).find('input.pageUrl:eq(0)').val(); 
		var thisPriority = 1.0-($(this).parents('li').size() / $('#sitePages ul').size());
		var thisUrlNode = '<url><loc>'+thisUrl+'</loc><priority>'+thisPriority+'</priority><lastmod>2007-10-05</lastmod><changefreq>hourly</changefreq></url>';
		//thisUrlNode = thisUrlNode.htmlEntities();
		urls.push(thisUrlNode);
	});
	
	xmlDocument+=urls.join('\n')+'\n\n';
	xmlDocument+=urlSetClose;
	return xmlDocument;
}



/* TRIAL FEATURES: This functionality is in bookmarklet stage and is not yet implemented in the application*/
function exportHTML(){
		if(!$.browser.msie){
		var copyMap = $('#sitePages').clone();
		copyMap.find('input.titleText').each(function(){
		var thisTitle = $(this).val();
		var parentLi = $(this).parents('li:eq(0)');
		var pageUrl = parentLi.find('input.pageUrl:eq(0)').val();
		thisTitle = '<a href="'+ pageUrl +'">'+thisTitle+'</a>';
		
		$(this).parents('li:eq(0)').prepend(thisTitle);
		});
		copyMap.find('div, a.addPage, img, h3, h4, label, textarea').remove();
		copyMap.find('ul, li').each(function(){
			var indent = '';
			var depth = $(this).parents('ul, li').each(function(){
				indent = indent + '\t';
			});
			$(this).removeAttr('class').removeAttr('id').removeAttr('style').before("\n"+indent).append("\n"+indent);
		});
		modalBox.create('<h2>Trial Feature: XHTML Sitemap</h2>', '<p>Here\'s your Sitemap data in XHTML format. This can be used to make a clickable site directory on your website. <strong>Note:</strong> Please let us know if you would like this integrated into the application!</p> <textarea name="xmlData" id="xmlData">'+	copyMap.html() +'</textarea>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');
	}
	else {
		modalBox.create('<h2>Trial Feature: XHTML Sitemap</h2>', '<p>Sorry, due to technical constraints, this trial feature is not available in Internet Explorer. However, if you are interested in having this feature implemented in WriteMaps, please let us know!</p>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');
	}
}


//BUILD MAP FROM JS OBJECT
function buildMap(mapData){
	if(!mapData){ return false;}
	//no pages means new map
	if(mapData.pages.length == 0){
		//cleanup any map that's there
		$('#sitemap').remove();
		addPage('sitePages',null,null,null,null, null);
	}
	else{
		var mapschema = 'valid';
		//check json for valid schema
		
		$(mapData.pages).each(function(){
			if(typeof this.id == "undefined" || typeof this.name == "undefined" || typeof this.url == "undefined" || typeof this.id == "undefined"){
				mapschema = 'invalid';
			}
		});
		
		//schema is good if we got this far		
		//cleanup any map that's there
		if(mapschema == 'valid'){
			$('#sitemap').remove();
			modalBox.kill();
			if($('#initLoader').size()<1){$('#sitePages').after('<p id="initLoader">Loading...</p>');}
			$(mapData.pages).each(function(){
				var thisPageID = this.id;
				var thisPageName = decodeURIComponent(this.name);
				var thisPageUrl = decodeURIComponent(this.url);
				var thisPageNotes = decodeURIComponent(this.notes);
				var tempID = thisPageID.lastIndexOf('_');
				var thisParentID =  thisPageID.substring(0, tempID);
				if(thisParentID == "page") {thisParentID = 'sitePages';}
				setTimeout(function(){addPage(thisParentID, thisPageID, thisPageName, thisPageUrl, thisPageNotes);}, 10);
			});
		}
		else{
				modalBox.create('<h2>Error: Malformed Source Data</h2>', '<p>The sitemap source you have attempted to import has a malformed schema.</p>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');
		}
	}
	//Done loading, fade the map in and alert the user if there was a recovery
	if (!$.browser.safari && $('#initLoader').size()>0) {$('#sitemap').hide();}
		$('#mapbuilder').css('cursor', 'default');  
		cleanMapStructure();
		$('#initLoader').fadeOut('normal', function(){
			$(this).remove();
			
			if (!$.browser.safari) {$('#sitemap').fadeIn(1500);}
			scrollMap();
			hugSiteMap();
		
			
	});
}





		



//GET MAP ID
function getMapID(){
   return $('#map_id').val(); 
}
//GET SHARED ID
function getShareID(){
   return $('#share_id').val(); 
}

//LOAD A SITEMAP BY EITHER MAP/SHARED ID OR NEW
function loadMap(){
		$('#sitemap').remove();
		if($('#initLoader').size()==0) {$('fieldset').prepend('<p id="initLoader">Loading...</p>');}
		var postParams = {};
	  if(getMapID()) {postParams = { map_id: getMapID()};}
	  else if(getShareID()) {postParams = {share_id: getShareID()};}
	  else {postParams = false;}
	  //Send to loadMap script	  
  	$.getJSON("http://writemaps.com/mapfunctions/loadMap/", postParams, function(json){buildMap(json);});
}


//OVERLAY BEHAVIOR
var modalBox = {
	create: function (header, content, footer){
			$('li.appMenu').removeClass('open');
			$('#overlayScreen').remove();
			$('#mapNames').css('overflow', 'hidden');
			$('body').append('<div id="overlayScreen" style="display: none;"><div id="modalBox"><div id="mbHeader">'+header+'<a href="javascript://" id="mbClose" title="Close">Close</a></div><div id="mbContain"><div id="mbContent">'+content+'</div><div id="mbFooter">'+footer+'</div></div></div></div>');
			$('#overlayScreen').width($('body').width()).height($('body').height());
			$('#overlayScreen').fadeIn(500);
	},
	kill: function(){
			$('#overlayScreen').fadeOut(500, function(){
				$(this).remove();
				$('#mapNames').css('overflow', 'auto');
			});
			
	}
};



//OPEN MAP
function openMap(){
		modalBox.create('<h2>Open a Saved Map</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		 $.ajax({
		   type: "GET",
		   url: "http://writemaps.com/mapfunctions/openMenu/",
		   success: function(msg){$('#mbContent').html(msg);}
		 });
}

	
//SAVE MAP AS
function saveMapAs(userAction){
		modalBox.create('<h2>Save Map As...</h2>', '<form action="#"><fieldset><label for="map_name">New SiteMap Name:</label><input type="text" id="map_name" name="map_name" /></fieldset></form>', '<a href="javascript://" id="mbCancel">Cancel</a><a href="javascript://" id="mbSave">Save</a>' );

		cleanMapStructure();
		$('#mbSave').click(function(){
			$('#mbContent form').trigger("submit");
			return false;
		});
		var postString = '';
		$('#mbContent form').submit(function(){
			$('#mbContent').html('<p>Saving...</p>');
			$('#sitemap input.defaultText').val('');
			var mapData = {};
			mapData['map_name'] = encodeURIComponent($(this).find('input[@type=text]:eq(0)').val());
			$('#sitemap input.defaultText').val('New Page');
			
			if(mapData['map_name'] != ''){
				$('#sitePages li').each(function(i){

					var thisID = $(this).attr('id');
					var thisPageName = $(this).find('input[@type=text]:eq(0)');
					var thisPageUrl = $(this).find('input[@type=text]:eq(1)');
					var thisPageNotes = $(this).find('textarea:eq(0)');
		
					mapData[thisPageName.attr('name')]= encodeURIComponent(thisPageName.val());
					mapData[thisID+'_url']= encodeURIComponent(thisPageUrl.val());
					mapData[thisID+'_notes']= encodeURIComponent(thisPageNotes.val());
				});
			}
			else {
				$(this).find('input[@type=text]:eq(0)').val('Give your sitemap a name!');
				return false;
			}
			
			$.ajax({
			   type: "POST",
			   url: "http://writemaps.com/mapfunctions/saveMap/",
			   data: mapData,
			   success: function(msg){
				   	if(msg*1 == msg){
					   		
				   		if(userAction == 'new') {window.location = baseURL+'/sitemaps/mapBuilder/';}
				   		else {window.location = baseURL+'/sitemaps/mapBuilder/'+msg;}
				   	}
				   	else {$('#mbContent').html('<p>'+msg+'</p>');}}
			 });
			return false;
		});
}


	


	






//IMAGES PRELOADING AND REFERENCING
var imgs = (function(){
	var ext =  ($.browser.msie && $.browser.version < 7) ? 'gif' : 'png'; //extension switch for IE
	var imgsArr = {
		close: '/images/site/close.'+ext,
		modalBoxHeader: '/images/site/bg_modalBox_header.'+ext,
		modalBoxBot: '/images/site/bg_modalBox_bot.'+ext,
		loaderAnim: '/images/site/loaderAnim.gif',
		bullet_toggle_minus: '/images/site/bullet_toggle_minus.'+ext,
		bullet_toggle_plus: '/images/site/bullet_toggle_plus.'+ext,
		page: '/images/site/page.'+ext,
		page_iePrint: '/images/site/page_iePrint.gif',
		cancel: '/images/site/cancel.'+ext,
		information: '/images/site/information.'+ext,
		information_off: '/images/site/information_off.'+ext,
		add: '/images/site/add.'+ext,
		newWin: '/images/site/newWin.gif',
		dropZone: '/images/site/dropZone.gif'
	};
	return imgsArr;
})();

//PRELOAD IMAGES FUNCTION
(function(){
		var loadedImgs = [];
		var i = 0;
		for (property in imgs){
			loadedImgs[i] = new Image();
			loadedImgs[i].src = imgs[property];	
			i++;
		}
})();


	


/*-------------------------------------------------------------------------
DOM READY EVENTS
-------------------------------------------------------------------------*/
$(function(){
		$('#logo').pngFix();
		$('#alertUser').remove();
		view.loadView();
					
		zoomSlider();
		setCanvas();
		assignPageEvents();
		$(window).resize(function () {setCanvas();});
		loadMap();
		whControls();
});









