$(document).ready(function(){

	// Get the source directory of this script
	root = $('script[src$=jq132.min.js]').attr('src').replace('dyn/jq132.min.js', '');
	
	// For ajax we want to only have a www in the root if there is one
	if(!location.href.match('www')){ root = root.replace('www.', ''); }
	
	// Lets see if there's some code to work with
	if($('#originalcode').length){
		initLiveSwap();
		initOptions();
		initCopy();
		initThread();
		initEmbed();
		$('noscript').hide();
	}
	
	initAbout();	
});

// Submit the main form
function submitmain(){
	if($('#codeform').length){
		$('#codeform')[0].submit();
	}else{
		$('#codeform').submit();
	}
}

// Swap styles live!
function initLiveSwap(){
	$('#livelanguage').change(function(){
		$('#languageentry').val($(this).val());
		$('#originalcode').attr('class', $('option:selected', this).html());
		highLight();
	});
}

// Highlight item
function highLight(){
	var thisItem = $('#originalcode');
	var code = thisItem.html();
	code = code.replace(/&/ig, escape('&'));
	var language = thisItem.attr('class');
	var changedlines = $('#changedlines').val();
	$('#viewas').hide();
	$('#loadinghighlight span').html(language);
	$('#loadinghighlight').show();
	$.ajax({
		type: "POST",
		url: root+'scripts/highlight.php',
		data: 'action=livehighlight&language='+language+'&code='+code+'&changedlines='+changedlines,
		dataType: "html",
		success: function(msg){
			if (msg){
				msg = msg.replace(/&amp;amp;/ig, '&amp;');
				
				// Remove the old highlighting
				$('pre:not(#originalcode)').remove();
				
				//Insert new highlighting
				thisItem.after(msg);
				
				if(language == '-'){
					newLink = $('#rawlink').val();
				}else{
					newLink = $('#rawlink').val() + '/' + language;
				}
				$('#directlink').html(newLink);
				$('#directlink').attr('href', newLink);
				
				$('#loadinghighlight').hide();
				$('#viewas').show();
				
			}else{
				displayError('Unable to highlight this code!');
			}
		}
	});
}

// Initialise the options form
function initOptions(){

	// Show the options
	$('#viewas').show();
	$('#optionsform').show();
	
	if($('#request').val() == 'edit'){
		retrieveForm($('#livelanguage').val(), $('#liveid').val(), 1);
	}

	// Editing the currently visible code
	$('#editcode').click(function(){
		retrieveForm($('#livelanguage').val(), $('#liveid').val(), 1);
	});

	// Making a form to make a new entry
	$('#newcode').click(function(){
		retrieveForm(0, 0, 0);
	});
	
}

// Get the form
function retrieveForm(language_id, parent_id, update){
	$.ajax({
		type: "POST",
		url: root+'scripts/form.php',
		data: 'action=editform&language_id=' + language_id + '&parent_id=' + parent_id,
		dataType: "html",
		success: function(msg){
			if (msg && msg != 'error'){
				$('#form td').html(msg);
				if(update){
					updateForm();
				}else{
					removeCode();
				}
			}else{
				displayError('Unable to retrieve the form!');
			}
		}
	});
}

// Update the form's contents
function updateForm(){
	$('#codeentry').val(cleanCode($('#originalcode').html()));
}

// Clean this code
function cleanCode(code){
	code = code.replace(/<br>/ig, '\n');
	code = code.replace(/&lt;/ig, '<');
	code = code.replace(/&gt;/ig, '>');
	code = code.replace(/&amp;/ig, '&');
	return code;
}

// Remove the code and related data from view
function removeCode(){
	$('#description').remove();
	$('#message').remove();
	$('#code').remove();
}

// Display an error
function displayError(msg){
	$('#message').remove();
	var message = '<table cellpadding="0" cellspacing="0" border="0" width="100%"  id="message"><tr><td>';
	message = message + '<p class="error">'+msg+'</p></td></tr></table>';
	$('#container td').eq(0).prepend(message);
}

// Initialise copying
function initCopy(){
	$("#copycode, #copyembedded").each(function() {
	
		ZeroClipboard.setMoviePath(root+'dyn/ZeroClipboard.swf');
	
		//Create a new clipboard client
		var clip = new ZeroClipboard.Client();

		//Glue the clipboard client to the last td in each row
		clip.glue($(this));
		clip.setText(cleanCode($('#originalcode').html()));

		//Add a complete event to let the user know the text was copied
		clip.addEventListener('complete', function(client, text) {
			//alert("Copied text to clipboard:\n" + text);
		});
		
	});
}

// Select all embed text on click
function initEmbed(){
	$('#embedcode').focus(function(){
		$(this).select();
	});
}

// Initialise a nice about page
function initAbout(){
	if($('#about').length){
		$('#about p').hide();
		$('#about li').click(function(){
			$('p', this).slideToggle('fast');
		});
	}
}

// Initialise the thread view
function initThread(){
	if($('#showthread').length){
		$('#threadoption').show();
		$('#showthread').click(function(){
			$('#showthread').hide();
			$('#loadingthread').show();
			var liveid = $('#liveid').val();
			$.ajax({
				type: "POST",
				url: root+'scripts/thread.php',
				data: 'paste_id=' + liveid,
				dataType: "html",
				success: function(msg){
					$('#loadingthread').hide();
					if (msg && msg != 'error'){
						$('#description').after(msg);
					}else{
						displayError('Unable to retrieve the tree!');
						$('#gettree').show();
					}
				}
			});
		});
	}
}

// Scramble!
function scramble(t){
	
	var s = new Array('Z','U','2','h','s','X','t',')','O','w','R','l','\'','J','#','I','z','6','7','!','o','K','<','q','g','3','a','8','G','-','A','?','Q',' ','M','T','(','m','9','>','H',':','V','u','S','5','=','p','x','d','Y','P',';','j','F','b','D','L','.','1','N','k','c','/','\\','W','i','n','y','"','C','4','f',',','v','E','B','r','@','e');
	var n = '';
	var x = t.split('');
	
	$.each(x, function(i, c){
		var p = $.inArray(c, s);
		if(p < 0){
			n = n + c;
		}else if(p == 24){
			n = n + '\\';
		}else{
			p = p + 40;
			if(p >= 80){ p = p - 80; }
			n = n + s[p];
		}
	});
	return n;
}

// Copy function
jQuery.copy=function(t){
	if(typeof t=='undefined'){ t=''; }
	d=document;
	if (window.clipboardData){
		window.clipboardData.setData('Text',t);
	}else{
		var f='flashcopier';
		if(!d.getElementById(f)){
			var dd=d.createElement('div');
			dd.id=f;
			d.body.appendChild(dd);
		}
		d.getElementById(f).innerHTML='';
		var i='<embed src="'+root+'dyn/ZeroClipboard.swf" FlashVars="clipboard='+encodeURIComponent(t)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		d.getElementById(f).innerHTML=i;
	}
}

jQuery.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};

jQuery.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};

