/***********************
QuickChange CORE SCRIPT

Author: Emir Plicanic
Version: 1.0
Created: 11/01/2009
Webstie: www.bewebmaster.com
		 www.emirplicanic.com
***********************/

$(function() { 	
	//Load and execute jquery DIALOG UI only if not already in use
	if(typeof dialog == 'undefined'){
		var load_QC_ui=document.createElement("script");
		load_QC_ui.setAttribute("type", "text/javascript");
		load_QC_ui.setAttribute("src", "http://"+window.location.hostname+"/qchange/js/jquery.ui.dialog.js");
		document.getElementsByTagName("head")[0].appendChild(load_QC_ui);
		$.getScript("http://"+window.location.hostname+"/qchange/js/jquery.ui.dialog.js");
		
	}
	
	//Load and execute jquery FORM plugin if not already loaded
	if(typeof ajaxSubmit == 'undefined'){
		var load_QC_ui=document.createElement("script");
		  load_QC_ui.setAttribute("type", "text/javascript");
		  load_QC_ui.setAttribute("src", "http://"+window.location.hostname+"/qchange/js/jquery.form.js");
		  document.getElementsByTagName("head")[0].appendChild(load_QC_ui);
		  $.getScript("http://"+window.location.hostname+"/qchange/js/jquery.form.js");
		
	}
	//Load and execute jquery jGROWEL plugin if not already loaded
	if(typeof jGrowl == 'undefined'){
		  var load_QC_ui=document.createElement("script");
		  load_QC_ui.setAttribute("type", "text/javascript");
		  load_QC_ui.setAttribute("src", "http://"+window.location.hostname+"/qchange/js/jquery.jgrowel.js");
		  document.getElementsByTagName("head")[0].appendChild(load_QC_ui);
		  $.getScript("http://"+window.location.hostname+"/qchange/js/jquery.jgrowel.js");	
	}

  
	//see if user is logged in													 
	$.ajax({
	  url: "http://"+window.location.hostname+"/qchange/ajax.php",
	  data: "action=getlogin",
	  async: false,
	  success: function(msg){
						  if(msg == 'loggedin'){
							load_QC_styles();
							load_QC_editor();
						  }else{
							$("body .tiny_QC_mce").each(function(){
								var tmceid = $(this).attr('id');
								tinyMCE.execCommand('mceRemoveControl', false, tmceid);
							});
							$("#login_QC_dialog form").remove();
							$(".qc-edit").unbind('click');
							//$(".qc-edit").removeClass('ui-state-highlight');
						  }
					  }
	});
	

	jQuery(document).bind('keydown', 'Alt+Ctrl+e',function (evt){
		  login_to_QC();
		  return false; 
	});

});

function login_to_QC(){
			if($("head #load_QC_jqUI_css").length < 1){  
			  var qccss=document.createElement("link");
			  qccss.setAttribute("rel", "stylesheet");
			  qccss.setAttribute("type", "text/css");
			  qccss.setAttribute("href", "http://"+window.location.hostname+"/qchange/css/jquery-ui-1.7.2.custom.css");
			  qccss.setAttribute("id", "load_QC_jqUI_css");
			  document.getElementsByTagName("head")[0].appendChild(qccss);
		   }
		  
		  login_QC();	
}

//function login form
function login_QC(){
	//close and remove any opened login dialogs
	try{
	$("#login_QC_dialog form").remove();
	$(".ui-dialog").dialog('destroy');
	$("#login_QC_dialog").remove();
	}catch(e){}
    //see if user is logged in													 
	var msg = $.ajax({
	  url: "http://"+window.location.hostname+"/qchange/ajax.php",
	  data: "action=getlogin",
	  async: false
	}).responseText;
	 //set default dialog title 
	 var dialogtitle = "Login";
	 
	 //add dialog to the DOM
	 $("body").append('<div id="login_QC_dialog"></div>');
	 
	 //if not logged in display login form otherwise show logout dialog
	 if(msg=="loggedin"){
		 $("#login_QC_dialog").append('<style>#loginform label{display:block;font-size:12px;}#loginform input{display:block;}</style><form action="http://'+window.location.hostname+'/qchange/ajax.php" method="post" enctype="application/x-www-form-urlencoded" name="loginform" id="loginform"><div><p>Press "OK" to log out.</p><input type="hidden" name="action" id="action" value="logout" /></div></form>'); 
		 dialogtitle = "Logout";
	 }else{
		 $("#login_QC_dialog").append('<style>#loginform label{display:block;font-size:12px;}#loginform input{display:block;}</style><form action="http://'+window.location.hostname+'/qchange/ajax.php" method="post" enctype="application/x-www-form-urlencoded" name="loginform" id="loginform"><div><label for="u">Username</label><input type="text" name="u" id="u" class="ui-widget-content" /></div><div><label for="p">Password</label><input type="password" name="p" id="p" class="ui-widget-content" /><input type="hidden" name="action" id="action" value="login" /></div></form>'); 
	 }
	 
	 //create UI dialog
	 $("#login_QC_dialog").dialog({
			bgiframe: true,
			width: 300,
			height:  'auto',
			modal: true,
			title: dialogtitle,
			close: function(){					
				$("#login_QC_dialog form").remove();
				$(this).dialog('destroy');
	
			},
			buttons: {
			'OK' : function() {
				//Login
				 //check if logged in
				 var u = $("#loginform #u").val();
				 var p = $("#loginform #p").val();
				 if(dialogtitle=="Logout"){
					var dialogaction = 'logout';	 
				 }else{
					var dialogaction = 'login';
				 }
				 msg = $.ajax({
					  url: "http://"+window.location.hostname+"/qchange/ajax.php",
					  data: "action="+dialogaction+"&u="+u+"&p="+p, 
					  success: function(msg){
						  if(msg == 'loggedin'){
							load_QC_styles();
							load_QC_editor();
							
						  }else if(msg == "error"){
							 $("#login_QC_dialog form").html('<p>There was an error! Check username and password and <br /> <a href="javascript:login_QC();">CLICK HERE TO TRY AGAIN</a>.</p>'); 
							  
						  }else{
							$("body .tiny_QC_mce").each(function(){
								var tmceid = $(this).attr('id');
								tinyMCE.execCommand('mceRemoveControl', false, tmceid);
							});
							
							//LOGGING OUT. DO Clean up.
							$("head #jiffcecss").remove();
							//unload and close all open dialogs
							$("#login_QC_dialog form, #load_QC_jqUI_css, #editor_QC_dialog, #load_QC_css").remove();
							$("#login_QC_dialog").dialog('destroy');
							$("#editor_QC_dialog").dialog('destroy');
							$(".qc-edit").unbind('click');
							//$(".qc-edit").removeClass('ui-state-highlight');
						  }
					  }
				 }).responseText;
				
			},
			Cancel: function() {
				$("#login_QC_dialog form").remove();
				$(this).dialog('destroy');
				
			}
		}
	
	 });
	 
}

function load_QC_styles(){
	//check if CSS and JS is loaded
	if($("head #load_QC_jqUI_css").length < 1){  
	  var qccss=document.createElement("link");
	  qccss.setAttribute("rel", "stylesheet");
	  qccss.setAttribute("type", "text/css");
	  qccss.setAttribute("href", "http://"+window.location.hostname+"/qchange/css/jquery-ui-1.7.2.custom.css");
	  qccss.setAttribute("id", "load_QC_jqUI_css");
	  document.getElementsByTagName("head")[0].appendChild(qccss);
	}
	if($("head #load_QC_css").length < 1){  
	  var qcuicss=document.createElement("link");
	  qcuicss.setAttribute("rel", "stylesheet");
	  qcuicss.setAttribute("type", "text/css");
	  qcuicss.setAttribute("href", "http://"+window.location.hostname+"/qchange/css/qc_css.css");
	  qcuicss.setAttribute("id", "load_QC_css");
	  document.getElementsByTagName("head")[0].appendChild(qcuicss);
	}
}

function load_QC_editor(){
	//close opened login dialogs
	$("#login_QC_dialog form").remove();
	$("#login_QC_dialog").dialog('destroy');
	//get filename
	var filename = return_QC_document();
	
	$(".qc-edit").unbind('click').click(function(){
											 
			//add dialog to the DOM
			$("body").append('<div id="editor_QC_dialog"></div>');
			//get current div
			//var editsection = $(this).attr("id");
			//get index
			var editsection = $("body .qc-edit").index(this);

			//load selected content
			var content = $(this).html();
			
			//check if div
			var thiselement = this.tagName;
			var casechanged=thiselement.toLowerCase();
			if(casechanged !="div"){
				$("#editor_QC_dialog").append('<form id="qc_form" name="qc_form" action="http://'+window.location.hostname+'/qchange/ajax.php" method="post"><textarea id="elm1" name="elm1" rows="5" cols="50" style="width: 700px">'+content+'</textarea><input type="hidden" name="action" id="action" value="save"><input type="hidden" name="id" id="id" value="'+editsection+'"><input type="hidden" name="file" id="file" value="'+filename+'"></form>');
			}else{
			//append textarea w/ content to the dialog
				$("#editor_QC_dialog").append('<form id="qc_form" name="qc_form" action="http://'+window.location.hostname+'/qchange/ajax.php" method="post"><textarea id="elm1" name="elm1" rows="15" cols="50" style="width: 700px; height:500px;" class="tiny_QC_mce">'+content+'</textarea><input type="hidden" name="action" id="action" value="save"><input type="hidden" name="id" id="id" value="'+editsection+'"><input type="hidden" name="file" id="file" value="'+filename+'"></form>');
			}
			//show dialog
			$("#editor_QC_dialog").dialog({
				bgiframe: true,
				width: 730,
				height:  'auto',
				modal: true,
				title: "Editor",
				close: function(){					
					$("body .tiny_QC_mce").each(function(){
						var tmceid = $(this).attr('id');
						tinyMCE.execCommand('mceRemoveControl', false, tmceid);
					});
					$("#editor_QC_dialog form").remove();
					$(this).dialog('destroy');
				},
				buttons: {
				'Save': function() {
					//check if tinymce or textarea
					var updatedHTML = '';
					if($(".tiny_QC_mce").length > 0){
					    updatedHTML = $('#elm1').html();
					}else{
						updatedHTML = $('#elm1').val();	
					}
					$('#elm1').val(updatedHTML);
					//submit content
					submit_QC_form();
					$(".qc-edit:eq("+editsection+")").html(updatedHTML);		
					//close dialog
					$("body .tiny_QC_mce").each(function(){
						var tmceid = $(this).attr('id');
						tinyMCE.execCommand('mceRemoveControl', false, tmceid);
					});
					$("#editor_QC_dialog form").remove();
					$(this).dialog('destroy');
				},
				Cancel: function() {
					$("body .tiny_QC_mce").each(function(){
						var tmceid = $(this).attr('id');
						tinyMCE.execCommand('mceRemoveControl', false, tmceid);
					});
					$("#editor_QC_dialog form").remove();
					$(this).dialog('destroy');
				}
			}

			});
			
			
			//get tinymcy script and execute it			   
			$.getScript("http://"+window.location.hostname+"/qchange/tiny_mce/jquery.tinymce.js", function(){
			  //get styles
			  var styles = $.ajax({
			  url: "http://"+window.location.hostname+"/qchange/ajax.php",
			  data: "action=getstyles",
			  async: false
			}).responseText;
			  
			  
			  $('textarea.tiny_QC_mce').tinymce({
					// Location of TinyMCE script
					script_url : 'http://'+window.location.hostname+'/qchange/tiny_mce/tiny_mce.js',
					forced_root_block:false,
					// General options
					theme : "advanced",
					skin : "o2k7",
					plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
			
					// Theme options
					theme_advanced_buttons1 : "cleanup,|,bold,italic,underline,separator,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,styleselect,formatselect,fontsizeselect,|,link,unlink,image,code",
					theme_advanced_buttons2 : "",
					theme_advanced_buttons3 : "",
					theme_advanced_buttons4 : "",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : true,
			
					// Example content CSS (should be your site CSS)
					content_css : 'http://'+window.location.hostname+'/'+styles
				});
			});//end tinymce
	return false;											 
	});//end click event
}

function submit_QC_form(){ 
		var options = { 
        success: show_QC_response  // post-submit callback 
         }; 							 
		// submit the form 
		$('#qc_form').ajaxSubmit(options); 
		// return false to prevent normal browser submit and page navigation 
		return false; 
	//});
}
function show_QC_response(responseText, statusText)  {
	if(responseText != 'Saved'){
		$.jGrowl("Error! Please try again.");
	 }else{
		$.jGrowl("Saved");	 
	 }
}
function return_QC_document() {
		//set default file name to empty
		var defaultfilename = "";
		//get current URL
		var file_name = document.location.href;
		//remove domain name part
        var end = (file_name.indexOf("?") == -1) ? file_name.length : file_name.indexOf("?");
        var file = file_name.substring(file_name.indexOf("/", 7)+1, end);
		
		//remove any parameters	
		var cleanfile = file.replace(/#/g, '');
		var noparams = cleanfile.split("?");
		var filewithpath = noparams[0];
		
		//see if folder or file
		if(filewithpath == ""){
			if(filewithpath.lastIndexOf("/", 0) == "-1"){
				//if folder get default filename
				var defaultfilename = 	$.ajax({
							  url: "http://"+window.location.hostname+"/qchange/ajax.php",
							  data: "action=getfilename",
							  async: false
							}).responseText;
			}
		}
		
	    return filewithpath+defaultfilename;	
	
		
}

//purely for theme-switching demo... ignore this unless you're using a theme switcher
		//quick function for tooltip color match
		function fixToolTipColor(){
			//grab the bg color from the tooltip content - set top border of pointer to same
			$('.ui-tooltip-pointer-down-inner').each(function(){
				var bWidth = $('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
				var bColor = $(this).parents('.ui-slider-tooltip').css('backgroundColor')
				$(this).css('border-top', bWidth+' solid '+bColor);
			});	
		}





/*******************************



JQUERY Plugins:
js-hotkeys : For handeling Alt+Shift+E shortcut
jQuery Form Plugin: For handeling of form submissions
jgrowel : For feedback handeling


If you are already using any of these plugins in your site and you are worried about file size of this document, you should be able to delete them from this file.



********************************/
	


///JS-HOTKEYS Plugin
;(function(jQuery){jQuery.fn.__bind__=jQuery.fn.bind;jQuery.fn.__unbind__=jQuery.fn.unbind;jQuery.fn.__find__=jQuery.fn.find;var hotkeys={version:'0.7.9',override:/keypress|keydown|keyup/g,triggersMap:{},specialKeys:{27:'esc',9:'tab',32:'space',13:'return',8:'backspace',145:'scroll',20:'capslock',144:'numlock',19:'pause',45:'insert',36:'home',46:'del',35:'end',33:'pageup',34:'pagedown',37:'left',38:'up',39:'right',40:'down',109:'-',112:'f1',113:'f2',114:'f3',115:'f4',116:'f5',117:'f6',118:'f7',119:'f8',120:'f9',121:'f10',122:'f11',123:'f12',191:'/'},shiftNums:{"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"},newTrigger:function(type,combi,callback){var result={};result[type]={};result[type][combi]={cb:callback,disableInInput:false};return result;}};hotkeys.specialKeys=jQuery.extend(hotkeys.specialKeys,{96:'0',97:'1',98:'2',99:'3',100:'4',101:'5',102:'6',103:'7',104:'8',105:'9',106:'*',107:'+',109:'-',110:'.',111:'/'});jQuery.fn.find=function(selector){this.query=selector;return jQuery.fn.__find__.apply(this,arguments);};jQuery.fn.unbind=function(type,combi,fn){if(jQuery.isFunction(combi)){fn=combi;combi=null;}
if(combi&&typeof combi==='string'){var selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();var hkTypes=type.split(' ');for(var x=0;x<hkTypes.length;x++){delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi];}}
return this.__unbind__(type,fn);};jQuery.fn.bind=function(type,data,fn){var handle=type.match(hotkeys.override);if(jQuery.isFunction(data)||!handle){return this.__bind__(type,data,fn);}
else{var result=null,pass2jq=jQuery.trim(type.replace(hotkeys.override,''));if(pass2jq){result=this.__bind__(pass2jq,data,fn);}
if(typeof data==="string"){data={'combi':data};}
if(data.combi){for(var x=0;x<handle.length;x++){var eventType=handle[x];var combi=data.combi.toLowerCase(),trigger=hotkeys.newTrigger(eventType,combi,fn),selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();trigger[eventType][combi].disableInInput=data.disableInInput;if(!hotkeys.triggersMap[selectorId]){hotkeys.triggersMap[selectorId]=trigger;}
else if(!hotkeys.triggersMap[selectorId][eventType]){hotkeys.triggersMap[selectorId][eventType]=trigger[eventType];}
var mapPoint=hotkeys.triggersMap[selectorId][eventType][combi];if(!mapPoint){hotkeys.triggersMap[selectorId][eventType][combi]=[trigger[eventType][combi]];}
else if(mapPoint.constructor!==Array){hotkeys.triggersMap[selectorId][eventType][combi]=[mapPoint];}
else{hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length]=trigger[eventType][combi];}
this.each(function(){var jqElem=jQuery(this);if(jqElem.attr('hkId')&&jqElem.attr('hkId')!==selectorId){selectorId=jqElem.attr('hkId')+";"+selectorId;}
jqElem.attr('hkId',selectorId);});result=this.__bind__(handle.join(' '),data,hotkeys.handler)}}
return result;}};hotkeys.findElement=function(elem){if(!jQuery(elem).attr('hkId')){if(jQuery.browser.opera||jQuery.browser.safari){while(!jQuery(elem).attr('hkId')&&elem.parentNode){elem=elem.parentNode;}}}
return elem;};hotkeys.handler=function(event){var target=hotkeys.findElement(event.currentTarget),jTarget=jQuery(target),ids=jTarget.attr('hkId');if(ids){ids=ids.split(';');var code=event.which,type=event.type,special=hotkeys.specialKeys[code],character=!special&&String.fromCharCode(code).toLowerCase(),shift=event.shiftKey,ctrl=event.ctrlKey,alt=event.altKey||event.originalEvent.altKey,mapPoint=null;for(var x=0;x<ids.length;x++){if(hotkeys.triggersMap[ids[x]][type]){mapPoint=hotkeys.triggersMap[ids[x]][type];break;}}
if(mapPoint){var trigger;if(!shift&&!ctrl&&!alt){trigger=mapPoint[special]||(character&&mapPoint[character]);}
else{var modif='';if(alt)modif+='alt+';if(ctrl)modif+='ctrl+';if(shift)modif+='shift+';trigger=mapPoint[modif+special];if(!trigger){if(character){trigger=mapPoint[modif+character]||mapPoint[modif+hotkeys.shiftNums[character]]||(modif==='shift+'&&mapPoint[hotkeys.shiftNums[character]]);}}}
if(trigger){var result=false;for(var x=0;x<trigger.length;x++){if(trigger[x].disableInInput){var elem=jQuery(event.target);if(jTarget.is("input")||jTarget.is("textarea")||jTarget.is("select")||elem.is("input")||elem.is("textarea")||elem.is("select")){return true;}}
result=result||trigger[x].cb.apply(this,[event]);}
return result;}}}};window.hotkeys=hotkeys;return jQuery;})(jQuery);