
$.fn.yellow_highlightFade = function(type) {
	if(type == 'border'){
		this.css({cursor:'pointer', border:'3px solid #ffffc5'}).mouseover(function() {
			$(this).highlightFade({attr:'borderColor', start:'#ffff44', end:'#ffffc5'});
		}).mouseout(function() {
			$(this).highlightFade({attr:'borderColor', start:'#ffff44', end:'#ffffc5', speed:150});
		});
	} else {
		this.css({cursor:'pointer', background:'#ffffea'})
		.mouseover(function() {
			$(this).highlightFade({start:'#ffff99', end:'#ffffb9'});
		}).mouseout(function() {
			$(this).highlightFade({start:'#ffff99', end:'#ffffea', speed:150});
		});
	}
};

/*
 *  Check all checkboxes in form & highlight row
 *
 *	$("#check_all").click(function() {
 *		$(this).check_all("productIds", "rowchecked");
 *	})
 */
jQuery.fn.check_all = function(group_id, row_class) {
	if(this.length === 0 || !group_id) return(this);
	var self = this;
	var controller = jQuery(self).is(":checked");
	if(controller) {
		jQuery(self).parents('form').find('input[@id^='+group_id+']').not(":checked").each(function() {
			if(row_class) jQuery(this).parents("tr").toggleClass(row_class);
			jQuery(this).attr("checked", "checked");
		});
	} else {
		jQuery(self).parents('form').find('input[@id^='+group_id+']').filter(":checked").each(function() {
			if(row_class) jQuery(this).parents("tr").toggleClass(row_class);
			jQuery(this).attr("checked", "");
		});
	}
};

/*
	This adds the following new selctors to jQuery:
	:modified		- $("*:modified")	- Find <INPUT>, <TEXTAREA> or <SELECT> elements who's value or checked attribute has changed since the page loaded. (For <INPUT> elements, this only applies where type = text, file, hidden or password)
	:option			- $("*:option")		- Find multiple/choice form items: RADIO, CHECKBOX and OPTION elements.
	:option-def		- $("*:option-def") - Find <OPTION>, RADIO and CHECKBOX elements that were selected/checked originally, before changes were made.
	:option-sel		- $("*:option-sel") - Find <OPTION>, RADIO and CHECKBOX elements that are currently selected/checked.
	:option-mod		- $("*:option-mod") - Find <OPTION>, RADIO and CHECKBOX elements un/selected or un/checked since page loaded. Same as :modified but is for <OPTION>, radio and checkbox elements only.
	:text			- $("*:text")		- Equivalent to $("INPUT[@type='text'], TEXTAREA")
	:textarea		- $("*:textarea")	- Equivalent to $("TEXTAREA"). Only included for continuity with the INPUT selectors. Not particularly useful!
	:select			- $("*:select")		- Equivalent to $("SELECT").   Only included for continuity with the INPUT selectors. Not particularly useful!
	:multiple		- $("*:multiple")	- Equivalent to $("SELECT[@multiple]"). Only included for continuity with the INPUT selectors.
	:selected		- $("*:selected")	- Find <SELECT> elements with 1 or more selections, and all <OPTION> elements that are selected.
*/
jQuery.extend(jQuery.expr[":"],{text:"!m[3] ? a.type=='text' || a.nodeName=='TEXTAREA' : ( jQuery(a).text().toLowerCase()==m[3].toLowerCase() || (a.value && a.value.toLowerCase()==m[3].toLowerCase()) )",modified:"(a.nodeName=='INPUT' && (a.type=='checkbox' || a.type=='radio') && a.defaultChecked != a.checked) || (a.nodeName=='INPUT' && a.defaultValue != a.value && {'text':true,'hidden':true,'file':true,'password':true}[a.type]) || (a.nodeName=='TEXTAREA' && a.defaultValue != a.value) || (a.nodeName=='SELECT' &&  jQuery(a).is('['OPTION:option-mod']') )",unchecked:"a.nodeName=='INPUT' && !a.checked",selected:"(a.nodeName=='SELECT' && jQuery('OPTION[@selected]',a).is()) || (a.nodeName=='OPTION' && a.selected)","option-sel":"(a.nodeName=='OPTION' && a.selected) || (a.nodeName=='INPUT' && a.checked && (a.type=='checkbox' || a.type=='radio'))","option-def":"(a.nodeName=='OPTION' && a.defaultSelected) || (a.nodeName=='INPUT' && (a.type=='checkbox' || a.type=='radio') && a.defaultChecked)","option-mod":"(a.nodeName=='OPTION' && a.defaultSelected != a.selected) || (a.nodeName=='INPUT' && (a.type=='checkbox' || a.type=='radio') && a.defaultChecked != a.checked)",textarea:"a.nodeName=='TEXTAREA'",select:"a.nodeName=='SELECT'",multiple:"a.nodeName=='SELECT' && a.multiple",option:"(a.nodeName=='OPTION') || ( a.nodeName=='INPUT' && (a.type=='checkbox' || a.type=='radio') )",nodename:"(new RegExp(m[3])).test(a.nodeName)"});

/* 
 * Jquery Dimensions Plugin
 * Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com)
 * Version: 1.2
 */
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);

/* 
 * jQuery history plugin
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 */
jQuery.extend({historyCurrentHash:undefined,historyCallback:undefined,historyInit:function(callback){jQuery.historyCallback=callback;var current_hash=location.hash;jQuery.historyCurrentHash=current_hash;if(jQuery.browser.msie){if(jQuery.historyCurrentHash==''){jQuery.historyCurrentHash='#';}
$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=current_hash;}else if($.browser.safari){jQuery.historyBackStack=[];jQuery.historyBackStack.length=history.length;jQuery.historyForwardStack=[];jQuery.isFirst=true;}
jQuery.historyCallback(current_hash.replace(/^#/,''));setInterval(jQuery.historyCheck,100);},historyAddHistory:function(hash){jQuery.historyBackStack.push(hash);jQuery.historyForwardStack.length=0;this.isFirst=true;},historyCheck:function(){if(jQuery.browser.msie){var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentDocument||ihistory.contentWindow.document;var current_hash=iframe.location.hash;if(current_hash!=jQuery.historyCurrentHash){location.hash=current_hash;jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,''));}}else if($.browser.safari){if(!jQuery.dontCheck){var historyDelta=history.length-jQuery.historyBackStack.length;if(historyDelta){jQuery.isFirst=false;if(historyDelta<0){for(var i=0;i<Math.abs(historyDelta);i++)jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());}else{for(var i=0;i<historyDelta;i++)jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());}
var cachedHash=jQuery.historyBackStack[jQuery.historyBackStack.length-1];if(cachedHash!=undefined){jQuery.historyCurrentHash=location.hash;jQuery.historyCallback(cachedHash);}}else if(jQuery.historyBackStack[jQuery.historyBackStack.length-1]==undefined&&!jQuery.isFirst){if(document.URL.indexOf('#')>=0){jQuery.historyCallback(document.URL.split('#')[1]);}else{var current_hash=location.hash;jQuery.historyCallback('');}
jQuery.isFirst=true;}}}else{var current_hash=location.hash;if(current_hash!=jQuery.historyCurrentHash){jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,''));}}},historyLoad:function(hash){var newhash;if(jQuery.browser.safari){newhash=hash;}else{newhash='#'+hash;location.hash=newhash;}
jQuery.historyCurrentHash=newhash;if(jQuery.browser.msie){var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=newhash;jQuery.historyCallback(hash);}else if(jQuery.browser.safari){jQuery.dontCheck=true;this.historyAddHistory(hash);var fn=function(){jQuery.dontCheck=false;};window.setTimeout(fn,200);jQuery.historyCallback(hash);location.hash=newhash;}else{jQuery.historyCallback(hash);}}});

/* 
 * jQuery form plugin
 * Examples at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 * version: 2.03 (01/20/2008)
 */
(function($){$.fn.ajaxSubmit=function(options){if(typeof options=="function"){options={success:options}}options=$.extend({url:this.attr("action")||window.location.toString(),type:this.attr("method")||"GET"},options||{});var veto={};$.event.trigger("form.pre.serialize",[this,options,veto]);if(veto.veto){return this}var a=this.formToArray(options.semantic);if(options.data){for(var n in options.data){a.push({name:n,value:options.data[n]})}}if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){return this}$.event.trigger("form.submit.validate",[a,this,options,veto]);if(veto.veto){return this}var q=$.param(a);if(options.type.toUpperCase()=="GET"){options.url+=(options.url.indexOf("?")>=0?"&":"?")+q;options.data=null}else{options.data=q}var $form=this,callbacks=[];if(options.resetForm){callbacks.push(function(){$form.resetForm()})}if(options.clearForm){callbacks.push(function(){$form.clearForm()})}if(!options.dataType&&options.target){var oldSuccess=options.success||function(){};callbacks.push(function(data){if(this.evalScripts){$(options.target).attr("innerHTML",data).evalScripts().each(oldSuccess,arguments)}else{$(options.target).html(data).each(oldSuccess,arguments)}})}else{if(options.success){callbacks.push(options.success)}}options.success=function(data,status){for(var i=0,max=callbacks.length;i<max;i++){callbacks[i](data,status,$form)}};var files=$("input:file",this).fieldValue();var found=false;for(var j=0;j<files.length;j++){if(files[j]){found=true}}if(options.iframe||found){if($.browser.safari&&options.closeKeepAlive){$.get(options.closeKeepAlive,fileUpload)}else{fileUpload()}}else{$.ajax(options)}$.event.trigger("form.submit.notify",[this,options]);return this;function fileUpload(){var form=$form[0];var opts=$.extend({},$.ajaxSettings,options);var id="jqFormIO"+$.fn.ajaxSubmit.counter++;var $io=$("<iframe id=\""+id+"\" name=\""+id+"\" />");var io=$io[0];var op8=$.browser.opera&&window.opera.version()<9;if($.browser.msie||op8){io.src="javascript:false;document.write(\"\");"}$io.css({position:"absolute",top:"-1000px",left:"-1000px"});var xhr={responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){}};var g=opts.global;if(g&&!$.active++){$.event.trigger("ajaxStart")}if(g){$.event.trigger("ajaxSend",[xhr,opts])}var cbInvoked=0;var timedOut=0;setTimeout(function(){var encAttr=form.encoding?"encoding":"enctype";var t=$form.attr("target"),a=$form.attr("action");$form.attr({target:id,method:"POST",action:opts.url});form[encAttr]="multipart/form-data";if(opts.timeout){setTimeout(function(){timedOut=true;cb()},opts.timeout)}$io.appendTo("body");io.attachEvent?io.attachEvent("onload",cb):io.addEventListener("load",cb,false);form.submit();$form.attr({action:a,target:t})},10);function cb(){if(cbInvoked++){return }io.detachEvent?io.detachEvent("onload",cb):io.removeEventListener("load",cb,false);var ok=true;try{if(timedOut){throw"timeout"}var data,doc;doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;xhr.responseText=doc.body?doc.body.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;if(opts.dataType=="json"||opts.dataType=="script"){var ta=doc.getElementsByTagName("textarea")[0];data=ta?ta.value:xhr.responseText;if(opts.dataType=="json"){eval("data = "+data)}else{$.globalEval(data)}}else{if(opts.dataType=="xml"){data=xhr.responseXML;if(!data&&xhr.responseText!=null){data=toXml(xhr.responseText)}}else{data=xhr.responseText}}}catch(e){ok=false;$.handleError(opts,xhr,"error",e)}if(ok){opts.success(data,"success");if(g){$.event.trigger("ajaxSuccess",[xhr,opts])}}if(g){$.event.trigger("ajaxComplete",[xhr,opts])}if(g&&!--$.active){$.event.trigger("ajaxStop")}if(opts.complete){opts.complete(xhr,ok?"success":"error")}setTimeout(function(){$io.remove();xhr.responseXML=null},100)}function toXml(s,doc){if(window.ActiveXObject){doc=new ActiveXObject("Microsoft.XMLDOM");doc.async="false";doc.loadXML(s)}else{doc=(new DOMParser()).parseFromString(s,"text/xml")}return(doc&&doc.documentElement&&doc.documentElement.tagName!="parsererror")?doc:null}}};$.fn.ajaxSubmit.counter=0;$.fn.ajaxForm=function(options){return this.ajaxFormUnbind().submit(submitHandler).each(function(){this.formPluginId=$.fn.ajaxForm.counter++;$.fn.ajaxForm.optionHash[this.formPluginId]=options;$(":submit,input:image",this).click(clickHandler)})};$.fn.ajaxForm.counter=1;$.fn.ajaxForm.optionHash={};function clickHandler(e){var $form=this.form;$form.clk=this;if(this.type=="image"){if(e.offsetX!=undefined){$form.clk_x=e.offsetX;$form.clk_y=e.offsetY}else{if(typeof $.fn.offset=="function"){var offset=$(this).offset();$form.clk_x=e.pageX-offset.left;$form.clk_y=e.pageY-offset.top}else{$form.clk_x=e.pageX-this.offsetLeft;$form.clk_y=e.pageY-this.offsetTop}}}setTimeout(function(){$form.clk=$form.clk_x=$form.clk_y=null},10)}function submitHandler(){var id=this.formPluginId;var options=$.fn.ajaxForm.optionHash[id];$(this).ajaxSubmit(options);return false}$.fn.ajaxFormUnbind=function(){this.unbind("submit",submitHandler);return this.each(function(){$(":submit,input:image",this).unbind("click",clickHandler)})};$.fn.formToArray=function(semantic){var a=[];if(this.length==0){return a}var form=this[0];var els=semantic?form.getElementsByTagName("*"):form.elements;if(!els){return a}for(var i=0,max=els.length;i<max;i++){var el=els[i];var n=el.name;if(!n){continue}if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el){a.push({name:n+".x",value:form.clk_x},{name:n+".y",value:form.clk_y})}continue}var v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(var j=0,jmax=v.length;j<jmax;j++){a.push({name:n,value:v[j]})}}else{if(v!==null&&typeof v!="undefined"){a.push({name:n,value:v})}}}if(!semantic&&form.clk){var inputs=form.getElementsByTagName("input");for(var i=0,max=inputs.length;i<max;i++){var input=inputs[i];var n=input.name;if(n&&!input.disabled&&input.type=="image"&&form.clk==input){a.push({name:n+".x",value:form.clk_x},{name:n+".y",value:form.clk_y})}}}return a};$.fn.formSerialize=function(semantic){return $.param(this.formToArray(semantic))};$.fn.fieldSerialize=function(successful){var a=[];this.each(function(){var n=this.name;if(!n){return }var v=$.fieldValue(this,successful);if(v&&v.constructor==Array){for(var i=0,max=v.length;i<max;i++){a.push({name:n,value:v[i]})}}else{if(v!==null&&typeof v!="undefined"){a.push({name:this.name,value:v})}}});return $.param(a)};$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=="undefined"||(v.constructor==Array&&!v.length)){continue}v.constructor==Array?$.merge(val,v):val.push(v)}return val};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=="undefined"){successful=true}if(successful&&(!n||el.disabled||t=="reset"||t=="button"||(t=="checkbox"||t=="radio")&&!el.checked||(t=="submit"||t=="image")&&el.form&&el.form.clk!=el||tag=="select"&&el.selectedIndex==-1)){return null}if(tag=="select"){var index=el.selectedIndex;if(index<0){return null}var a=[],ops=el.options;var one=(t=="select-one");var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=$.browser.msie&&!(op.attributes["value"].specified)?op.text:op.value;if(one){return v}a.push(v)}}return a}return el.value};$.fn.clearForm=function(){return this.each(function(){$("input,select,textarea",this).clearFields()})};$.fn.clearFields=$.fn.clearInputs=function(){return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(t=="text"||t=="password"||tag=="textarea"){this.value=""}else{if(t=="checkbox"||t=="radio"){this.checked=false}else{if(tag=="select"){this.selectedIndex=-1}}}})};$.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){this.reset()}})};$.fn.enable=function(b){if(b==undefined){b=true}return this.each(function(){this.disabled=!b})};$.fn.select=function(select){if(select==undefined){select=true}return this.each(function(){var t=this.type;if(t=="checkbox"||t=="radio"){this.checked=select}else{if(this.tagName.toLowerCase()=="option"){var $sel=$(this).parent("select");if(select&&$sel[0]&&$sel[0].type=="select-one"){$sel.find("option").select(false)}this.selected=select}}})}})(jQuery);

/* 
 * Jquery Numeric Plugin 1.0
 * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
 * @example   $(".numeric").numeric();    $(".numeric").numeric(",");    $(".numeric").numeric(null, callback);
 */
$.fn.numeric=function(decimal,callback){decimal=decimal||".";callback=typeof callback=="function"?callback:function(){};$(this).keypress(function(e){var key=e.charCode?e.charCode:e.keyCode?e.keyCode:0;if(key==13&&this.nodeName.toLowerCase()=="input"){return true;}else if(key==13){return false;}
var allow=false;if((e.ctrlKey&&key==97)||(e.ctrlKey&&key==65))return true;if((e.ctrlKey&&key==120)||(e.ctrlKey&&key==88))return true;if((e.ctrlKey&&key==99)||(e.ctrlKey&&key==67))return true;if((e.ctrlKey&&key==122)||(e.ctrlKey&&key==90))return true;if((e.ctrlKey&&key==118)||(e.ctrlKey&&key==86)||(e.shiftKey&&key==45))return true;if(key<48||key>57){if(key==45&&this.value.length==0)return true;if(key==decimal.charCodeAt(0)&&this.value.indexOf(decimal)!=-1){allow=false;}
if(key!=8&&key!=9&&key!=13&&key!=35&&key!=36&&key!=37&&key!=39&&key!=46){allow=false;}else{if(typeof e.charCode!="undefined"){if(e.keyCode==e.which&&e.which!=0){allow=true;}else if(e.keyCode!=0&&e.charCode==0&&e.which==0){allow=true;}}}
if(key==decimal.charCodeAt(0)&&this.value.indexOf(decimal)==-1){allow=true;}}else{allow=true;}
return allow;}).blur(function(){var val=jQuery(this).val();if(val!=""){var re=new RegExp("^\\d+$|\\d*"+decimal+"\\d+");if(!re.exec(val)){callback.apply(this);}}});return this;};

/* 
 *  jQuery Plugin highlightFade (jquery.offput.ca/highlightFade)
 *  (c) 2006 Blair Mitchelmore (offput.ca) blair@offput.ca
 *  version 0.7
 */
$.fn.highlightFade=function(D){var G=(D&&D.constructor==String)?{start:D}:D||{};var F=jQuery.highlightFade.defaults;var C=G["interval"]||F["interval"];var A=G["attr"]||F["attr"];var E={"linear":function(I,J,H,K){return parseInt(I+(K/H)*(J-I))},"sinusoidal":function(I,J,H,K){return parseInt(I+Math.sin(((K/H)*90)*(Math.PI/180))*(J-I))},"exponential":function(I,J,H,K){return parseInt(I+(Math.pow(K/H,2))*(J-I))}};var B=(G["iterator"]&&G["iterator"].constructor==Function)?G["iterator"]:E[G["iterator"]]||E[F["iterator"]]||E["linear"];if(F["iterator"]&&F["iterator"].constructor==Function){B=F["iterator"]}return this.each(function(){if(!this.highlighting){this.highlighting={}}var J=(this.highlighting[A])?this.highlighting[A].end:jQuery.highlightFade.getBaseValue(this,A)||[255,255,255];var K=jQuery.highlightFade.getRGB(G["start"]||G["colour"]||G["color"]||F["start"]||[255,255,128]);var H=jQuery.speed(G["speed"]||F["speed"]);var I=G["final"]||(this.highlighting[A]&&this.highlighting[A].orig)?this.highlighting[A].orig:jQuery.curCSS(this,A);if(G["end"]||F["end"]){I=jQuery.highlightFade.asRGBString(J=jQuery.highlightFade.getRGB(G["end"]||F["end"]))}if(typeof G["final"]!="undefined"){I=G["final"]}if(this.highlighting[A]&&this.highlighting[A].timer){window.clearInterval(this.highlighting[A].timer)}this.highlighting[A]={steps:((H.duration)/C),interval:C,currentStep:0,start:K,end:J,orig:I,attr:A};jQuery.highlightFade(this,A,G["complete"],B)})};jQuery.highlightFade=function(C,A,D,B){C.highlighting[A].timer=window.setInterval(function(){var F=B(C.highlighting[A].start[0],C.highlighting[A].end[0],C.highlighting[A].steps,C.highlighting[A].currentStep);var E=B(C.highlighting[A].start[1],C.highlighting[A].end[1],C.highlighting[A].steps,C.highlighting[A].currentStep);var G=B(C.highlighting[A].start[2],C.highlighting[A].end[2],C.highlighting[A].steps,C.highlighting[A].currentStep);jQuery(C).css(A,jQuery.highlightFade.asRGBString([F,E,G]));if(C.highlighting[A].currentStep++>=C.highlighting[A].steps){jQuery(C).css(A,C.highlighting[A].orig||"");window.clearInterval(C.highlighting[A].timer);C.highlighting[A]=null;if(D&&D.constructor==Function){D.call(C)}}},C.highlighting[A].interval)};jQuery.highlightFade.defaults={start:[255,255,128],interval:50,speed:400,attr:"backgroundColor"};jQuery.highlightFade.getRGB=function(C,B){var A;if(C&&C.constructor==Array&&C.length==3){return C}if(A=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(C)){return[parseInt(A[1]),parseInt(A[2]),parseInt(A[3])]}else{if(A=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(C)){return[parseFloat(A[1])*2.55,parseFloat(A[2])*2.55,parseFloat(A[3])*2.55]}else{if(A=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(C)){return[parseInt("0x"+A[1]),parseInt("0x"+A[2]),parseInt("0x"+A[3])]}else{if(A=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(C)){return[parseInt("0x"+A[1]+A[1]),parseInt("0x"+A[2]+A[2]),parseInt("0x"+A[3]+A[3])]}else{return jQuery.highlightFade.checkColorName(C)||B||null}}}}};jQuery.highlightFade.asRGBString=function(A){return"rgb("+A.join(",")+")"};jQuery.highlightFade.getBaseValue=function(E,B,A){var D,C;A=A||false;C=B=B||jQuery.highlightFade.defaults["attr"];do{D=jQuery(E).css(C||"backgroundColor");if((D!=""&&D!="transparent")||(E.tagName.toLowerCase()=="body")||(!A&&E.highlighting&&E.highlighting[B]&&E.highlighting[B].end)){break}C=false}while(E=E.parentNode);if(!A&&E.highlighting&&E.highlighting[B]&&E.highlighting[B].end){D=E.highlighting[B].end}if(D==undefined||D==""||D=="transparent"){D=[255,255,255]}return jQuery.highlightFade.getRGB(D)};jQuery.highlightFade.checkColorName=function(A){if(!A){return null}switch(A.replace(/^\s*|\s*$/g,"").toLowerCase()){case"gray":return[128,128,128];case"lime":return[0,255,0];case"yellow":return[255,255,0]}};

/*
 * jQuery Example Plugin 1.3.3 - http://github.com/mudge/jquery-example/tree/master
 * Copyright (c) Paul Mucur (http://mucur.name), 2007-2008.
 *
 *  $('input#name').example('Bob Smith');
 *  $('input[@alt]').example(function() {
 *    return $(this).attr('alt');
 *  });
 */
(function($){$.fn.example=function(text,args){var options=$.extend({},$.fn.example.defaults,args);var callback=$.isFunction(text);if(!$.fn.example.bound_class_names[options.class_name]){$(window).unload(function(){$('.'+options.class_name).val('');});$('form').submit(function(){$(this).find('.'+options.class_name).val('');});$.fn.example.bound_class_names[options.class_name]=true;}
return this.each(function(){var $this=$(this);if($.browser.msie&&!$this.attr('defaultValue')&&(callback?$this.val()!='':$this.val()==text)){$this.val('');}
if($this.val()==''){$this.addClass(options.class_name);$this.val(callback?text.call(this):text);}
$this.focus(function(){if($(this).is('.'+options.class_name)){$(this).val('');$(this).removeClass(options.class_name);}});$this.blur(function(){if($(this).val()==''){$(this).addClass(options.class_name);$(this).val(callback?text.call(this):text);}});});};$.fn.example.defaults={class_name:'example'};$.fn.example.bound_class_names=[];})(jQuery);




jQuery.extend({

    createUploadIframe: function(id, uri){
			//create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                } else if(typeof uri== 'string'){
                    io.src = uri;
                }
            } else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);
            return io;
    },
    createUploadForm: function(id, fileElementId){
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
		var form = jQuery.createUploadForm(id, s.fileElementId);
		
		$('#field').appendTo($(form));
		$('#link').appendTo($(form));
		
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ ){
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout){			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow){
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument){
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout"){				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											$(io).remove();
											$(form).remove();	
											
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{
           // var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
            if(form.encoding){
                form.encoding = 'multipart/form-data';				
            }else{				
                form.enctype = 'multipart/form-data';
            }			
            $(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        } 		
        return {abort: function () {}};	
    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" ) jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" ) eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" ) jQuery("<div>").html(data);
        return data;
    }
})

/*
 * jQuery inplace editor plugin (version 1.4.x)
 *
 * Added - @param String  options[tiny_mce]   =   true or false
 *
 * @name  jEditable
 * @type  jQuery
 * @param String  target             POST URL or function name to send edited content
 * @param Hash    options            additional options 
 * @param String  options[name]      POST parameter name of edited content
 * @param String  options[id]        POST parameter name of edited div id
 * @param Hash    options[submitdata] Extra parameters to send when submitting edited content.
 * @param String  options[type]      text, textarea or select
 * @param Integer options[rows]      number of rows if using textarea
 * @param Integer options[cols]      number of columns if using textarea
 * @param Mixed   options[height]    'auto' or height in pixels
 * @param Mixed   options[width]     'auto' or width in pixels 
 * @param String  options[loadurl]   URL to fetch external content before editing
 * @param String  options[loadtype]  Request type for load url. Should be GET or POST.
 * @param String  options[loadtext]  Text to display while loading external content.
 * @param Hash    options[loaddata]  Extra parameters to pass when fetching content before editing.
 * @param String  options[data]      Or content given as paramameter.
 * @param String  options[indicator] indicator html to show when saving
 * @param String  options[tooltip]   optional tooltip text via title attribute
 * @param String  options[event]     jQuery event such as 'click' of 'dblclick'
 * @param String  options[onblur]    'cancel', 'submit' or 'ignore'
 * @param String  options[submit]    submit button value, empty means no button
 * @param String  options[cancel]    cancel button value, empty means no button
 * @param String  options[cssclass]  CSS class to apply to input form. 'inherit' to copy from parent.
 * @param String  options[style]     Style to apply to input form 'inherit' to copy from parent.
 * @param String  options[select]    true or false, when true text is highlighted
 *             
*/

jQuery.fn.editable = function(target, options, callback) {

    /* prevent elem has no properties error */
    if (this.length === 0) { 
        return(this); 
    }
    
    var settings = {
        target     : target,
        name       : 'value',
        id         : 'id',
        event      : 'click',
        cancel     : 'Cancel',
        submit     : 'Save',
        type       : 'text',
        width      : 'auto',
        height     : 'auto',
        onblur     : 'cancel',
        loadtype   : 'GET',
        loadtext   : 'Loading...',
        tiny_mce   : false,
        loaddata   : {},
        submitdata : {}
    };
        
    if(options) {
        jQuery.extend(settings, options);
    }
    
    /* setup some functions */
    var plugin   = jQuery.editable.types[settings.type].plugin || function() { };
    var submit   = jQuery.editable.types[settings.type].submit || function() { };
    var buttons  = jQuery.editable.types[settings.type].buttons || jQuery.editable.types['defaults'].buttons;
    var content  = jQuery.editable.types[settings.type].content || jQuery.editable.types['defaults'].content;
    var element  = jQuery.editable.types[settings.type].element || jQuery.editable.types['defaults'].element;

    callback = callback || function() { };
          
    jQuery(this).attr('title', settings.tooltip);

    jQuery(this)[settings.event](function(e) {

        /* save this to self because this changes when scope changes */
        var self = this;

        /* prevent throwing an exeption if edit field is clicked again */
        if (self.editing) {
            return;
        }

        if(true == settings.tiny_mce){
            settings.width = ('auto' == settings.width)  ? jQuery(self).width() - 0 : settings.width;
            settings.height = ('auto' == settings.height) ? jQuery(self).height() + 68 : settings.height;
        } else {
            settings.width = ('auto' == settings.width)  ? jQuery(self).width() - 6 : settings.width;
            settings.height = ('auto' == settings.height) ? jQuery(self).height() : settings.height;
        }
        
        self.editing    = true;
        self.revert     = jQuery(self).html();
        jQuery(self).html('');

        /* create the form object */
        var f = document.createElement('form');

        /* apply css or style or both */
        if (settings.cssclass) {
            if('inherit' == settings.cssclass) {
                jQuery(f).attr('class', jQuery(self).attr('class'));
            } else {
                jQuery(f).attr('class', settings.cssclass);
            }
        }
        
        if(settings.style) {
            if ('inherit' == settings.style) {
                jQuery(f).attr('style', jQuery(self).attr('style'));
                /* IE needs the second line or display wont be inherited */
                jQuery(f).css('display', jQuery(self).css('display'));
            } else {
                jQuery(f).attr('style', settings.style);
            }
        }
        
        /*  Add main input element to form and store it in i. */
        var i = element.apply(f, [settings, self]);

        if(settings.font) {
            jQuery(i).css('font-size', jQuery(self).css('font-size'));
            jQuery(i).css('font-family', jQuery(self).css('font-family'));
            jQuery(i).css('font-weight', jQuery(self).css('font-weight'));
            jQuery(i).css('line-height', jQuery(self).css('line-height'));
		}
        
        /* maintain bc with 1.1.1 and earlier versions */        
        if (settings.getload) {
            settings.loadurl    = settings.getload;
            settings.loadtype = 'GET';
        } else if (settings.postload) {
            settings.loadurl    = settings.postload;
            settings.loadtype = 'POST';
        }

        /* set input content via POST, GET, given data or existing value */
        if (settings.loadurl) {
            var t = setTimeout(function() {
                i.disabled = true;
                content.apply(f, [settings.loadtext, settings, self]);
            }, 100);
                
            var loaddata = {};
            loaddata[settings.id] = self.id;
            if (jQuery.isFunction(settings.loaddata)) {
                jQuery.extend(loaddata, settings.loaddata.apply(self, [self.revert, settings]));
            } else {
                jQuery.extend(loaddata, settings.loaddata);
            }
            jQuery.ajax({
               type : settings.loadtype,
               url  : settings.loadurl,
               data : loaddata,
               success: function(string) {
                  window.clearTimeout(t);
                  content.apply(f, [string, settings, self]);
                  i.disabled = false;
               }
            });
        } else if (settings.data) {
            var str = settings.data;
            if (jQuery.isFunction(settings.data)) {
                var str = settings.data.apply(self, [self.revert, settings]);
            }
            content.apply(f, [str, settings, self]);
        } else { 
            content.apply(f, [self.revert, settings, self]);
        }
        
        i.name  = settings.name;
        
        /* add buttons to the form */
        buttons.apply(f, [settings, self]);

        /* add created form to self */
        self.appendChild(f);
        
        /* highlight input contents when requested */
        if (settings.select) {
            i.select();
        }
         
        /* attach 3rd party plugin if requested */
        plugin.apply(f, [settings, self]);      
        
         if(settings.tiny_mce==false) {
            jQuery(":input:visible:enabled:first", f).focus();
        }
       
        /* discard changes if pressing esc */
        jQuery(i).keydown(function(e) {
            if (e.keyCode == 27) {
                e.preventDefault();
                reset();
            }
        });

        var t;
        if (settings.onblur=='cancel') {
        	jQuery(i).blur(function(e) {
        		t = setTimeout(reset, 500);
        	});
        } else if ('submit' == settings.onblur) {
            jQuery(i).blur(function(e) {
                jQuery(f).submit();
            });
        } else {
            jQuery(i).blur(function(e) {
                
              /* TODO: maybe something here */
            });
        }

        jQuery(f).submit(function(e) {
                                  
            if(t) {
                clearTimeout(t);
            }

            if(true == settings.tiny_mce) {
                tinyMCE.triggerSave();
                removeTinyEditor(self);
            }
            
            /* do not submit */
            e.preventDefault(); 
            
            /* if this input type has a call before submit hook, call it */
            submit.apply(f, [settings, self]);

            /* check if given target is function */
            if (jQuery.isFunction(settings.target)) {
                var str = settings.target.apply(self, [jQuery(i).val(), settings]);
                jQuery(self).html(str);
                self.editing = false;
                callback.apply(self, [self.innerHTML, settings]);
            } else {
                /* add edited content and id of edited element to POST */
                var submitdata = {};
                submitdata[i.name] = jQuery(i).val();
                submitdata[settings.id] = self.id;
                /* add extra data to be POST:ed */
                if (jQuery.isFunction(settings.submitdata)) {
                    jQuery.extend(submitdata, settings.submitdata.apply(self, [self.revert, settings]));
                } else {
                    jQuery.extend(submitdata, settings.submitdata);
                }          

                /* show the saving indicator */
                jQuery(self).html(settings.indicator);
                jQuery.post(settings.target, submitdata, function(str) {					
                    jQuery(self).html(str);
                    self.editing = false;
                    callback.apply(self, [self.innerHTML, settings]);
                });
            }
                        
            return false;
        });

        function reset() {
            if(settings.tiny_mce==true) {
                removeTinyEditor(self);
            }
            jQuery(self).html(self.revert);
            self.editing   = false;
        }

        function removeTinyEditor(scope) {
            $('#tiny_mce',scope).each(function(){
                var id = this.attributes.getNamedItem("name").value;
                tinyMCE.execCommand('mceFocus', false, id);                    
                tinyMCE.execCommand('mceRemoveControl', false, id);
            });
        }
        function initTinyEditor(scope) {
            $('#tiny_mce',scope).each(function(){
                var id = this.attributes.getNamedItem("name").value;
                tinyMCE.idCounter=0;
                tinyMCE.execCommand('mceAddControl', false, id);
                tinyMCE.switchClassCache = [];
                tinyMCE.execCommand('mceFocus', false, id);                
            });
        }

        initTinyEditor(self);
    });
    
    return(this);
};

jQuery.editable = {
    types: {
        defaults: {
            element : function(settings, original) {
                var input = jQuery('<input type="hidden">');                
                jQuery(this).append(input);
                return(input);
            },
            content : function(string, settings, original) {
                jQuery(':input:first', this).val(string);
            },
            buttons : function(settings, original) {
                if (settings.submit) {
                    var submit = jQuery('<input type="submit">');
                    submit.val(settings.submit);
                    jQuery(this).append(submit);
                }
                if (settings.cancel) {
                    var cancel = jQuery('<input type="button">');
                    cancel.val(settings.cancel);
                    cancel.attr('id','cancel');
                    jQuery(this).append(cancel);

                    jQuery(cancel).click(function() {
                        jQuery(original).html(original.revert);
                        original.editing = false;
                    });
                }
            }
        },
        text: {
            element : function(settings, original) {
                var input = jQuery('<input>');
                input.width(settings.width);
                input.height(settings.height);
                input.attr('autocomplete','off');
                jQuery(this).append(input);
                return(input);
            }
        },
        price: {
            element : function(settings, original) {
                var input = jQuery('<input>');
                input.width(settings.width);
                input.height(settings.height);
                input.attr('autocomplete','off');
                jQuery(this).append(input);
                return(input);
            },
            content : function(string, settings, original) {
                string = string.replace("$", "");
                jQuery(':input:first', this).val(string);
            }            
        },
        textarea: {
            element : function(settings, original) {
                var textarea = jQuery('<textarea>');
                if (settings.rows) {
                    textarea.attr('rows', settings.rows);
                } else {
                    textarea.height(settings.height);
                }
                if (settings.cols) {
                    textarea.attr('cols', settings.cols);
                } else {
                    textarea.width(settings.width);
                }
                if(true == settings.tiny_mce) {
                    textarea.attr('id', 'tiny_mce');
                    textarea.attr('name', 'tiny_mce');
                }
                jQuery(this).append(textarea);
                return(textarea);
            }
        },
        select: {
            element : function(settings, original) {
                var select = jQuery('<select>');
                jQuery(this).append(select);
                return(select);
            },
            content : function(string, settings, original) {
                if (String == string.constructor) {      
                    eval ("var json = " + string);
                    for (var key in json) {
                        if ('selected' == key) {
                            continue;
                        } 
                        var option = $('<option>').val(key).append(json[key]);
                        if (key == json['selected']) {
                            console.log(key);
                            /* TODO: why does not this work? */
                            //option.attr('selected', 'selected');
                            option[0].selected = true;
                        }
                        jQuery("select", this).append(option);      
                    }
                }
            }
        }
    },
    
    /* Add new input type */
    addInputType: function(name, input) {
        jQuery.editable.types[name] = input;
    }
};


$.editable.addInputType('ajaxupload', {
    /* create input element */
    element : function(settings) {
        settings.onblur = 'ignore';

		var input = $('<input type="file" id="upload" name="upload"><br><input type="hidden" id="field" name="field" value="' + settings.submitdata["field"] + '"><input type="hidden" id="link" name="link" value="' + settings.submitdata["link"] + '">');
        $(this).append(input);
		
        return(input);
    },
    content : function(string, settings, original) {
        /* do nothing */
    },
    plugin : function(settings, original) {
        var form = this;
		
 		$("input:submit", this).bind('click', function() {
            //$(".message").show();
			$.ajaxFileUpload({
                url: settings.target,
                secureuri:false,
                fileElementId: 'upload',
                dataType: 'html',
                success: function (data, status) {
        			$(original).html(data);
        			original.editing = false;
					$(original).find("img").yellow_highlightFade('border');
                },
                error: function (data, status, e) {
                    alert(e);
                }
            })
            return(false);
        });
    }
});
