text:
/*

	HTML Builder front-end version 1.5

*/

/* SETTINGS */

var pageContainer = "#page";
var enablePreview = true; //set to off to disable previews

var editableItems = new Array();

editableItems['.frameCover'] = [];
editableItems['span.fa'] = ['color', 'font-size'];
editableItems['.bg.bg1'] = ['background-color'];
editableItems['nav a, a.edit'] = ['color', 'font-weight', 'text-transform'];
editableItems['h1'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['h2'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['h3'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['h4'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['h5'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['h6'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['.pix_text, .pix_edit'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['p'] = ['color', 'font-size', 'background-color', 'font-family'];
editableItems['a.btn, button.btn'] = ['border-radius', 'font-size', 'background-color'];
editableItems['img'] = ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-left-radius', 'border-bottom-right-radius', 'border-color', 'border-style', 'border-width', 'width', 'height'];
editableItems['hr.dashed'] = ['border-color', 'border-width'];
editableItems['.divider > span'] = ['color', 'font-size'];
editableItems['hr.shadowDown'] = ['margin-top', 'margin-bottom'];
editableItems['.footer a'] = ['color'];
editableItems['.bg.bg1, .bg.bg2, .header10, .header11'] = ['background-image', 'background-color'];
//editableItems['.pix_builder_bg, .confirm_page_2'] = ['background-image', 'background-color', 'height', 'padding-top', 'padding-bottom'];
editableItems['.pix_builder_bg, .confirm_page_2'] = ['background-image', 'background-color', 'padding-top', 'padding-bottom'];
editableItems['#nivoSlider img.edit'] = [];

var editableItemOptions = new Array();

editableItemOptions['nav a : font-weight'] = ['400', '700'];
editableItemOptions['a.btn : border-radius'] = ['0px', '4px', '10px'];
editableItemOptions['img : border-style'] = ['none', 'dotted', 'dashed', 'solid'];
editableItemOptions['img : border-width'] = ['1px', '2px', '3px', '4px'];
editableItemOptions['h1 : font-family'] = ['default', 'Lato', 'Helvetica', 'Arial', 'Times New Roman'];
editableItemOptions['h2 : font-family'] = ['default', 'Lato', 'Helvetica', 'Arial', 'Times New Roman'];
editableItemOptions['h3 : font-family'] = ['default', 'Lato', 'Helvetica', 'Arial', 'Times New Roman'];
editableItemOptions['p : font-family'] = ['default', 'Lato', 'Helvetica', 'Arial', 'Times New Roman'];

var editableContent = ['.editContent', '.pix_edit', '.navbar a', 'button', 'a.btn', '.footer a:not(.fa)', '.tableWrapper'];

/* FLAT UI PRO INITS */

$(function(){

	// Tabs
	$(".nav-tabs a").on('click', function (e) {
	  e.preventDefault();
	  $(this).tab("show");
	})

})

/* END SETTINGS */

var mainMenuWidth = 230;
var secondMenuWidth = 300;

//local storage check
if(typeof(Storage) !== "undefined") {

	localStorage = true;

} else {

	localStorage = false;

}

$( window ).load(function() {

	$('#loader').fadeOut(function(){

		$('#menu').animate({'left': '-190px'}, 1000);

	});

	//activate previews?
	if( enablePreview == true ) {

		$('#preview').show();

	}

	//do we have saved pages?

	if( localStorage.getItem("blocksElement1") !== null ) {

		$('#start').hide()

	}

	var framesForLater = [];

	for(x=0; x<=99; x++) {

		if( localStorage.getItem("blocksElement"+x) !== null && localStorage.getItem("blocksFrame"+x) !== null ) {

			//alert('')
			//localStorage.removeItem("page"+x);

			var blocksElement = JSON.parse(localStorage["blocksElement"+x]);
			var blocksFrame = JSON.parse(localStorage["blocksFrame"+x]);
			var pageNames = JSON.parse(localStorage["pageNames"]);

			//does the parent UL exist?

			if( $('ul#page'+x).size() == 0 ) {

				newUL = $('

');

				$('#pageList').append(newUL);

		    	makeSortable( newUL );

			}

			for(var y=0; y<=blocksElement.length; y++) {

				if( blocksElement[y] != null ) {

					//build 'em

					toInsert = $("
"+blocksElement[y]+"
");

					//Pix fix
					theHeight = toInsert.find('.frameCover').height();
					toInsert = $("
"+blocksElement[y]+"
");

					toInsert.find('iframe').attr('id', 'ui-id-'+x+y);
					toInsert.find('.frameCover').show();

					//sandbox? if so, create the sanboxed frame
					var attr = toInsert.find('iframe').attr('data-sandbox');

					if (typeof attr !== typeof undefined && attr !== false) {

						theiFrame = toInsert.find('iframe');

						theID = theiFrame.attr('data-sandbox');

						sandboxedFrame = $('');

						$('#sandboxes').append( sandboxedFrame );

					}

					framesForLater[toInsert.find('iframe').attr('id')] = blocksFrame[y];

					toInsert.find('iframe').load(function(){

						$(this).contents().find(pageContainer).html( framesForLater[$(this).attr('id')] );

						//sandbox

						var attr = $(this).attr('data-sandbox');

						if (typeof attr !== typeof undefined && attr !== false) {

							$('iframe#'+$(this).attr('data-sandbox')).contents().find(pageContainer).html( framesForLater[$(this).attr('id')] );

							theLoaderFunction = $(this).data('data-loaderfunction');

							theiFrame = $(this);

							var codeToExecute = "theiFrame[0].contentWindow."+theiFrame.attr('data-loaderfunction')+"()";
							var tmpFunc = new Function(codeToExecute);
							tmpFunc();

						}

					})

					$('ul#page'+x).append( toInsert );

					//page links

				}

			}

			if( x >= 1 && pageNames[x] != undefined) {

				newLI = $('
'+pageNames[x]+'
');

				$('ul#pages').append( newLI );

			}

			//localStorage.removeItem("blocksElement"+x);
			//localStorage.removeItem("blocksFrame"+x);

		}
	}

	allEmpty();

});

var hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
	rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 	return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  	return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}

function getRandomArbitrary(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

var pendingChanges = false;

function setPendingChanges(v) {

	if( v == true ) {

		$('#savePage .bLabel').text("Save changes (!)");

		pendingChanges = true;

	} else {

		$('#savePage .bLabel').text("Nothing new to save");

		pendingChanges = false;

	}

}

function pageEmpty() {

	if( $('#pageList ul:visible > li').size() == 0 ) {

		$('#start').show();

		$('#frameWrapper').addClass('empty');

	} else {

		$('#start').hide();

		$('#frameWrapper').removeClass('empty');

	}

}

function allEmpty() {

	var allEmpty = false;

	if( $('#pageList li').size() == 0 ) {

		allEmpty = true;

	} else {

		allEmpty = false;

	}

	if( allEmpty ) {

		$('a.actionButtons').each(function(){

			$(this).addClass('disabled');

		});

		$('header .modes input').each(function(){

			$(this).prop('disabled', true).parent().addClass('disabled');

		});

	} else {

		$('header .modes input').each(function(){

			$(this).prop('disabled', false).parent().removeClass('disabled');

		});

		$('a.actionButtons').each(function(){

			$(this).removeClass('disabled');

		});

	}

}

function makeDraggable(theID) {

	$('#second #elements li').each(function(){

		$(this).draggable({
			helper: function() {
				return $('

');
			},
			revert: 'invalid',
			appendTo: 'body',
			connectToSortable: theID,
			stop: function(){

				pageEmpty();

				allEmpty();

			},
			start: function(){

				//switch to block mode
				$('input:radio[name=mode]').parent().addClass('disabled');
				$('input:radio[name=mode]#modeBlock').radio('check');

				//show all iframe covers and activate designMode

				$('#pageList ul .zoomer-wrapper .zoomer-cover').each(function(){

					$(this).show();

				})

				//deactivate designmode

				$('#pageList ul li iframe').each(function(){

					this.contentDocument.designMode = "off";

				})

			}
		});

	})

	$('#elements li a').each(function(){

		$(this).unbind('click').bind('click', function(e){

			e.preventDefault();

		})

	})

}

var frameContents = '';//holds frame contents

function makeSortable(el) {

	el.sortable({
		revert: true,
		placeholder: "drop-hover",
		handle: ".frameCover",
		beforeStop: function(event, ui){

			if( ui.item.find('.frameCover').size() == 0 ) {

				if( ui.item.find('iframe').size() > 0 ) {//iframe thumbnails

					theHeight = ui.item.height();

					var attr = ui.item.find('iframe').attr('data-sandbox');

					if (typeof attr !== typeof undefined && attr !== false) {

						//sandboxed

						theID = getRandomArbitrary(10000, 1000000000);

						sandboxedFrame = $('');

						$('#sandboxes').append( sandboxedFrame );

						if (typeof ui.item.find('iframe').attr('data-loaderfunction') !== typeof undefined && ui.item.find('iframe').attr('data-loaderfunction') !== false) {
							loaderFunction_ = 'data-loaderfunction="'+ui.item.find('iframe').attr('data-loaderfunction')+'"';
						}

						ui.item.html('');

					} else {

						ui.item.html('');

					}

					ui.item.find('iframe').uniqueId();
					ui.item.find('iframe').height(theHeight+"px");

				} else {//image thumbnails

					theHeight = ui.item.find('img').attr('data-height');

					//is this iframe to be sandboxed?

					var attr = ui.item.find('img').attr('data-sandbox');

					if (typeof attr !== typeof undefined && attr !== false) {

						//sandboxed

						theID = getRandomArbitrary(10000, 1000000000);

						sandboxedFrame = $('');

						$('#sandboxes').append( sandboxedFrame );

						if (typeof ui.item.find('img').attr('data-loaderfunction') !== typeof undefined && ui.item.find('img').attr('data-loaderfunction') !== false) {
							loaderFunction_ = 'data-loaderfunction="'+ui.item.find('img').attr('data-loaderfunction')+'"';
						}

						ui.item.html('');

					} else {

						ui.item.html('');

					}

					ui.item.find('iframe').uniqueId();
					ui.item.find('iframe').height(theHeight+"px");
					ui.item.find('iframe').css('background', '#ffffff url(images/pixbuilder-gif.gif) 50% 50% no-repeat');

					ui.item.find('iframe').load(function(){

						heightAdjustment( ui.item.find('iframe').attr('id'), true );

					})

				}

				//add a delete button
				delButton = $('<button type="button" class="btn btn-danger deleteBlock"> remove</button>');
				resetButton = $('<button type="button" class="btn btn-warning resetBlock"> reset</button>');
				htmlButton = $('<button type="button" class="btn btn-inverse htmlBlock"> source</button>');

				frameCover = $('

');

				frameCover.append( delButton );
				frameCover.append( resetButton );
				frameCover.append( htmlButton );

				ui.item.append( frameCover );

			} else {

				//sorted

				ui.item.find('iframe').load(function(){

					$(this).contents().find( pageContainer ).html( frameContents )

				})

			}

			setPendingChanges(true)

		},
		stop: function(){

			$('#pageList ul:visible li').each(function(){

				$(this).find('.zoomer-cover > a').remove();

			});

		},
		start: function(event, ui){

			if( ui.item.find('.frameCover').size() != 0 ) {

				frameContents = ui.item.find('iframe').contents().find( pageContainer ).html();

			}

		},
		over: function(){

			$('#start').hide();

		}
	});

}

function buildeStyleElements(el, theSelector) {

	for( x=0; x<editableItems[theSelector].length; x++ ) {

		//create style elements

		//alert( $(el).get(0).tagName )

		newStyleEl = $('#styleElTemplate').clone();

		newStyleEl.attr('id', '');
		newStyleEl.find('.control-label').text( editableItems[theSelector][x]+":" );

		if( theSelector+" : "+editableItems[theSelector][x] in editableItemOptions) {//we've got a dropdown instead of open text input

			//alert( theSelector+" "+editableItems[kkey][x] )

			newStyleEl.find('input').remove();

			newDropDown = $('<select></select>');
			newDropDown.attr('name', editableItems[theSelector][x]);

			for( z=0; z<editableItemOptions[ theSelector+" : "+editableItems[theSelector][x] ].length; z++ ) {

				newOption = $('<option value="'+editableItemOptions[theSelector+" : "+editableItems[theSelector][x]][z]+'">'+editableItemOptions[theSelector+" : "+editableItems[theSelector][x]][z]+'</option>');

				if( editableItemOptions[theSelector+" : "+editableItems[theSelector][x]][z] == $(el).css( editableItems[theSelector][x] ) ) {

					//current value, marked as selected
					newOption.attr('selected', 'true')

				}

				newDropDown.append( newOption )

			}

			newStyleEl.append( newDropDown );

			newDropDown.selectpicker({style: 'btn-sm btn-default', menuStyle: 'dropdown-inverse'});

		} else {

			newStyleEl.find('input').val( $(el).css( editableItems[theSelector][x] ) ).attr('name', editableItems[theSelector][x])

			if( editableItems[theSelector][x].indexOf("color") > -1 ) {

				//alert( editableItems[theSelector][x]+" : "+$(el).css( editableItems[theSelector][x] ) )

				if( $(el).css( editableItems[theSelector][x] ) != 'transparent' && $(el).css( editableItems[theSelector][x] ) != 'none' && $(el).css( editableItems[theSelector][x] ) != '' ) {

					newStyleEl.val( $(el).css( editableItems[theSelector][x] ) )

				}

				newStyleEl.find('input').spectrum({
					preferredFormat: "hex",
					showPalette: true,
					allowEmpty: true,
					showInput: true,
					palette: [
						["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
						["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
						["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
						["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
						["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
						["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
						["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
						["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
					]
				});

			}

		}

		newStyleEl.css('display', 'block');

		$('#styleElements').append( newStyleEl );

		$('#styleEditor form#stylingForm').height('auto')

	}

}

function getParentFrameID(el) {

	theID = '';

	$('#pageList li:visible iframe').each(function(){

		theBody = $(this).contents().find('body');

		if( $.contains( document.getElementById( $(this).attr('id') ).contentWindow.document, el ) ) {

			theID = $(this).attr('id');

		}

	})

	if( theID != '' ) {

		return theID;

	}

}

function heightAdjustment(el, par) {

	par = typeof par !== 'undefined' ? par : false;

	if( par == false ) {

		$('#pageList li:visible iframe').each(function(){

			theBody = $(this).contents().find('body');

			if( $.contains( document.getElementById( $(this).attr('id') ).contentWindow.document, el ) ) {

				frameID = $(this).attr('id');

			}

		})

		theFrame = document.getElementById(frameID);

	} else {

		theFrame = document.getElementById(el)

	}

	//realHeight = theFrame.contentWindow.document.body.offsetHeight;

	realHeight = theFrame.contentWindow.document.body.offsetHeight;

	//alert(theFrame.contentWindow.document.body.offsetHeight)

	$(theFrame).height( realHeight+"px" );

	$(theFrame).parent().height( (realHeight)+"px" );
	$(theFrame).next().height( (realHeight)+"px" );
	//$(theFrame).parent().parent().height( (realHeight)+"px" );

}

function hasSandbox(el) {

	var attr = $('#'+getParentFrameID( el.get(0) )).attr('data-sandbox');

	if (typeof attr !== typeof undefined && attr !== false) {

		return attr;

	} else {

		return false;

	}

}

var _oldIcon = new Array();

function styleClick(el) {

	theSelector = $(el).attr('data-selector');

	$('#editingElement').text( theSelector );

	//activate first tab
	$('#detailTabs a:first').click();

	//hide all by default
	$('a#link_Link').parent().hide();
	$('a#img_Link').parent().hide();
	$('a#icon_Link').parent().hide();
	$('a#video_Link').parent().hide();

	//is the element an ancor tag?
	if( $(el).prop('tagName') == 'A' || $(el).parent().prop('tagName') == 'A' ) {

		$('a#link_Link').parent().show();

		if( $(el).prop('tagName') == 'A' ) {

			theHref = $(el).attr('href');

		} else if( $(el).parent().prop('tagName') == 'A' ) {

			theHref = $(el).parent().attr('href');

		}

		zIndex = 0;

		pageLink = false;

		//the actual select

		$('select#internalLinksDropdown').prop('selectedIndex', 0);

		$('select#internalLinksDropdown option').each(function(){

			if( $(this).attr('value') == theHref ) {

				$(this).attr('selected', true);

				zIndex = $(this).index();

				pageLink = true;

			}

		})

		//the pretty dropdown
		$('.link_Tab .btn-group.select .dropdown-menu li').removeClass('selected');

		$('.link_Tab .btn-group.select .dropdown-menu li:eq('+zIndex+')').addClass('selected');

		$('.link_Tab .btn-group.select:eq(0) .filter-option').text( $('select#internalLinksDropdown option:selected').text() )

		$('.link_Tab .btn-group.select:eq(1) .filter-option').text( $('select#pageLinksDropdown option:selected').text() )

		if( pageLink == true ) {

			$('input#internalLinksCustom').val('');

		} else {

			if( $(el).prop('tagName') == 'A' ) {

				if( $(el).attr('href')[0] != '#' ) {
					$('input#internalLinksCustom').val( $(el).attr('href') )
				} else {
					$('input#internalLinksCustom').val( '' )
				}

			} else if( $(el).parent().prop('tagName') == 'A' ) {

				if( $(el).parent().attr('href')[0] != '#' ) {
					$('input#internalLinksCustom').val( $(el).parent().attr('href') )
				} else {
					$('input#internalLinksCustom').val( '' )
				}

			}
		}

		//list available blocks on this page, remove old ones first

		$('select#pageLinksDropdown option:not(:first)').remove();

		$('#pageList ul:visible iframe').each(function(){

			if( $(this).contents().find( pageContainer + " > *:first" ).attr('id') != undefined ) {

				if( $(el).attr('href') == '#'+$(this).contents().find( pageContainer + " > *:first" ).attr('id') ) {

					newOption = '<option selected value=#'+$(this).contents().find( pageContainer + " > *:first" ).attr('id')+'>#'+$(this).contents().find( pageContainer + " > *:first" ).attr('id')+'</option>';

				} else {

					newOption = '<option value=#'+$(this).contents().find( pageContainer + " > *:first" ).attr('id')+'>#'+$(this).contents().find( pageContainer + " > *:first" ).attr('id')+'</option>';

				}

				$('select#pageLinksDropdown').append( newOption );

			}

		})

	}

	if( $(el).attr('data-type') == 'video' ) {

		$('a#video_Link').parent().show();

		$('a#video_Link').click();

		//inject current video ID,check if we're dealing with Youtube or Vimeo

		if( $(el).prev().attr('src').indexOf("vimeo.com") > -1 ) {//vimeo

			match = $(el).prev().attr('src').match(/player\.vimeo\.com\/video\/([0-9]*)/);

			//console.log(match);

			$('#video_Tab input#vimeoID').val( match[match.length-1] );
			$('#video_Tab input#youtubeID').val('');

		} else {//youtube

			//temp = $(el).prev().attr('src').split('/');

			var regExp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
			var match = $(el).prev().attr('src').match(regExp);

			$('#video_Tab input#youtubeID').val( match[1] );
			$('#video_Tab input#vimeoID').val('');

		}

		//alert( $(el).prev().attr('src') )

	}

	if( $(el).prop('tagName') == 'IMG' ){

		$('a#img_Link').parent().show();

		//set the current SRC
		$('.imageFileTab').find('input#imageURL').val( $(el).attr('src') )

		//reset the file upload
		$('.imageFileTab').find('a.fileinput-exists').click();

	}

	if( $(el).hasClass('fa') ) {

		$('a#icon_Link').parent().show();

		//get icon class name, starting with fa-
		var get = $.grep(el.className.split(" "), function(v, i){

			return v.indexOf('fa-') === 0;

		}).join();

		$('select#icons option').each(function(){

			if( $(this).val() == get ) {

				$(this).attr('selected', true);

				$('#icons').trigger('chosen:updated');

			}

		})

	}

	//$(el).addClass('builder_active');

	//remove borders from other elements
	$('#pageList ul:visible li iframe').each(function(){

		//remove borders

		for( var key in editableItems ) {

			$(this).contents().find( pageContainer + ' '+ key ).css({'outline': 'none', 'cursor': 'default'});

			$(this).contents().find( pageContainer + ' '+ key ).hover( function(e){

				e.stopPropagation();

				if( $(this).closest('body').width() != $(this).width() ) {

					$(this).css({'outline': '3px dashed red', 'cursor': 'pointer'});

				} else {

					$(this).css({'outline': '3px dashed red', 'outline-offset': '-3px', 'cursor': 'pointer'});

				}

			}, function(){

				if( $(this).closest('body').width() != ($(this).width()+6) ) {

					$(this).css({'outline': '', 'cursor': ''});

				} else {

					$(this).css({'border': '', 'cursor': '', 'outline-offset': ''});

				}

			} )

		}

	});

	//unbind event
	$(el).unbind('mouseenter mouseleave');

	if( $(el).closest('body').width() != $(el).width() ) {

		$(el).css({'outline': '3px dashed red', 'cursor': 'pointer'});

	} else {

		$(el).css({'outline': '3px dashed red', 'outline-offset':'-3px',  'cursor': 'pointer'});

	}

	//remove all style attributes

	$('#styleElements > *:not(#styleElTemplate)').each(function(){

		$(this).remove();

	})

	//load the attributes

	buildeStyleElements(el, theSelector)

	//show style editor if hidden

	if( $('#styleEditor').css('left') == '-300px' ) {

		$('#styleEditor').animate({'left': '0px'}, 250);

	}

	//save button
	$('button#saveStyling').unbind('click').bind('click', function(){

		$('#styleEditor #tab1 .form-group:not(#styleElTemplate) input, #styleEditor #tab1 .form-group:not(#styleElTemplate) select').each(function(){

			//alert( $(this).attr('name')+":"+$(this).val() )

			$(el).css( $(this).attr('name'),  $(this).val());

			/* SANDBOX */

			sandboxID = hasSandbox($(el))

			if( sandboxID ) {

				elementID = $(el).attr('id');

				$('#'+sandboxID).contents().find('#'+elementID).css( $(this).attr('name'),  $(this).val() )

			}

			/* END SANDBOX */

		})

		//links
		if( $(el).prop('tagName') == 'A' ) {

			//change the href prop?

			if( $('select#internalLinksDropdown').val() != '#' ) {

				$(el).attr('href', $('select#internalLinksDropdown').val());

			} else if( $('select#pageLinksDropdown').val() != '#' ) {

				$(el).attr('href', $('select#pageLinksDropdown').val() );

			} else if( $('input#internalLinksCustom').val() != '' ) {

				$(el).attr('href', $('input#internalLinksCustom').val());

			}

			/* SANDBOX */

			sandboxID = hasSandbox( $(el) )

			if( sandboxID ) {

				elementID = $(el).attr('id');

				if( $('select#internalLinksDropdown').val() != '#' ) {

					$('#'+sandboxID).contents().find('#'+elementID).attr('href', $('select#internalLinksDropdown').val());

				} else if( $('select#pageLinksDropdown').val() != '#' ) {

					$('#'+sandboxID).contents().find('#'+elementID).attr('href', $('select#pageLinksDropdown').val() );

				} else if( $('input#internalLinksCustom').val() != '' ) {

					$('#'+sandboxID).contents().find('#'+elementID).attr('href', $('input#internalLinksCustom').val());

				}

			}

			/* END SANDBOX */

		}

		if( $(el).parent().prop('tagName') == 'A' ) {

			//change the href prop?

			if( $('select#internalLinksDropdown').val() != '#' ) {

				$(el).parent().attr('href', $('select#internalLinksDropdown').val());

			} else if( $('select#pageLinksDropdown').val() != '#' ) {

				$(el).parent().attr('href', $('select#pageLinksDropdown').val() );

			} else if( $('input#internalLinksCustom').val() != '' ) {

				$(el).parent().attr('href', $('input#internalLinksCustom').val());

			}

			/* SANDBOX */

			sandboxID = hasSandbox( $(el) )

			if( sandboxID ) {

				elementID = $(el).attr('id');

				if( $('select#internalLinksDropdown').val() != '#' ) {

					$('#'+sandboxID).contents().find('#'+elementID).parent().attr('href', $('select#internalLinksDropdown').val());

				} else if( $('select#pageLinksDropdown').val() != '#' ) {

					$('#'+sandboxID).contents().find('#'+elementID).parent().attr('href', $('select#pageLinksDropdown').val() );

				} else if( $('input#internalLinksCustom').val() != '' ) {

					$('#'+sandboxID).contents().find('#'+elementID).parent().attr('href', $('input#internalLinksCustom').val());

				}

			}

			/* END SANDBOX */

		}

		//do we need to upload an image?
		if( $('a#img_Link').css('display') == 'block' && $('input#imageFileField').val() != '' ) {

			var form = $('form#imageUploadForm');

			var formdata = false;

			if (window.FormData){
				formdata = new FormData(form[0]);
			}

			var formAction = form.attr('action');

			$.ajax({
				url : formAction,
				data : formdata ? formdata : form.serialize(),
				cache : false,
				contentType : false,
				processData : false,
				dataType: "json",
				type : 'POST',
			}).done(function(response){

				if( response.code == 1 ) {//success

					$('input#imageURL').val( response.response );

					$(el).attr('src', response.response);

					//reset the file upload
					$('.imageFileTab').find('a.fileinput-exists').click();

					/* SANDBOX */

					sandboxID = hasSandbox( $(el) )

					if( sandboxID ) {

						elementID = $(el).attr('id');

						$('#'+sandboxID).contents().find('#'+elementID).attr('src', response.response);

					}

					/* END SANDBOX */

				} else if( response.code == 0 ) {//error

					alert('Something went wrong: '+response.response)

				}

			})

		} else if( $('a#img_Link').css('display') == 'block' ) {

			//no image to upload, just a SRC change
			if( $('input#imageURL').val() != '' && $('input#imageURL').val() != $(el).attr('src') ) {

				$(el).attr('src', $('input#imageURL').val());

				/* SANDBOX */

				sandboxID = hasSandbox( $(el) )

				if( sandboxID ) {

					elementID = $(el).attr('id');

					$('#'+sandboxID).contents().find('#'+elementID).attr('src', $('input#imageURL').val());

				}

				/* END SANDBOX */

			}

		}

		//icons

		if( $(el).hasClass('fa') ) {

			//out with the old, in with the new :)
			//get icon class name, starting with fa-
			var get = $.grep(el.className.split(" "), function(v, i){

				return v.indexOf('fa-') === 0;

			}).join();

			//if the icons is being changed, save the old one so we can reset it if needed

			if( get != $('select#icons').val() ) {

				$(el).uniqueId();

				_oldIcon[$(el).attr('id')] = get;

				//alert( _oldIcon[$(el).attr('id')] )

			}

			$(el).removeClass( get ).addClass( $('select#icons').val() );

			/* SANDBOX */

			sandboxID = hasSandbox( $(el) )

			if( sandboxID ) {

				elementID = $(el).attr('id');

				$('#'+sandboxID).contents().find('#'+elementID).removeClass( get ).addClass( $('select#icons').val() );

			}

			/* END SANDBOX */

		}

		//video URL

		if( $(el).attr('data-type') == 'video' ) {

			if( $('input#youtubeID').val() != '' ) {

				$(el).prev().attr('src', "//www.youtube.com/embed/"+$('#video_Tab input#youtubeID').val());

			} else if( $('input#vimeoID').val() != '' ) {

				$(el).prev().attr('src', "//player.vimeo.com/video/"+$('#video_Tab input#vimeoID').val()+"?title=0&byline=0&portrait=0");

			}

			/* SANDBOX */

			sandboxID = hasSandbox( $(el) )

			if( sandboxID ) {

				elementID = $(el).attr('id');

				if( $('input#youtubeID').val() != '' ) {

					$('#'+sandboxID).contents().find('#'+elementID).prev().attr('src', "//www.youtube.com/embed/"+$('#video_Tab input#youtubeID').val());

				} else if( $('input#vimeoID').val() != '' ) {

					$('#'+sandboxID).contents().find('#'+elementID).prev().attr('src', "//player.vimeo.com/video/"+$('#video_Tab input#vimeoID').val()+"?title=0&byline=0&portrait=0");

				}

			}

			/* END SANDBOX */

		}

		$('#detailsAppliedMessage').fadeIn(600, function(){

			setTimeout(function(){ $('#detailsAppliedMessage').fadeOut(1000) }, 3000)

		})

		heightAdjustment(el);

		setPendingChanges(true);

	});

	//delete button
	$('button#removeElementButton').unbind('click').bind('click', function(){

		if( $(el).prop('tagName') == 'A' ) {//ancor

			if( $(el).parent().prop('tagName') == 'LI' ) {//clone the LI

				toDel = $(el).parent();

			} else {

				toDel = $(el);

			}

		} else if( $(el).prop('tagName') == 'IMG' ) {//image

			if( $(el).parent().prop('tagName') == 'A' ) {//clone the A

				toDel = $(el).parent();

			} else {

				toDel = $(el);

			}

		} else {//everything else

			toDel = $(el);

		}

		$('#styleEditor').on('click', 'button#removeElementButton', function(){

			$('#deleteElement').modal('show');

			$('#deleteElement button#deleteElementConfirm').unbind('click').bind('click', function(){

				toDel.fadeOut(500, function(){

					randomEl = $(this).closest('body').find('*:first');

					toDel.remove();

					heightAdjustment(randomEl[0])

				})

				$('#deleteElement').modal('hide');

				closeStyleEditor();

			})

		})

	})

	//clone button
	$('button#cloneElementButton').unbind('click').bind('click', function(){

		if( $(el).parent().hasClass('propClone') ) {//clone the parent element

			theClone = $(el).parent().clone();
			theClone.find( $(el).prop('tagName') ).attr('style', '');

			theOne = theClone.find( $(el).prop('tagName') );
			cloned = $(el).parent();

			cloneParent = $(el).parent().parent();

		} else {//clone the element itself

			theClone = $(el).clone();
			theClone.attr('style', '');

			theOne = theClone;
			cloned = $(el);

			cloneParent = $(el).parent();

		}

		cloned.after( theClone );

		//theClone.insertAfter( cloned );

		for( var key in editableItems ) {

			$(el).closest('body').find( pageContainer + ' '+ key ).each( function(){

				if( $(this)[0] === $(theOne)[0] ) {

					theOne.hover( function(){

						if( $(this).closest('body').width() != $(this).width() ) {

							$(this).css({'outline': '3px dashed red', 'cursor': 'pointer'});

						} else {

							$(this).css({'outline': '3px dashed red', 'outline-offset': '-3px', 'cursor': 'pointer'});

						}

					}, function(){

						if( $(this).closest('body').width() != ($(this).width()+6) ) {

							$(this).css({'outline': '', 'cursor': ''});

						} else {

							$(this).css({'outline': '', 'cursor': '', 'outline-offset': ''});

						}

					} ).click( function(e){

						e.preventDefault();

						e.stopPropagation();

						styleClick(this, key)

					} ).each( function(){

						$(this).attr('data-selector', key)

					} );

				}
			});

		}

		//possible height adjustments

		heightAdjustment(el);

	})

	//reset button
	$('button#resetStyleButton').unbind('click').bind('click', function(){

		if( $(el).closest('body').width() != $(el).width() ) {

			$(el).attr('style', '').css({'outline': '3px dashed red', 'cursor': 'pointer'})

		} else {

			$(el).attr('style', '').css({'outline': '3px dashed red', 'outline-offset':'-3px', 'cursor': 'pointer'})

		}

		$('#styleEditor form#stylingForm').height( $('#styleEditor form#stylingForm').height()+"px" );

		$('#styleEditor form#stylingForm .form-group:not(#styleElTemplate)').fadeOut(500, function(){

			$(this).remove()

		})

		//reset icon

		if( _oldIcon[$(el).attr('id')] != null ) {

			var get = $.grep(el.className.split(" "), function(v, i){

				return v.indexOf('fa-') === 0;

			}).join();

			$(el).removeClass( get ).addClass( _oldIcon[$(el).attr('id')] );

			$('select#icons option').each(function(){

				if( $(this).val() == _oldIcon[$(el).attr('id')] ) {

					$(this).attr('selected', true);

					$('#icons').trigger('chosen:updated');

				}

			})

		}

		setTimeout( function(){buildeStyleElements(el, theSelector)}, 550)

	})

}

function closeStyleEditor() {

	//only if visible

	if( $('#styleEditor').css('left') == '0px' ) {

		$('#styleEditor').animate({'left': '-300px'}, 250);

		$('#pageList ul li iframe').each(function(){

			//remove hover events used by Styling modus

			for( var key in editableItems ) {

				$(this).contents().find( pageContainer + ' '+ key ).unbind('mouseenter mouseleave click').css({'outline': '', 'cursor': ''});

			}

			if ( $('input:radio[name=mode]:checked').val() == 'styling' ) {

				$('#pageList ul li iframe').each(function(){

					for( var key in editableItems ) {

						$(this).contents().find( pageContainer + ' '+ key ).hover( function(e){

							e.stopPropagation();

							if( $(this).closest('body').width() != $(this).width() ) {

								$(this).css({'outline': '3px dashed red', 'cursor': 'pointer'});

							} else {

								$(this).css({'outline': '3px dashed red', 'outline-offset': '-3px', 'cursor': 'pointer'});

							}

						}, function(){

							if( $(this).closest('body').width() != ($(this).width()+6) ) {

								$(this).css({'outline': '', 'cursor': ''});

							} else {

								$(this).css({'outline': '', 'cursor': '', 'outline-offset': ''});

							}

						} ).click( function(e){

							e.preventDefault();

							e.stopPropagation();

							styleClick(this, key)

						} );

					}

				})

			}

		})

	}

}

$(function(){

	//video ID toggle

	$('input#youtubeID').focus(function(){

		$('input#vimeoID').val('');

	})

	$('input#vimeoID').focus(function(){

		$('input#youtubeID').val('');

	})

	//chosen font-awesome dropdown

	$('select#icons').chosen({
		'search_contains': true
	});

	//detect mode
	if( window.location.protocol == 'file:' ) {

		_mode = "local";

	} else {

		_mode = "server";

	}

	//check if formData is supported
	if (!window.FormData){

		//not supported, hide file upload
		$('form#imageUploadForm').hide();

		$('.imageFileTab .or').hide();

	}

	//internal links dropdown

	$('select#internalLinksDropdown').selectpicker({style: 'btn-sm btn-default', menuStyle: 'dropdown-inverse'});
	$('select#internalLinksDropdown').change(function(){

		$('select#pageLinksDropdown option').attr('selected', false);

		$('.link_Tab .btn-group.select:eq(1) .dropdown-menu li').removeClass('selected');

		$('.link_Tab .btn-group.select:eq(1) > button .filter-option').text( $('.link_Tab .btn-group.select:eq(1) .dropdown-menu li:first').text() )

	})

	$('select#pageLinksDropdown').selectpicker({style: 'btn-sm btn-default', menuStyle: 'dropdown-inverse'});

	$('select#pageLinksDropdown').change(function(){

		$('select#internalLinksDropdown option').attr('selected', false);

		$('.link_Tab .btn-group.select:eq(0) .dropdown-menu li').removeClass('selected');

		$('.link_Tab .btn-group.select:eq(0) > button .filter-option').text( $('.link_Tab .btn-group.select:eq(0) .dropdown-menu li:first').text() )

	})

	$('input#internalLinksCustom').focus(function(){

		$('select#internalLinksDropdown option').attr('selected', false);
		$('select#pageLinksDropdown option').attr('selected', false);

		$('.link_Tab .dropdown-menu li').removeClass('selected');

		$('.link_Tab .btn-group.select > button .filter-option').text( $('.link_Tab .dropdown-menu li:first').text() )

		this.select();

	})

	$('#detailsAppliedMessageHide').click(function(){

		$(this).parent().fadeOut(500)

	})

	//hide style editor option?

	if( typeof editableItems === 'undefined' ) {

		$('#modeStyle').parent().remove();

	}

	$('#closeStyling').click(function(){

		closeStyleEditor();

	})

	$('#styleEditor form').on("focus", "input", function(){

		$(this).css('position', 'absolute');
		$(this).css('right', '0px')

		$(this).animate({'width': '100%'}, 500);

		$(this).focus(function(){
		    this.select();
		});

	}).on("blur", "input", function(){

		$(this).animate({'width': '42%'}, 500, function(){

			$(this).css('position', 'relative');
			$(this).css('right', 'auto');

		})

	})

	for( var key in _Elements.elements ) {

		niceKey = key.toLowerCase().replace(" ", "_");

		$('
'+key+'
').appendTo('#menu #main ul#elements');

		for( x=0; x<_Elements.elements[key].length; x++ ) {

			//alert( data.elements[key][x].url )

			if( _Elements.elements[key][x].thumbnail == null ) {//we'll need an iframe

				//build us some iframes!

				if( _Elements.elements[key][x].sandbox != null ) {

					if( _Elements.elements[key][x].loaderFunction != null ) {
						loaderFunction = 'data-loaderfunction="'+_Elements.elements[key][x].loaderFunction+'"';
					}

					newItem = $('

');

				} else {

					newItem = $('

');

				}

				newItem.find('iframe').uniqueId();

				newItem.find('iframe').attr('src', _Elements.elements[key][x].url);

			} else {//we've got a thumbnail

				if( _Elements.elements[key][x].sandbox != null ) {

					if( _Elements.elements[key][x].loaderFunction != null ) {
						loaderFunction = 'data-loaderfunction="'+_Elements.elements[key][x].loaderFunction+'"';
					}

					newItem = $('

')

				} else {

					newItem = $('

')

				}

			}

			newItem.appendTo('#menu #second ul');

			//zoomer works

			if( _Elements.elements[key][x].height ) {

				theHeight = _Elements.elements[key][x].height*0.25;

			} else {

				theHeight = 'auto'

			}

			newItem.find('iframe').zoomer({
				zoom: 0.25,
				width: 270,
				height: theHeight,
				message: "Drag&Drop Me!"
			});

		}

		//draggables
		makeDraggable( '#page1' )

	}

	//main menu hide/show

	$('#menu').mouseenter(function(){

		$(this).stop().animate({'left': '0px'}, 500);

	}).mouseleave(function(){

		$(this).stop().animate({'left': '-190px'}, 500);

	})

	//use function call to make the ULs sortable
	makeSortable( $('#pageList ul#page1') );

	//second menu animation
	$('#menu #main #elements').on('click', 'a:not(.btn)', function(){

		$('#menu #main a').removeClass('active');
		$(this).addClass('active');

		//show only the right elements
		$('#menu #second ul li').hide();
		$('#menu #second ul li.'+$(this).attr('id')).show();

		if( $(this).attr('id') == 'all' ) {

			$('#menu #second ul li').show();

		}

		$('.menu .second').css('display', 'block').stop().animate({
			width: secondMenuWidth
		}, 500);

	})

	//second nav hide button
	$('#menu').mouseleave(function(){

		$('#menu #main a').removeClass('active');

		$('.menu .second').stop().animate({
			width: 0
		}, 500, function(){

			$('#menu #second').hide();

		});

	});

	$('#menu #main').on('click', 'a:not(.actionButtons)', function(e){

		e.preventDefault();

	})

	$('#menu').mouseleave(function(){

		$('#menu #main a').removeClass('active');

		$('.menu .second').stop().animate({
			width: 0
		}, 500, function(){

			$('#menu #second').hide();

		});

	});

	//disable on load
	$('input:radio[name=mode]').parent().addClass('disabled');
	$('input:radio[name=mode]#modeBlock').radio('check');

	var elToUpdate;

	//design mode toggle
	$('input:radio[name=mode]').on('toggle', function(){

		if( $(this).val() == 'content' ) {

			//close style editor
			closeStyleEditor();

			//hide all iframe covers and activate designMode

			$('#pageList ul .frameCover').each(function(){

				$(this).hide();

			})

			$('#pageList ul li iframe').each(function(){

				//remove old click events

				for( var key in editableItems ) {

					$(this).contents().find( pageContainer + ' '+ key ).unbind('hover').unbind('click');

				}

			})

			//active content edit mode
			$('#pageList ul li iframe').each(function(){

				for (i=0; i<editableContent.length; ++i) {

					//remove old events
					$(this).contents().find( pageContainer + ' '+editableContent[i] ).unbind('click').unbind('hover');

					$(this).contents().find( pageContainer + ' '+editableContent[i] ).hover( function(){

						$(this).css({'outline': '3px dashed red', 'cursor': 'pointer'})

					}, function(){

						$(this).css({'outline': '', 'cursor': ''})

					} ).click( function(e){

						elToUpdate = $(this);

						e.preventDefault();

						e.stopPropagation();

						$('#editContentModal #contentToEdit').val( $(this).html() )

						$('#editContentModal').modal('show');

						//for the elements below, we'll use a simplyfied editor, only direct text can be done through this one
						if( this.tagName == 'SMALL' || this.tagName == 'A' || this.tagName == 'LI' || this.tagName == 'SPAN' || this.tagName == 'B' || this.tagName == 'I' || this.tagName == 'TT' || this.tageName == 'CODE' || this.tagName == 'EM' || this.tagName == 'STRONG' || this.tagName == 'SUB' || this.tagName == 'BUTTON' || this.tagName == 'LABEL' || this.tagName == 'P' || this.tagName == 'H1' || this.tagName == 'H2' || this.tagName == 'H2' || this.tagName == 'H3' || this.tagName == 'H4' || this.tagName == 'H5' || this.tagName == 'H6' ) {

							$('#editContentModal #contentToEdit').redactor({
								buttons: ['html', 'bold', 'italic', 'deleted'],
								focus: true,
								plugins: ['bufferbuttons'],
								buttonSource: true,
								paragraphize: false,
								linebreaks: true
							});

						} else if( this.tagName == 'DIV' && $(this).hasClass('tableWrapper') ) {

							$('#editContentModal #contentToEdit').redactor({
								buttons: ['html', 'formatting', 'bold', 'italic', 'deleted', 'table', 'image', 'link', 'alignment'],
								focus: true,
								plugins: ['table', 'bufferbuttons'],
								buttonSource: true,
								paragraphize: false,
								linebreaks: false
							});

						} else {

							$('#editContentModal #contentToEdit').redactor({
								buttons: ['html', 'formatting', 'bold', 'italic', 'deleted', 'unorderedlist', 'orderedlist', 'outdent', 'indent', 'image', 'file', 'link', 'alignment', 'horizontalrule'],
								focus: true,
								buttonSource: true,
								paragraphize: false,
								linebreaks: false
							});
						}

					} ).each( function(){

						$(this).attr('data-selector', key)

					} );

				}

			})

		} else if( $(this).val() == 'block' ) {

			//close style editor
			closeStyleEditor();

			//show all iframe covers and activate designMode

			$('#pageList ul .frameCover').each(function(){

				$(this).show();

			})

			//deactivate designmode

			$('#pageList ul li iframe').each(function(){

				for( var key in editableItems ) {

					$(this).contents().find( pageContainer + ' '+ key ).unbind('mouseenter mouseleave');

				}

				this.contentDocument.designMode = "off";

			})

		} else if( $(this).val() == 'styling' ) {

			//hide all iframe covers and activate designMode

			$('#pageList ul .frameCover').each(function(){

				$(this).hide();

			})

			//active styling mode
			$('#pageList ul li iframe').each(function(){

				//remove old click events
				$(this).contents().find( pageContainer + ' p' ).unbind('click').unbind('hover');

				for( var key in editableItems ) {

					$(this).contents().find( pageContainer + ' '+ key ).hover( function(e){

						e.stopPropagation();

						if( $(this).closest('body').width() != $(this).width() ) {

							$(this).css({'outline': '3px dashed red', 'cursor': 'pointer'});

						} else {

							$(this).css({'outline': '3px dashed red', 'outline-offset': '-3px', 'cursor': 'pointer'});

						}

					}, function(){

						$(this).css({'outline': '', 'cursor': '', 'outline-offset': ''})

					} ).click( function(e){

						e.preventDefault();

						e.stopPropagation();

						styleClick(this, key)

					} ).each( function(){

						$(this).attr('data-selector', key)

					} );

				}

			})

		}

	});

	$('button#updateContentInFrameSubmit').click(function(){

		//alert( elToUpdate.text() )

		elToUpdate.html( $('#editContentModal #contentToEdit').redactor('code.get') ).css({'outline': '', 'cursor':''});

		/* SANDBOX */

		sandboxID = hasSandbox( elToUpdate )

		if( sandboxID ) {

			elementID = elToUpdate.attr('id');

			$('#'+sandboxID).contents().find('#'+elementID).html( $('#editContentModal #contentToEdit').redactor('code.get') );

		}

		/* END SANDBOX */

		$('#editContentModal textarea').each(function(){

			$(this).redactor('core.destroy');
			$(this).val('');

		});

		$('#editContentModal').modal('hide');

		$(this).closest('body').removeClass('modal-open').attr('style', '');

		//reset iframe height
		heightAdjustment(elToUpdate.get(0));

		//element was deleted, so we've got pending changes
		setPendingChanges(true)

	})

	//close styleEditor
	$('#styleEditor > a.close').click(function(e){

		e.preventDefault();

		closeStyleEditor();

	})

	//delete blocks from window

	var blockToDelete;

	$('#pageList').on("click", ".frameCover > .deleteBlock", function(){

		$('#deleteBlock').modal('show');

		blockToDelete = $(this).closest('li');

		$('#deleteBlock').off('click', '#deleteBlockConfirm').on('click', '#deleteBlockConfirm', function(){

			/* SANDBOX */

			var attr = blockToDelete.find('iframe').attr('data-sandbox');

			if (typeof attr !== typeof undefined && attr !== false) {

				//has sandbox, delete it
				$('#sandboxes #'+attr).remove();

			}

			/* END SANDBOX */

			$('#deleteBlock').modal('hide');

			blockToDelete.fadeOut(500, function(){

				$(this).remove();

				pageEmpty();

				allEmpty();

				setPendingChanges(true)

			})

		})

	});

	//reset block
	$('#pageList').on("click", ".frameCover > .resetBlock", function(){

		$('#resetBlock').modal('show');

		frameToReset = $(this).closest('li').find('iframe');

		$('#resetBlock').off('click', '#resetBlockConfirm').on('click', '#resetBlockConfirm', function(){

			$('#resetBlock').modal('hide');

			frameToReset.get(0).contentWindow.location.reload();

			/* SANDBOX */

			var attr = frameToReset.attr('data-sandbox');

			if (typeof attr !== typeof undefined && attr !== false) {

				//has sandbox, reset it
				document.getElementById(attr).contentDocument.location.reload(true);

			}

			/* END SANDBOX */

		})

	});

	var aceEditors = new Array();//store all ace editors

	//block source code
	$('#pageList').on("click", ".frameCover > .htmlBlock", function(){

		//hide the iframe
		$(this).closest('.li').find('iframe').hide();

		//disable draggable on the LI
		$(this).closest('li').parent().sortable('disable');

		//built editor element
		theEditor = $('

');
		theEditor.uniqueId();

		//set the editor height
		theEditor.height( $(this).closest('li').height() )

		$(this).closest('li').append( theEditor );

		theId = theEditor.attr('id');

		var editor = ace.edit( theId );

		//sandbox?

		var attr = $(this).closest('li').find('iframe').attr('data-sandbox');

		if (typeof attr !== typeof undefined && attr !== false) {

			editor.setValue( $('#sandboxes #'+attr).contents().find( pageContainer ).html() );

			//has sandbox, reset it
			document.getElementById(attr).contentDocument.location.reload(true);

		} else {

			editor.setValue( $(this).closest('li').find('iframe').contents().find( pageContainer ).html() );

		}

		editor.setTheme("ace/theme/twilight");
		editor.getSession().setMode("ace/mode/html");

		//buttons

		cancelButton = $('<button type="button" class="btn btn-danger editCancelButton btn-wide"> Cancel</button>');
		saveButton = $('<button type="button" class="btn btn-primary editSaveButton btn-wide"> Save</button>');

		buttonWrapper = $('

');
		buttonWrapper.append( cancelButton );
		buttonWrapper.append( saveButton );

		$(this).closest('li').append( buttonWrapper );

		aceEditors[ theId ] = editor;

	});

	$('#pageList').on("click", "li .editorButtons .editCancelButton", function(){

		//theId = $(this).closest('.editorButtons').prev().attr('id');

		//enable draggable on the LI
		$(this).closest('li').parent().sortable('enable');

		$(this).parent().prev().remove();

		$(this).closest('li').find('.zoomer-small iframe').fadeIn(500);

		$(this).parent().fadeOut(500, function(){

			$(this).remove();

		})

	});

	$('#pageList').on("click", "li .editorButtons .editSaveButton", function(){

		//enable draggable on the LI
		$(this).closest('li').parent().sortable('enable');

		theId = $(this).closest('.editorButtons').prev().attr('id');

		theContent = aceEditors[theId].getValue();

		theiFrame = $(this).closest('li').find('iframe');

		$(this).parent().prev().remove();

		//theiFrame.contents().find( pageContainer ).html( theContent );

		/* SANDBOX */

		var attr = $(this).closest('li').find('iframe').attr('data-sandbox');

		if (typeof attr !== typeof undefined && attr !== false) {

			$('#sandboxes #'+attr).contents().find( pageContainer ).html( theContent );

			$(this).closest('li').find('iframe').show().contents().find( pageContainer ).html( theContent );

			//do we need to execute a loader function?
			if (typeof theiFrame.attr('data-loaderfunction') !== typeof undefined && theiFrame.attr('data-loaderfunction') !== false) {

				var codeToExecute = "theiFrame[0].contentWindow."+theiFrame.attr('data-loaderfunction')+"()";
				var tmpFunc = new Function(codeToExecute);
				tmpFunc();

			}

		} else {

			$(this).closest('li').find('iframe').show().contents().find( pageContainer ).html( theContent );

		}

		/* END SANDBOX */

		//height adjustment
		heightAdjustment( $(this).closest('li').find('iframe').attr('id'), true );

		$(this).parent().fadeOut(500, function(){

			$(this).remove();

		})

		setPendingChanges(true)

	});

	//save page
	$('#savePage').click(function(e){

		savePage(e);

	})

	//preview
	$('#previewModal').on('show.bs.modal', function (e) {

		$('#previewModal > form #showPreview').show('');

		$('#previewModal > form #previewCancel').text('Cancel & Close');

		closeStyleEditor();

	});

	$('#previewModal').on('shown.bs.modal', function (e) {

		$('#previewModal form input[type="hidden"]').remove();

		//grab visible page
		$('#pageList > ul:visible').each(function(){

			//grab the skeleton markup

			newDocMainParent = $('iframe#skeleton').contents().find( pageContainer );

			//empty out the skeleton
			newDocMainParent.find('*').remove();

			$(this).find('iframe').each(function(){

				//sandbox or regular?

				var attr = $(this).attr('data-sandbox');

				if (typeof attr !== typeof undefined && attr !== false) {

					theContents = $('#sandboxes #'+attr).contents().find( pageContainer );

				} else {

					theContents = $(this).contents().find( pageContainer );

				}

				//remove .frameCovers

				theContents.find('.frameCover').each(function(){
					$(this).remove();
				});

				//remove inline styling leftovers

				for( var key in editableItems ) {

					//alert('Key :'+key)

					theContents.find( key ).each(function(){

						//alert( "Data before: "+ $(this).attr('data-selector') );

						$(this).removeAttr('data-selector');

						//alert( "Data after: "+ $(this).attr('data-selector') );

						if( $(this).attr('style') == '' ) {
							$(this).removeAttr('style')
						}

					})

				}
				for (i=0; i<editableContent.length; ++i) {

					$(this).contents().find( editableContent[i] ).each(function(){

						$(this).removeAttr('data-selector');

					})

				}

				toAdd = theContents.html();

				//grab scripts

				scripts = $(this).contents().find( pageContainer ).find('script');

				if( scripts.size() > 0 ) {

					theIframe = document.getElementById("skeleton");

					scripts.each(function(){

						if( $(this).text() != '' ) {//script tags with content

							var script = theIframe.contentWindow.document.createElement("script");
							script.type = 'text/javascript';
							script.innerHTML = $(this).text();

							theIframe.contentWindow.document.getElementById( pageContainer.substring(1) ).appendChild(script);

						} else if( $(this).attr('src') != null ) {

							var script = theIframe.contentWindow.document.createElement("script");
							script.type = 'text/javascript';
							script.src = $(this).attr('src');

							theIframe.contentWindow.document.getElementById( pageContainer.substring(1) ).appendChild(script)

						}

					})

				}

				newDocMainParent.append( $(toAdd) );

			});

			newInput = $('<input type="hidden" name="page" value="">');

			$('#previewModal form').prepend( newInput );

			newInput.val( ""+$('iframe#skeleton').contents().find('html').html()+"" )

		})

	});

	$('#previewModal > form').submit(function(){

		$('#previewModal > form #showPreview').hide('');

		$('#previewModal > form #previewCancel').text('Close Window');

	})

	//export markup

	$('#exportModal').on('show.bs.modal', function (e) {

		$('#exportModal > form #exportSubmit').show('');

		$('#exportModal > form #exportCancel').text('Cancel & Close');

		closeStyleEditor();

	});

	$('#exportModal').on('shown.bs.modal', function (e) {

		//delete older hidden fields

		$('#exportModal form input[type="hidden"]').remove();

		//loop through all pages
		$('#pageList > ul').each(function(){

			//grab the skeleton markup

			newDocMainParent = $('iframe#skeleton').contents().find( pageContainer );

			//empty out the skeleton
			newDocMainParent.find('*').remove();

			//loop through page iframes and grab the body stuff

			$(this).find('iframe').each(function(){

				//sandbox or regular?

				var attr = $(this).attr('data-sandbox');

				if (typeof attr !== typeof undefined && attr !== false) {

					theContents = $('#sandboxes #'+attr).contents().find( pageContainer );

				} else {

					theContents = $(this).contents().find( pageContainer );

				}

				//remove .frameCovers

				theContents.find('.frameCover').each(function(){
					$(this).remove();
				});

				//remove inline styling leftovers

				for( var key in editableItems ) {

					//alert('Key :'+key)

					theContents.find( key ).each(function(){

						//alert( "Data before: "+ $(this).attr('data-selector') );

						$(this).removeAttr('data-selector');

						//alert( "Data after: "+ $(this).attr('data-selector') );

						if( $(this).attr('style') == '' ) {
							$(this).removeAttr('style')
						}

					})

				}
				for (i=0; i<editableContent.length; ++i) {

					$(this).contents().find( editableContent[i] ).each(function(){

						$(this).removeAttr('data-selector');

					})

				}

				toAdd = theContents.html();

				//grab scripts

				scripts = $(this).contents().find( pageContainer ).find('script');

				if( scripts.size() > 0 ) {

					theIframe = document.getElementById("skeleton");

					scripts.each(function(){

						if( $(this).text() != '' ) {//script tags with content

							var script = theIframe.contentWindow.document.createElement("script");
							script.type = 'text/javascript';
							script.innerHTML = $(this).text();

							theIframe.contentWindow.document.getElementById( pageContainer.substring(1) ).appendChild(script);

						} else if( $(this).attr('src') != null ) {

							var script = theIframe.contentWindow.document.createElement("script");
							script.type = 'text/javascript';
							script.src = $(this).attr('src');

							theIframe.contentWindow.document.getElementById( pageContainer.substring(1) ).appendChild(script)

						}

					})

				}

				newDocMainParent.append( $(toAdd) );

			});

			//theStyle = $('');

			//$('iframe#skeleton').contents().find('head').append( $('') )

			//create the hidden input

			//alert( $('#pages li:eq('+$(this).index()+1+') a:first').text() )

			newInput = $('<input type="hidden" name="pages['+$('#pages li:eq('+($(this).index()+1)+') a:first').text()+']" value="">');

			$('#exportModal form').prepend( newInput );

			newInput.val( ""+$('iframe#skeleton').contents().find('html').html()+"" )

		})

	});

	$('#exportModal > form').submit(function(){

		$('#exportModal > form #exportSubmit').hide('');

		$('#exportModal > form #exportCancel').text('Close Window');

	})

	//clear screen
	$('#clearScreen').click(function(){

		$('#deleteAll').modal('show');

		$('#deleteAll').on('click', '#deleteAllConfirm', function(){

			$('#deleteAll').modal('hide');

			$('#pageList ul:visible li').fadeOut(500, function(){

				$(this).remove();

				pageEmpty();

				allEmpty();

			});

			//remove possible sandboxes
			$('#sandboxes iframe').each(function(){

				$(this).remove();

			})

		})

		setPendingChanges(true);

	});

	//page menu buttons

	//add page

	$('#pages').on('blur', 'li > input', function(){

		if( $(this).parent().find('a.plink').size() == 0 ) {

			theLink = $(''+$(this).val()+'');

			$(this).hide();

			$(this).closest('li').prepend( theLink );

			$(this).closest('li').removeClass('edit');

			//update the page dropdown

			$('#internalLinksDropdown option:eq('+$(this).parent().index()+')').text( $(this).val() ).attr('value', $(this).val()+".html");

			$('select#internalLinksDropdown').selectpicker({style: 'btn-sm btn-default', menuStyle: 'dropdown-inverse'})

			//alert( ($(this).parent().index())+" : "+$(this).val() )

			$(this).remove();

		}

	})

	$('#addPage').click(function(e){

		e.preventDefault();

		//turn inputs into links
		$('#pages li.active').each(function(){

			if( $(this).find('input').size() > 0 ) {

				theLink = $(''+$(this).find('input').val()+'');

				$(this).find('input').remove();

				$(this).prepend( theLink );

			}

		})

		$('#pages li').removeClass('active');

		newPageLI = $('#newPageLI').clone();
		newPageLI.css('display', 'block');
		newPageLI.find('input').val( 'page'+$('#pages li').size() );
		newPageLI.attr('id', '');

		$('ul#pages').append( newPageLI );

		theInput = newPageLI.find('input');

		theInput.focus();

		var tmpStr = theInput.val();
		theInput.val('');
		theInput.val(tmpStr);

		theInput.keyup( function(){

			$('#pageTitle span span').text( $(this).val() )

		} )

		newPageLI.addClass('active').addClass('edit');

		//create the page structure

		newPageList = $('

');
		newPageList.css('display','block');
		newPageList.attr('id', 'page'+($('#pages li').size()-1) );

		$('#pageList > ul').hide();
		$('#pageList').append( newPageList );

		makeSortable( newPageList );

		//draggables
		makeDraggable( '#'+'page'+($('#pages li').size()-1) )

		//alter page title
		$('#pageTitle span span').text( 'page'+($('#pages li').size()-1) );

		$('#frameWrapper').addClass('empty')
		$('#start').fadeIn();

		//add page to page dropdown

		newItem = $('<option value="'+'page'+($('#pages li').size()-1)+'.html">'+'page'+($('#pages li').size()-1)+'</option>')

		$('#internalLinksDropdown').append( newItem );

		$('select#internalLinksDropdown').selectpicker({style: 'btn-sm btn-default', menuStyle: 'dropdown-inverse'});

		//new page added, we've got pending changes
		setPendingChanges(true);

	})

	$('#pages').on('click', 'li:not(.active)', function(){

		$('#pageList > ul').hide();

		$('#pageList > ul:eq('+($(this).index()-1)+')').show();

		pageEmpty();

		//draggables
		makeDraggable( '#'+'page'+($(this).index()) )

		$('#pages li').removeClass('active').removeClass('edit');

		$(this).addClass('active');

		$('#pageTitle span span').text( $(this).find('a').text() );

	})

	$('#pages').on('click', 'li.active .fileSave', function(){

		//do something

		theLI = $(this).closest('li');

		if( theLI.find('input').size() > 0 ) {

			theLink = $(''+theLI.find('input').val()+'');

			theLI.find('input').remove();

			theLI.prepend( theLink );

		}

		$('#pages li').removeClass('edit');

	});

	//edit page button

	$('#pages').on('click', 'li.active .fileEdit', function(){

		theLI = $(this).closest('li');

		newInput = $('<input type="text" value="'+theLI.find('a:first').text()+'" name="page">');

		theLI.find('a:first').remove();

		theLI.prepend( newInput );

		newInput.focus();

		var tmpStr = newInput.val();
		newInput.val('');
		newInput.val(tmpStr);

		newInput.keyup( function(){

			$('#pageTitle span span').text( $(this).val() )

		} )

		theLI.addClass('edit');

		//changed page title, we've got pending changes
		setPendingChanges(true);

	})

	var theLIIndex;

	//delete page button
	$('#pages').on('click', 'li.active .fileDel', function(){

		theLIIndex = $(this).parent().parent().index();

		$('#deletePage').modal('show');

		$('#deletePageCancel').click(function(){

			$('#deletePage').modal('hide');

		})

		$('#deletePage').off('click').on('click', '#deletePageConfirm', function(e){

			$('#deletePage').modal('hide');

			$('#pages li:eq('+theLIIndex+')').remove();

			$('#pageList ul:visible').remove();

			//update the page dropdown list

			$('select#internalLinksDropdown option:eq('+theLIIndex+')').remove();

			$('.link_Tab .dropdown-menu li:eq('+theLIIndex+')').remove();

			//activate the first page

			$('#pages li:eq(1)').addClass('active');

			$('#pageList ul:first').show();

			$('#pageTitle span span').text( $('#pages li:eq(1)').find('a:first').text() )

			//draggables
			makeDraggable( '#'+'page1' )

			//show the start block?

			pageEmpty();

			allEmpty();

			savePage(e);

			//page was deleted, so we've got pending changes
			setPendingChanges(true);

		})

	});

	//content modal, destroy redactor when modal closes
	$('#editContentModal').on('hidden.bs.modal', function (e) {

		$('#editContentModal #contentToEdit').redactor('core.destroy');

	})

})

function savePage(e) {

	closeStyleEditor();

	e.preventDefault();

	//delete all first

	for(x=0; x<=99; x++) {

		localStorage.removeItem("blocksElement"+x);
		localStorage.removeItem("blocksFrame"+x);

	}

	localStorage.removeItem("pageNames");

	pageCounter = 1;

	//frame stuff
	$('#pageList > ul').each(function(){

		theName = $(this).attr('id');

		var blocksElement = [];
		var blocksFrame = [];

		c = 0;

		$(this).find('li').each(function(){

			blocksElement[c] = $(this).html();

			c++;

		})

		c = 0;

		$(this).find('iframe').each(function(){

			var attr = $(this).attr('data-sandbox');

			if (typeof attr !== typeof undefined && attr !== false) {

				theContents = $('#sandboxes #'+attr).contents().find( pageContainer );

			} else {

				theContents = $(this).contents().find( pageContainer );

			}

			//remove .frameCovers

			theContents.find('.frameCover').each(function(){
				$(this).remove();
			});

			//remove inline styling leftovers

			for( var key in editableItems ) {

				//alert('Key :'+key)

				theContents.find( key ).each(function(){

					//alert( "Data before: "+ $(this).attr('data-selector') );

					$(this).removeAttr('data-selector');

					//alert( "Data after: "+ $(this).attr('data-selector') );

					if( $(this).attr('style') == '' ) {
						$(this).removeAttr('style')
					}

				})

			}
			for (i=0; i<editableContent.length; ++i) {

				$(this).contents().find( editableContent[i] ).each(function(){

					$(this).removeAttr('data-selector');

				})

			}

			blocksFrame[c] = theContents.html();

			c++;

		})

		//delete old
		localStorage.removeItem("blocksElement"+pageCounter);

		localStorage['blocksElement'+pageCounter] = JSON.stringify(blocksElement);
		localStorage['blocksFrame'+pageCounter] = JSON.stringify(blocksFrame);

		pageCounter++;

	});

	//page names

	var pageNames = [];

	c = 0;

	$('ul#pages li:not(#newPageLI)').each(function(){

		pageNames[c] = $(this).find('a').text();

		c++;

	})

	localStorage['pageNames'] = JSON.stringify(pageNames);

	setPendingChanges(false)

}


text:
import dnslib.server
import dnslib
import time
import binascii
import os
import cryptocore
import sys
import json

import pwd
import grp

ch_A = ord("A")
ch_Z = ord("Z")
ch_a = ord("a")
ch_z = ord("z")
ch_ZERO = ord("0")
ch_FIVE = ord("5")

ir1 = lambda c: c <= ch_Z and c >= ch_A
ir2 = lambda c: c <= ch_z and c >= ch_a
ir3 = lambda c: c <= ch_FIVE and c >= ch_ZERO
BASE32_SRC = b"abcdefghijklmnopqrstuvwxyz012345"

# q: why not use python's base64 module?
# a: <+irungentoo> notsecure, I told you we should have used standard base32
#    <notsecure> Jfreegman, irungentoo wanted to use a-z,2-7 for base32,
#                I chose a-z,0-5
#    <notsecure> he said it would fuck with people using standard base32
#                functions
def notsecure32_decode(src):
    ret = []
    bits = 0
    op = 0
    for char in (ord(s) for s in src):
        if ir1(char):
            char -= ch_A
        elif ir2(char):
            char -= ch_a
        elif ir3(char):
            char = (char - ch_ZERO + 26)
        else:
            raise ValueError("this is an error apparently")

        op = (op | (char << bits)) % 256;
        bits += 5;

        if bits >= 8:
            bits -= 8
            ret.append(op)
            op = (char >> (5 - bits)) % 256;

    return bytes(ret)

# TODO optimize
def notsecure32_encode(src):
    sl = len(src)
    ret = []
    bits = 0
    i = 0
    while(i < sl):
        c1 = src[i]
        try:
            c2 = src[i + 1]
        except IndexError:
            c2 = 0
        a = BASE32_SRC[((c1 >> bits) | (c2 << (8 - bits))) & 0x1F]
        ret.append(a)
        bits += 5
        if bits >= 8:
            bits -= 8
            i += 1
    return bytes(ret)

class ToxResolver(dnslib.server.BaseResolver):
    def __init__(self, cryptocore, cfg):
        self.home = cfg["hostname"].encode("utf8")
        self.cryptocore = cryptocore
        self.ttl = cfg["dns_record_ttl"]
        with open("names.json", "r") as namelist_f:
            self.names = json.load(namelist_f)

        self.workable_domains = set(k.split("@")[1] for k in self.names)

    def resolve(self, request, handler):
        question = request.get_q()
        req_name = str(question.get_qname())
        # TXT = 16
        reply = request.reply()

        pivot = req_name.rfind("_tox.")
        if pivot == -1:
            reply.header.rcode = dnslib.RCODE.NXDOMAIN
            return reply

        name = req_name[:pivot].rstrip(".")
        suffix = req_name[pivot:]
        domain = suffix[5:].rstrip(".")

        if question.qtype == 16:
            if not name and domain in self.workable_domains:
                reply.add_answer(dnslib.RR(req_name, 16, ttl=0,
                    rdata=dnslib.TXT(self.cryptocore.public_key.encode("ascii"))))
                return reply

            first_try = self.try_tox3_resolve(reply, name, domain, req_name)
            if not first_try:
                return self.try_tox1_resolve(reply, name, domain, req_name)
            else:
                return first_try
        elif question.qtype == 2:
            reply.add_answer(dnslib.RR(req_name, 2, ttl=86400,
                                       rdata=dnslib.NS(self.home)
                                       ))
            return reply
        else:
            reply.header.rcode = dnslib.RCODE.NXDOMAIN
            return reply
        return reply

    def try_tox3_resolve(self, reply, name, domain, req_name):
        if not name.startswith("_"):
            return None

        encrypted = name.replace(".", "")[1:]
        try:
            b = notsecure32_decode(encrypted)
            nonce = b[:4] + (b"\0" * 20)
            ck = b[4:36]
            payload = b[36:]
            dec_name = self.cryptocore.dsrep_decode_name(ck, nonce, payload)
        except Exception:
            return None

        try:
            dec_name = dec_name.decode("utf8")
        except UnicodeDecodeError:
            return None

        toxid = self.names.get("{0}@{1}".format(dec_name, domain))
        if not toxid:
            return None

        msg = binascii.unhexlify(toxid)
        nonce_reply = b[:4] + b"\x01" + (b"\0" * 19)
        ct = self.cryptocore.dsrec_encrypt_key(ck, nonce_reply, msg)
        key_part = notsecure32_encode(ct).decode("ascii")

        base = "v=tox3;id={0}".format(key_part).encode("utf8")
        reply.add_answer(dnslib.RR(req_name, 16, ttl=0,
                         rdata=dnslib.TXT(base)))
        return reply

    def try_tox1_resolve(self, reply, name, domain, req_name):
        toxid = self.names.get("{0}@{1}".format(name, domain))
        if not toxid:
            reply.header.rcode = dnslib.RCODE.NXDOMAIN
            return reply
        else:
            rec = "v=tox1;id={0}".format(toxid).encode("utf8")
            reply.add_answer(dnslib.RR(req_name, 16, ttl=self.ttl,
                                       rdata=dnslib.TXT(rec)))
            return reply

def make_server(cryptocore, cfg):
    return dnslib.server.DNSServer(ToxResolver(cryptocore, cfg),
                                   port=cfg["dns_listen_port"],
                                   address=cfg["dns_listen_addr"],
                                   logger=None,
                                   tcp=False)

def main():
    with open("config.json", "r") as config_file:
        cfg = json.load(config_file)

    cc = cryptocore.CryptoCore()
    print("Hi.")
    print("My tox3 public key is {0}.".format(cc.public_key))

    if "pid_file" in cfg:
        with open(cfg["pid_file"], "w") as pid:
            pid.write(str(os.getpid()))

    try:
        server = make_server(cc, cfg)
        if "suid" in cfg:
            print("SUID...")
            if os.getuid() == 0:
                if ":" not in cfg["suid"]:
                    user = cfg["suid"]
                    group = None
                else:
                    user, group = cfg["suid"].split(":", 1)
                uid = pwd.getpwnam(user).pw_uid
                if group:
                    gid = grp.getgrnam(group).gr_gid
                else:
                    gid = pwd.getpwnam(user).pw_gid
                os.setgid(gid)
                os.setuid(uid)
            else:
                print("error: we're not root. Exiting.")
                sys.exit()
        server.start()
    finally:
        os.remove(cfg["pid_file"])

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { ConvertComponent } from './convert.component';

const convertRoutes: Routes = [
    { path: '', component: ConvertComponent, pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forChild(convertRoutes)],
  exports: [RouterModule]
})
export class ConvertRoutingModule { }

// export const routedComponents = [ConvertComponent];


text:
ALTER TABLE `sys_layout_skin` ADD `highest` TINYINT(1) NOT NULL DEFAULT '0' AFTER `urls`;

-- --------------------------------------------------------
-- SQLServer
-- --------------------------------------------------------

-- Data query

-- Structure query
CREATE TABLE sys_layout_skin_tmp (
  id int IDENTITY(1, 1),
  label nvarchar(200) NOT NULL,
  session nvarchar(128) NULL,
  rexp nvarchar(200) NULL,
  urls nvarchar(200) NULL,
  highest tinyint NULL,
  template nvarchar(200) NOT NULL,
  css int NULL,
  priority int NOT NULL,
  auth nvarchar(5) NOT NULL
  	CONSTRAINT CK_sys_layout_skin_auth CHECK (auth IN('yes','no','')),
  cache bigint NOT NULL DEFAULT '0',
  CONSTRAINT PK_sys_layout_skin_tmp PRIMARY KEY (id)
)

SET IDENTITY_INSERT sys_layout_skin_tmp ON

INSERT INTO sys_layout_skin_tmp (id, label, session, rexp, urls, template, css, priority, auth, cache)
SELECT id, label, session, rexp, urls, template, css, priority, auth, cache FROM sys_layout_skin;

SET IDENTITY_INSERT sys_layout_skin_tmp OFF

UPDATE sys_layout_skin_tmp SET highest='0';

ALTER TABLE sys_layout_skin_tmp ALTER COLUMN highest tinyint NOT NULL DEFAULT '0';

DROP TABLE sys_layout_skin;

exec sp_rename 'sys_layout_skin_tmp', 'sys_layout_skin';
go

exec sp_rename 'PK_sys_layout_skin_tmp', 'PK_sys_layout_skin';
go


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0" metadata-complete="true">
    <display-name>hello-world-service</display-name>
    <listener>
        <listener-class>com.ctrip.framework.cs.VIServletContextListener</listener-class>
    </listener>
</web-app>


text:
using System;
using System.Web.Mvc;
using System.Web.UI;
using Frapid.Areas;
using Frapid.Areas.Caching;
using Frapid.AssetBundling;
using Frapid.Configuration.Models;
using Frapid.Framework.StaticContent;
using Serilog;

namespace Frapid.Web.Controllers
{
    [Route("assets")]
    public sealed class AssetsController : BaseController
    {
        private bool IsDevelopment()
        {
            var parameter = Parameter.Get();
            return parameter.IsDevelopment ?? false;
        }

        private Bundler GetStyleBundler(Asset asset)
        {
            if (this.IsDevelopment())
            {
                return new DevelopmentStyleBundler(Log.Logger, asset);
            }

            return new ProductionStyleBundler(Log.Logger, asset);
        }

        private Bundler GetScriptBundler(Asset asset)
        {
            if (this.IsDevelopment())
            {
                return new DevelopmentScriptBundler(Log.Logger, asset);
            }

            return new ProductionScriptBundler(Log.Logger, asset);
        }

        [Route("assets/js/{*name}")]
        [FileOutputCache(ProfileName = "StaticFile.xml", Duration = 60 * 60, Location = OutputCacheLocation.Client)]
        public ActionResult Js(string name)
        {
            var asset = AssetDiscovery.FindByName(name);

            if (asset == null)
            {
                return this.HttpNotFound();
            }

            var compressor = this.GetScriptBundler(asset);
            string contents = compressor.Compress();

            this.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(asset.CacheDurationInMinutes));
            return this.Content(contents, "text/javascript");
        }

        [Route("assets/css/{*name}")]
        [FileOutputCache(ProfileName = "StaticFile.xml", Duration = 60 * 60, Location = OutputCacheLocation.Client)]
        public ActionResult Css(string name)
        {
            var asset = AssetDiscovery.FindByName(name);

            var compressor = this.GetStyleBundler(asset);
            string contents = compressor.Compress();

            this.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(asset.CacheDurationInMinutes));
            return this.Content(contents, "text/css");
        }
    }
}


text:
Claymate is an optional helper script that wraps common tasks related specifically to [Gumby Framework](https://github.com/GumbyFramework/Gumby) for ease of use.

### Another CLI tool?!

Everyone and their cat these days seem to be putting out a command line tool to help with the process of building websites. We have yeoman, grunt, uglify, guard, compass, and many more. Claymate's purpose is not to replace these tools or even to accomplish much more beyond them, but is rather meant to simplify their use where particulars of gumby come into play.

For example, we think you'll agree that typing this:

	$ claymate install

... is better than typing this:

	$ bower install gumby && \
	mkdir css && \
	mkdir js && \
	mkdir img && \
	mkdir -p sass/var && \
	mkdir fonts && \
	cp bower_components/gumby/sass/gumby.scss sass/ && \
	cp bower_components/gumby/sass/_settings.scss sass/_settings.scss && \
	cp bower_components/gumby/sass/_fonts.scss sass/_font.scss && \
	cp bower_components/gumby/sass/_custom.scss sass/_custom.scss && \
	cp bower_components/gumby/config.rb . && \
	cp -r bower_componenets/gumby/fonts/icons fonts/ && \
	compass compile && \
	echo '{ "build": { "gumbyPath": "bower_components/gumby", "outPath": "js" } }' > gumby.json

And that *still* leaves manual steps for you to complete afterwards which claymate would do for us.

### So what can I do with it?

Right now claymate allows us to do two things: scaffold a new project and concatenate/minify the javascript. Both are tedious tasks to do by hand. Each task is a "subcommand" of claymate, and each in turn accept their own configuration to customize how they act to your use case.

As time goes on, we will add more subcommands to accomplish tasks we notice are repetitive. Before we get into the nitty gritty of each command, let's take a look at how we can install and configure claymate for our envirnoment.

## Getting Claymate

Before begining you will need [nodejs](http://nodejs.org/) version 0.8.0 or higher. Lower versions of nodejs have not been tested. Installation and update instructions for nodejs vary widely depending on what platform you're using and if you want to manage nodejs versions with something like [nvm](https://github.com/creationix/nvm). As such we leave the task to the reader.

> Note: A bug exists with nodejs v0.11.7 in one of claymate's dependencies (uglify-js). Until such time as that bug is fixed in uglify-js, you will not be able to use the 'build' command in that version of nodejs.

Claymate exists as an [npm](https://npmjs.org/) module, so we can easily use that to install it. We reccomend you install claymate globally to save the trouble of specifying the path to claymate every time you invoke it.

	$ npm install claymate

> Sudo is only required in cases where the shared node_modules directory for your system is owned by root. You'll notice when it throws a whole bunch of gobbledy-gook at you with stuff like ENOACCESS and complaints about permissions. A better approach to solving the problem than sudo'ing everything would be to set your npm prefix to a directory you own in $HOME, then adding that to your $PATH. Or more simply, use [nvm](https://github.com/creationix/nvm).

## How Configuration Works

Configuration for claymate is handled with either command line flags or in a JSON file.

### Flags

Flags are always preceded by `--` and come after the subcommand. Additionally a short option, preceded by `-` is defined for each that allows for less typing when using one-off configuration. For example, the following are equivalent:

	$ claymate build --gumbyPath bower_components/gumby
	$ claymate build -g bower_components/gumby
	$ claymate build -g "bower_components/gumby"

As shown above, many flags take an argument which is just a value for the flag. Most of the time, these will be paths, and are simply strings.

Some flags take more than one value. In this case, we use a comma to separate each value, with no spaces inbetween commas and the values.

	$ claymate build --modules retina,toggleswitch,validation

Still other flags are merely on/off switches. In this case they take no arguments at all. You can also negate them by prepending them with `--no-`.

	$ claymate build --buildSourceMap
	$ claymate build --no-buildSourceMap

> **Note:** You can always invoke the claymate command without any subcommands or flags in order to list the possible flags.

### Gumby.json

To make things easier you can specify a gumby.json file in the folder in which you will be running claymate. It's structure closely mirrors that of the command line options. Here is what the examples for the flags shown above would be converted to:

	{
		"build": {
			"gumbyPath": bower_components/gumby",
			"modules": ["retina", "toggleswitch", "validation"],
			"buildSourceMap": true
		}
	}

Each subcommand has it's own list of key-value pairs corresponding to command line flags. All keys are identically named to the long form of the corresponding option, minus the `--`. Prefixing a switch option with `no-` will have no effect, instead use `false` as its value. Also note that a comma separated list becomes a JSON array.

> **Remember:** Wherever you run claymate from, that directory is where it will look for gumby.json. Uppercasing or relocating the gumby.json file to a different directory will make claymate use the default values.

## Subcommand: Install

It is increasingly common practice to use some sort of front-end dependency manager in the vein of npm to manage a project's components. We favor [bower](http://bower.io/) for this task. However, one of the strengths of the gumby framework is the ability to change a few settings and completely change the look of the framework. Since the process of extracting the customizable components of the framework while using bower to maintain isolation from our app is a little complex, we decided to write a subcommand to handle the process for us.

The end result of running this subcommand is a directory structure like the following:

	├── bower_components/
	│   └── gumby/
	├── css/
	│   └── gumby.css
	├── fonts/
	│   └── icons/
	│       ├── entypo.eot
	│       ├── entypo.ttf
	│       └── entypo.woff
	├── img/
	├── js/
	├── sass/
	│   ├── var/
	│   │   └── _settings.scss
	│   ├── _custom.scss
	│   ├── _fonts.scss
	│   └── gumby.scss
	├── config.rb
	├── gumby.json
	├── index.html
	└── ui.html

> **Important!** You should always run this subcommand from an empty directory, as it will overwrite files if they exist already. Claymate will detect if the folder is non-empty and warn you of this.

### Options

> **Note:** If you wish to install gumby as a bower module without the extra processing, all you have to do is `$ bower install gumby`.

#### edge

`--edge`, `-e`

If you want the latest non-released gumby (develop branch), use this.

> **Defaults:** Off.

#### quiet

`--quiet, -q`

If you do not want to see any output from claymate, pass this option.

> **Default:** Off.

## Subcommand: Build

At some point in your project's lifetime you may wish to optimize your javascript files (minification) and combine them all together into one file (concatenation)  with something like [UglifyJS](https://github.com/mishoo/UglifyJS2) . You will find that the order of concatenation of the gumby scripts matters, and that pointing to all of the involved directories is a little annoying.

This subcommand will do all the work for us. It will concatenate and minify the javascript in the following order:

- `js/libs/gumby.js`
- `js/libs/ui/*.js` (the core modules)
- (any custom module files)
- `js/libs/gumby.init.js`
- (any custom non-module files)

It can also optionally output a sourcemap file.

### Options

#### gumbyPath

`--gumbyPath, -g` `path/to/gumby`

In order to find gumby's javascript files, claymate needs to know where the root of the gumby folder is. For example, if we are in `~/Sites/new-site-project/` and have gumby installed at `~/Sites/new-site-project/public_html/bower_components/gumby`, we can specify that by passing the relative path like so:

	$ claymate build --gumbyPath public_html/bower_components/gumby

> **Default:** The current directory will be used (such as if you downloaded a copy of gumby to your project). If you scaffolded your project with `claymate install`, then a `gumby.json` file will have been written for you that points to `bower_componenets/gumby`.

#### outPath

`--outPath, -o` `path/to/output/js`

This allows us to dictate where to output the final minified, concatenated file and its sourcemap. The rules for the path are the same as that for the gumbyPath argument.

> **Default:** The files will be written to the current directory if you do not specify. If you scaffolded your project with `claymate install`, then a `gumby.json` file will have been written for you that points to `js`.

#### modules

`--modules, -m` `list,of,ui,modules`

This is a comma separated list of the names of the core gumby UI modules you wish to be included. Names of modules should be specified without the `.js` ending, and can be written without their `gumby.` or `jquery.` prefixes. For example, to include `js/libs/ui/jquery.validation.js` and `js/libs/ui/retina.js`, one would write the following:

	$ claymate build --modules retina,validation

> **Default:** By default, all modules located in `$gumbyPath/js/libs/ui/` are included.

#### add-ons

`--add-ons, --addons, -a` `path/to/addon/a.js,path/to/addon/b.js`

This allows us to specify additional add-ons written specifically to work with gumby. An example of that is the Parallax module, which is published as a separate bower package. Assuming we install it with bower, one need only do the following:

	$ claymate build --addons bower_components/gumby-parallax/gumby.parallax.js

> **Default:** Empty.

#### files

`--files, -f` `path/to/file/a.js,path/to/file/b.js`

This is a comma separated list of additional javascript files. An example could be the `js/plugins.js` and `js/main.js` or any other javascript specific to your project. Rules for the arguments are the same as for `--addons`.

> **Default:** Empty.

#### buildSourceMap

`--buildSourceMap, -s`

No argument needs to be passed to this flag. Its presence enables the creation of sourcemaps along with the minified, concatenated file. To enable sourcemaps therefore, one writes:

	$ claymate build --buildSourceMap

> **Default:** Don't build a sourcemap.

#### quiet

`--quiet, -q`

Sometimes we need to use an option just once. Passing this flag will supress the helpful hint about the gumby.json file.

> **Default:** Off.

## I'm a developer, and I have an itch to scratch

Whether you have an idea for a subcommand, a bugfix, or just a little feature to add to claymate then please! By all means, fork our repository and give it a go!

In github, fork [our repository](https://github.com/GumbyFramework/Claymate), then clone it locally:

	$ git clone git@github.com:<your-username>/Claymate.git

Once cloned, go into the project directory and add the official respository as a new remote.

	$ cd Claymate
	$ git remote add upstream https://github.com/GumbyFramework/Claymate.git

You can set your copy of claymate as the global installation of claymate by linking, taking care to remove the globally installed claymate if it exists already.

	$ npm -g uninstall claymate
	$ npm link

The repository uses the [Git Flow](http://nvie.com/posts/a-successful-git-branching-model/) method for organizing branches. If you are not used to it, just treat the develop branch like you normally would the master branch of another project. That is, develop is the main integration point, which you should branch off for your work, then pull request to. Never commit on develop or master in your fork, as you will then have the headache of merge conflicts every time you pull from upstream. You can use any name you want for topic branches, as they will not appear in the official repository.

> **Note:** Before spending a lot of time on a large subcommand, please propose the idea in a github issue first. If the subcommand is not a fit for the purpose of claymate, we can discuss it ahead of time and perhaps collaborate on ways to reshape it to fit.

## MIT Open Source License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
namespace routing
{
class TransitInfo final
{
public:
  enum class Type
  {
    Gate,
    Edge,
    Transfer
  };

  struct EdgeSubway
  {
    EdgeSubway() = default;
    explicit EdgeSubway(transit::Edge const & edge)
      : m_lineId(edge.GetLineId())
      , m_stop1Id(edge.GetStop1Id())
      , m_stop2Id(edge.GetStop2Id())
      , m_shapeIds(edge.GetShapeIds())
    {
      ASSERT(!edge.GetTransfer(), ());
    }

    transit::LineId m_lineId = transit::kInvalidLineId;
    transit::StopId m_stop1Id = transit::kInvalidStopId;
    transit::StopId m_stop2Id = transit::kInvalidStopId;
    std::vector<transit::ShapeId> m_shapeIds;
  };

  struct EdgePT
  {
    EdgePT() = default;
    explicit EdgePT(::transit::experimental::Edge const & edge)
      : m_lineId(edge.GetLineId())
      , m_stop1Id(edge.GetStop1Id())
      , m_stop2Id(edge.GetStop2Id())
      , m_shapeLink(edge.GetShapeLink())
    {
      ASSERT(!edge.IsTransfer(), ());
    }

    ::transit::TransitId m_lineId = ::transit::kInvalidTransitId;
    ::transit::TransitId m_stop1Id = ::transit::kInvalidTransitId;
    ::transit::TransitId m_stop2Id = ::transit::kInvalidTransitId;
    ::transit::ShapeLink m_shapeLink;
  };

  struct GateSubway
  {
    GateSubway() = default;
    explicit GateSubway(transit::Gate const & gate) : m_featureId(gate.GetFeatureId()) {}

    transit::FeatureId m_featureId = transit::kInvalidFeatureId;
  };

  struct GatePT
  {
    GatePT() = default;
    explicit GatePT(::transit::experimental::Gate const & gate) : m_featureId(gate.GetFeatureId())
    {
    }

    ::transit::experimental::FeatureId m_featureId = ::transit::experimental::kInvalidFeatureId;
  };

  struct TransferSubway
  {
    TransferSubway() = default;
    explicit TransferSubway(transit::Edge const & edge)
      : m_stop1Id(edge.GetStop1Id()), m_stop2Id(edge.GetStop2Id())
    {
      ASSERT(edge.GetTransfer(), ());
    }

    transit::StopId m_stop1Id = transit::kInvalidStopId;
    transit::StopId m_stop2Id = transit::kInvalidStopId;
  };

  struct TransferPT
  {
    TransferPT() = default;
    explicit TransferPT(::transit::experimental::Edge const & edge)
      : m_stop1Id(edge.GetStop1Id()), m_stop2Id(edge.GetStop2Id())
    {
      ASSERT(edge.IsTransfer(), ());
    }

    ::transit::TransitId m_stop1Id = ::transit::kInvalidTransitId;
    ::transit::TransitId m_stop2Id = ::transit::kInvalidTransitId;
  };

  explicit TransitInfo(transit::Gate const & gate)
    : m_transitVersion(::transit::TransitVersion::OnlySubway)
    , m_type(Type::Gate)
    , m_gateSubway(gate)
  {
  }

  explicit TransitInfo(::transit::experimental::Gate const & gate)
    : m_transitVersion(::transit::TransitVersion::AllPublicTransport)
    , m_type(Type::Gate)
    , m_gatePT(gate)
  {
  }

  explicit TransitInfo(transit::Edge const & edge)
    : m_transitVersion(::transit::TransitVersion::OnlySubway)
    , m_type(edge.GetTransfer() ? Type::Transfer : Type::Edge)
    , m_edgeSubway(edge.GetTransfer() ? EdgeSubway() : EdgeSubway(edge))
    , m_transferSubway(edge.GetTransfer() ? TransferSubway(edge) : TransferSubway())
  {
  }

  explicit TransitInfo(::transit::experimental::Edge const & edge)
    : m_transitVersion(::transit::TransitVersion::AllPublicTransport)
    , m_type(edge.IsTransfer() ? Type::Transfer : Type::Edge)
    , m_edgePT(edge.IsTransfer() ? EdgePT() : EdgePT(edge))
    , m_transferPT(edge.IsTransfer() ? TransferPT(edge) : TransferPT())
  {
  }

  Type GetType() const { return m_type; }

  ::transit::TransitVersion GetVersion() const { return m_transitVersion; }

  EdgeSubway const & GetEdgeSubway() const
  {
    ASSERT_EQUAL(m_type, Type::Edge, ());
    CHECK_EQUAL(m_transitVersion, ::transit::TransitVersion::OnlySubway, ());
    return m_edgeSubway;
  }

  GateSubway const & GetGateSubway() const
  {
    ASSERT_EQUAL(m_type, Type::Gate, ());
    return m_gateSubway;
  }

  TransferSubway const & GetTransferSubway() const
  {
    ASSERT_EQUAL(m_type, Type::Transfer, ());
    return m_transferSubway;
  }

  EdgePT const & GetEdgePT() const
  {
    ASSERT_EQUAL(m_type, Type::Edge, ());
    CHECK_EQUAL(m_transitVersion, ::transit::TransitVersion::AllPublicTransport, ());
    return m_edgePT;
  }

  GatePT const & GetGatePT() const
  {
    CHECK_EQUAL(m_type, Type::Gate, ());
    CHECK_EQUAL(m_transitVersion, ::transit::TransitVersion::AllPublicTransport, ());
    return m_gatePT;
  }

  TransferPT const & GetTransferPT() const
  {
    ASSERT_EQUAL(m_type, Type::Transfer, ());
    CHECK_EQUAL(m_transitVersion, ::transit::TransitVersion::AllPublicTransport, ());
    return m_transferPT;
  }

private:
  ::transit::TransitVersion const m_transitVersion;
  Type const m_type;
  // Valid for m_type == Type::Edge only.
  EdgeSubway const m_edgeSubway;
  // Valid for m_type == Type::Gate only.
  GateSubway const m_gateSubway;
  // Valid for m_type == Type::Transfer only.
  TransferSubway const m_transferSubway;

  EdgePT const m_edgePT;
  GatePT const m_gatePT;
  TransferPT const m_transferPT;
};

class TransitInfoWrapper final
{
public:
  explicit TransitInfoWrapper(std::unique_ptr<TransitInfo> ptr) : m_ptr(move(ptr)) {}
  explicit TransitInfoWrapper(TransitInfoWrapper && rhs) { swap(m_ptr, rhs.m_ptr); }
  explicit TransitInfoWrapper(TransitInfoWrapper const & rhs)
  {
    if (rhs.m_ptr)
      m_ptr = std::make_unique<TransitInfo>(*rhs.m_ptr);
  }

  TransitInfoWrapper & operator=(TransitInfoWrapper && rhs)
  {
    swap(m_ptr, rhs.m_ptr);
    return *this;
  }

  TransitInfoWrapper & operator=(TransitInfoWrapper const & rhs)
  {
    if (this == &rhs)
      return *this;

    m_ptr.reset();
    if (rhs.m_ptr)
      m_ptr = std::make_unique<TransitInfo>(*rhs.m_ptr);
    return *this;
  }

  bool HasTransitInfo() const { return m_ptr != nullptr; }

  TransitInfo const & Get() const
  {
    ASSERT(HasTransitInfo(), ());
    return *m_ptr;
  }

  void Set(std::unique_ptr<TransitInfo> ptr) { m_ptr = move(ptr); }

private:
  std::unique_ptr<TransitInfo> m_ptr;
};

inline std::string DebugPrint(TransitInfo::Type type)
{
  switch (type)
  {
  case TransitInfo::Type::Gate: return "Gate";
  case TransitInfo::Type::Edge: return "Edge";
  case TransitInfo::Type::Transfer: return "Transfer";
  }
  UNREACHABLE();
}
}  // namespace routing