Rgm.ExpandWidgetControl=Class.create();Rgm.ExpandWidgetControl.prototype={initialize:function(name,widgetId){this.name=name;this.widgetId=widgetId;this.isLoaded=false;this.container=$(this.name+'_content_'+this.widgetId);},expand:function(){if(this.isLoaded){this.onCompleteExpand();}else{new Ajax.Request('/editor/edit_layout/ajax_show_widget/'+this.widgetId,{onComplete:this.onComplete.bind(this)});}},onComplete:function(request){eval(request.responseText);this.onCompleteExpand();},onCompleteExpand:function(){Element.show(this.container);Element.hide('show_'+this.name+'_'+this.widgetId);Element.show('hide_'+this.name+'_'+this.widgetId);this.isLoaded=true;},collapse:function(){Element.hide(this.container);Element.show('show_'+this.name+'_'+this.widgetId);Element.hide('hide_'+this.name+'_'+this.widgetId);},registerForm:function(){this.form=$('form_'+this.widgetId);this.strategySelect=$('strategy_'+this.widgetId);this.currCategorySelect=$('category_'+this.widgetId)||$('subcategory_'+this.widgetId)||null
this.spanSequence=$('span_sequence_'+this.widgetId)||null
if(this.isCategoryPresent(this.currCategorySelect)){if(Form.Element.getValue(this.strategySelect)!='CustomWidgetStrategy'){this.formDisabled=true;this.currCategorySelect.disabled=false;this.spanSequence.disabled=false;}else{this.formDisabled=false;this.currCategorySelect.disabled=false;this.spanSequence.disabled=false;}
this.refreshFormElements(this.currCategorySelect);Event.observe(this.currCategorySelect,'change',this.onChangeAutomaticSelect.bind(this));}else{if(Form.Element.getValue(this.strategySelect)!='CustomWidgetStrategy'){this.formDisabled=true;this.spanSequence.disabled=false;}else{this.formDisabled=false;this.spanSequence.disabled=false;}}
Event.observe(this.strategySelect,'change',this.onChangeAutomaticSelect.bind(this));},isCategoryPresent:function(categorySelect){return(categorySelect==null)?false:true;},onChangeAutomaticSelect:function(ev){params='path='+this.form.elements['path'].value;params+='&widget_strategy='+this.strategySelect.value;if(this.currCategorySelect!=null){params+='&'+this.currCategorySelect.id+'='+this.currCategorySelect.value;}
new Ajax.Request('/editor/edit_layout/ajax_update_widget/'+this.widgetId,{parameters:params,onComplete:this.onComplete.bind(this)});},refreshFormElements:function(categorySelect){for(var i=0;i<this.form.elements.length;++i){var element=this.form.elements[i];if(element.id!=this.strategySelect.id&&element.id!=this.spanSequence.id&&element.id!=categorySelect.id&&element.type!='submit'&&element.type!='image'&&element.type!='button'){element.disabled=this.formDisabled;}}}}
function setLoginLinks(){}
function setDefaultLinks(){$('logoutLink').style.display='';$('loginLink').style.display='none';if($('header_login')){$('header_login').style.display='none';}
if($('you_must_be_an_editor')){$('you_must_be_an_editor').style.display='none';}
if($('you_may_enter')){$('you_may_enter').style.display='';}}
function setEditorLinksLoggedOut(){window.location='/editor/browse';}
function setEditorLinks(){if(!Rgm.isLoggedIn())
{setDefaultLinks();setEditorLinksLoggedOut();}else if(Rgm.isEditor()){setDefaultLinks();}}
Rgm.CharCounter=Class.create();Rgm.CharCounter.prototype={initialize:function(textElemId,msgLyrId,msg,maxChars,editorType){this.textElemId=textElemId;this.textElem=$j('#'+textElemId)[0];this.msgLyr=$j('#'+msgLyrId)[0];this.msg=msg;this.maxChars=maxChars;this.editorType=editorType;if(this.isCKEditor()){var ckEditor=this.getCKEditor();var updateCounterProxy=$j.proxy(this.updateCounter,this);ckEditor.on('focus',updateCounterProxy);ckEditor.on('contentDom',function(e){this.document.on('keyup',updateCounterProxy);});this.updateCounter();}else{var counter=this;$j(this.textElem).keyup($j.proxy(this.onTextKeyup,this)).focus($j.proxy(this.onTextFocus,this));this.updateCounter();}},onTextKeyup:function(){this.updateCounter();},onTextFocus:function(){this.updateCounter();},updateCounter:function(){var len=this.maxChars-this.elemValue().length;if(len<=0){len=0;this.truncateValue();}
if(this.isCKEditor()&&len<=0){$j(this.msgLyr).text('<span style="color:red">Text is too long</span>');}else{$j(this.msgLyr).text(this.msg.replace("{NUMB}",len));}},elemValue:function(){if(this.isCKEditor()){data=this.getCKEditor().getData();return data===null?"":data;}else{return $j(this.textElem).val();}},truncateValue:function(){if(!this.isCKEditor()){$j(this.textElem).val($j(this.textElem).val().substr(0,this.maxChars));}},isCKEditor:function(){return this.editorType=='ck';},getCKEditor:function(){return CKEDITOR.instances[this.textElemId];}};if(typeof Prototype=='undefined')alert("CalendarDateSelect Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (.g. <%= javascript_include_tag :defaults %>) *before* it includes calendar_date_select.js (.g. <%= calendar_date_select_includes %>).");if(Prototype.Version<"1.6")alert("Prototype 1.6.0 is required.  If using earlier version of prototype, please use calendar_date_select version 1.8.3");Element.addMethods({purgeChildren:function(element){$A(element.childNodes).each(function(e){$(e).remove();});},build:function(element,type,options,style){var newElement=Element.buildAndAppend(type,options,style);element.appendChild(newElement);return newElement;}});Element.buildAndAppend=function(type,options,style)
{var e=$(document.createElement(type));$H(options).each(function(pair){eval("e."+pair.key+" = pair.value");});if(style)
$H(style).each(function(pair){eval("e.style."+pair.key+" = pair.value");});return e;};nil=null;Date.one_day=24*60*60*1000;Date.weekdays=$w("S M T W T F S");Date.first_day_of_week=0;Date.months=$w("January February March April May June July August September October November December");Date.padded2=function(hour){var padded2=parseInt(hour,10);if(hour<10)padded2="0"+padded2;return padded2;}
Date.prototype.getPaddedMinutes=function(){return Date.padded2(this.getMinutes());}
Date.prototype.getAMPMHour=function(){var hour=this.getHours();return(hour==0)?12:(hour>12?hour-12:hour)}
Date.prototype.getAMPM=function(){return(this.getHours()<12)?"AM":"PM";}
Date.prototype.stripTime=function(){return new Date(this.getFullYear(),this.getMonth(),this.getDate());};Date.prototype.daysDistance=function(compare_date){return Math.round((compare_date-this)/Date.one_day);};Date.prototype.toFormattedString=function(include_time){var hour,str;str=Date.months[this.getMonth()]+" "+this.getDate()+", "+this.getFullYear();if(include_time){hour=this.getHours();str+=" "+this.getAMPMHour()+":"+this.getPaddedMinutes()+" "+this.getAMPM()}
return str;}
Date.parseFormattedString=function(string){return new Date(string);}
Math.floor_to_interval=function(n,i){return Math.floor(n/i)*i;}
window.f_height=function(){return([window.innerHeight?window.innerHeight:null,document.documentElement?document.documentElement.clientHeight:null,document.body?document.body.clientHeight:null].select(function(x){return x>0}).first()||0);}
window.f_scrollTop=function(){return([window.pageYOffset?window.pageYOffset:null,document.documentElement?document.documentElement.scrollTop:null,document.body?document.body.scrollTop:null].select(function(x){return x>0}).first()||0);}
_translations={"OK":"OK","Now":"Now","Today":"Today"}
SelectBox=Class.create();SelectBox.prototype={initialize:function(parent_element,values,html_options,style_options){this.element=$(parent_element).build("select",html_options,style_options);this.populate(values);},populate:function(values){this.element.purgeChildren();var that=this;$A(values).each(function(pair){if(typeof(pair)!="object"){pair=[pair,pair]};that.element.build("option",{value:pair[1],innerHTML:pair[0]})});},setValue:function(value){var e=this.element;var matched=false;$R(0,e.options.length-1).each(function(i){if(e.options[i].value==value.toString()){e.selectedIndex=i;matched=true;};});return matched;},getValue:function(){return $F(this.element)}}
CalendarDateSelect=Class.create();CalendarDateSelect.prototype={initialize:function(target_element,options){this.target_element=$(target_element);if(!this.target_element){alert("Target element "+target_element+" not found!");return false;}
if(this.target_element.tagName!="INPUT")this.target_element=this.target_element.down("INPUT")
this.target_element.calendar_date_select=this;this.last_click_at=0;this.options=$H({embedded:false,popup:nil,time:false,buttons:true,year_range:10,close_on_click:nil,minute_interval:5,popup_by:this.target_element,month_year:"dropdowns",onchange:this.target_element.onchange,valid_date_check:nil}).merge(options||{});this.use_time=this.options.get("time");this.parseDate();this.callback("before_show")
this.initCalendarDiv();if(!this.options.get("embedded")){this.positionCalendarDiv()
Event.observe(document,"mousedown",this.closeIfClickedOut_handler=this.closeIfClickedOut.bindAsEventListener(this));Event.observe(document,"keypress",this.keyPress_handler=this.keyPress.bindAsEventListener(this));}
this.callback("after_show")},positionCalendarDiv:function(){var above=false;var c_pos=this.calendar_div.viewportOffset(),c_left=c_pos[0],c_top=c_pos[1],c_dim=this.calendar_div.getDimensions(),c_height=c_dim.height,c_width=c_dim.width;var w_top=window.f_scrollTop(),w_height=window.f_height();var e_dim=$(this.options.get("popup_by")).viewportOffset(),e_top=e_dim[1],e_left=e_dim[0],e_height=$(this.options.get("popup_by")).getDimensions().height,e_bottom=e_top+e_height;if(((e_bottom+c_height)>(w_top+w_height))&&(e_bottom-c_height>w_top))above=true;var left_px=e_left.toString()+"px",top_px=(above?(e_top-c_height):(e_top+e_height)).toString()+"px";this.calendar_div.style.left=left_px;this.calendar_div.style.top=top_px;this.calendar_div.setStyle({visibility:""});if(navigator.appName=="Microsoft Internet Explorer")this.iframe=$(document.body).build("iframe",{src:"javascript:false",className:"ie6_blocker"},{left:left_px,top:top_px,height:c_height.toString()+"px",width:c_width.toString()+"px",border:"0px"})},initCalendarDiv:function(){if(this.options.get("embedded")){var parent=this.target_element.parentNode;var style={}}else{var parent=document.body
var style={position:"absolute",visibility:"hidden",left:0,top:0}}
this.calendar_div=$(parent).build('div',{className:"calendar_date_select"},style);var that=this;$w("top header body buttons footer bottom").each(function(name){eval("var "+name+"_div = that."+name+"_div = that.calendar_div.build('div', { className: 'cds_"+name+"' }, { clear: 'left'} ); ");});this.initHeaderDiv();this.initButtonsDiv();this.initCalendarGrid();this.updateFooter("&#160;");this.refresh();this.setUseTime(this.use_time);},initHeaderDiv:function(){var header_div=this.header_div;this.close_button=header_div.build("a",{innerHTML:"x",href:"#",onclick:function(){this.close();return false;}.bindAsEventListener(this),className:"close"});this.next_month_button=header_div.build("a",{innerHTML:"&gt;",href:"#",onclick:function(){this.navMonth(this.date.getMonth()+1);return false;}.bindAsEventListener(this),className:"next"});this.prev_month_button=header_div.build("a",{innerHTML:"&lt;",href:"#",onclick:function(){this.navMonth(this.date.getMonth()-1);return false;}.bindAsEventListener(this),className:"prev"});if(this.options.get("month_year")=="dropdowns"){this.month_select=new SelectBox(header_div,$R(0,11).map(function(m){return[Date.months[m],m]}),{className:"month",onchange:function(){this.navMonth(this.month_select.getValue())}.bindAsEventListener(this)});this.year_select=new SelectBox(header_div,[],{className:"year",onchange:function(){this.navYear(this.year_select.getValue())}.bindAsEventListener(this)});this.populateYearRange();}else{this.month_year_label=header_div.build("span")}},initCalendarGrid:function(){var body_div=this.body_div;this.calendar_day_grid=[];var days_table=body_div.build("table",{cellPadding:"0px",cellSpacing:"0px",width:"100%"})
var weekdays_row=days_table.build("thead").build("tr");Date.weekdays.each(function(weekday){weekdays_row.build("th",{innerHTML:weekday});});var days_tbody=days_table.build("tbody")
var row_number=0,weekday;for(var cell_index=0;cell_index<42;cell_index++)
{weekday=(cell_index+Date.first_day_of_week)%7;if(cell_index%7==0)days_row=days_tbody.build("tr",{className:'row_'+row_number++});(this.calendar_day_grid[cell_index]=days_row.build("td",{calendar_date_select:this,onmouseover:function(){this.calendar_date_select.dayHover(this);},onmouseout:function(){this.calendar_date_select.dayHoverOut(this)},onclick:function(){this.calendar_date_select.updateSelectedDate(this,true);},className:(weekday==0)||(weekday==6)?" weekend":""},{cursor:"pointer"})).build("div");this.calendar_day_grid[cell_index];}},initButtonsDiv:function()
{var buttons_div=this.buttons_div;if(this.options.get("time"))
{var blank_time=$A(this.options.get("time")=="mixed"?[[" - ",""]]:[]);buttons_div.build("span",{innerHTML:"@",className:"at_sign"});var t=new Date();this.hour_select=new SelectBox(buttons_div,blank_time.concat($R(0,23).map(function(x){t.setHours(x);return $A([t.getAMPMHour()+" "+t.getAMPM(),x])})),{calendar_date_select:this,onchange:function(){this.calendar_date_select.updateSelectedDate({hour:this.value});},className:"hour"});buttons_div.build("span",{innerHTML:":",className:"seperator"});var that=this;this.minute_select=new SelectBox(buttons_div,blank_time.concat($R(0,59).select(function(x){return(x%that.options.get('minute_interval')==0)}).map(function(x){return $A([Date.padded2(x),x]);})),{calendar_date_select:this,onchange:function(){this.calendar_date_select.updateSelectedDate({minute:this.value})},className:"minute"});}else if(!this.options.get("buttons"))buttons_div.remove();if(this.options.get("buttons")){buttons_div.build("span",{innerHTML:"&#160;"});if(this.options.get("time")=="mixed"||!this.options.get("time"))b=buttons_div.build("a",{innerHTML:_translations["Today"],href:"#",onclick:function(){this.today(false);return false;}.bindAsEventListener(this)});if(this.options.get("time")=="mixed")buttons_div.build("span",{innerHTML:" | ",className:"button_seperator"})
if(this.options.get("time"))b=buttons_div.build("a",{innerHTML:_translations["Now"],href:"#",onclick:function(){this.today(true);return false}.bindAsEventListener(this)});if(!this.options.get("embedded"))
{buttons_div.build("span",{innerHTML:"&#160;"});buttons_div.build("a",{innerHTML:_translations["OK"],href:"#",onclick:function(){this.close();return false;}.bindAsEventListener(this)});}}},refresh:function()
{this.refreshMonthYear();this.refreshCalendarGrid();this.setSelectedClass();this.updateFooter();},refreshCalendarGrid:function(){this.beginning_date=new Date(this.date).stripTime();this.beginning_date.setDate(1);this.beginning_date.setHours(12);var pre_days=this.beginning_date.getDay()
if(pre_days<3)pre_days+=7;this.beginning_date.setDate(1-pre_days+Date.first_day_of_week);var iterator=new Date(this.beginning_date);var today=new Date().stripTime();var this_month=this.date.getMonth();vdc=this.options.get("valid_date_check");for(var cell_index=0;cell_index<42;cell_index++)
{day=iterator.getDate();month=iterator.getMonth();cell=this.calendar_day_grid[cell_index];Element.remove(cell.childNodes[0]);div=cell.build("div",{innerHTML:day});if(month!=this_month)div.className="other";cell.day=day;cell.month=month;cell.year=iterator.getFullYear();if(vdc){if(vdc(iterator.stripTime()))cell.removeClassName("disabled");else cell.addClassName("disabled")};iterator.setDate(day+1);}
if(this.today_cell)this.today_cell.removeClassName("today");if($R(0,41).include(days_until=this.beginning_date.stripTime().daysDistance(today))){this.today_cell=this.calendar_day_grid[days_until];this.today_cell.addClassName("today");}},refreshMonthYear:function(){var m=this.date.getMonth();var y=this.date.getFullYear();if(this.options.get("month_year")=="dropdowns")
{this.month_select.setValue(m,false);var e=this.year_select.element;if(this.flexibleYearRange()&&(!(this.year_select.setValue(y,false))||e.selectedIndex<=1||e.selectedIndex>=e.options.length-2))this.populateYearRange();this.year_select.setValue(y);}else{this.month_year_label.update(Date.months[m]+" "+y.toString());}},populateYearRange:function(){this.year_select.populate(this.yearRange().toArray());},yearRange:function(){if(!this.flexibleYearRange())
return $R(this.options.get("year_range")[0],this.options.get("year_range")[1]);var y=this.date.getFullYear();return $R(y-this.options.get("year_range"),y+this.options.get("year_range"));},flexibleYearRange:function(){return(typeof(this.options.get("year_range"))=="number");},validYear:function(year){if(this.flexibleYearRange()){return true;}else{return this.yearRange().include(year);}},dayHover:function(element){var hover_date=new Date(this.selected_date);hover_date.setYear(element.year);hover_date.setMonth(element.month);hover_date.setDate(element.day);this.updateFooter(hover_date.toFormattedString(this.use_time));},dayHoverOut:function(element){this.updateFooter();},clearSelectedClass:function(){if(this.selected_cell)this.selected_cell.removeClassName("selected");},setSelectedClass:function(){if(!this.selection_made)return;this.clearSelectedClass()
if($R(0,42).include(days_until=this.beginning_date.stripTime().daysDistance(this.selected_date.stripTime()))){this.selected_cell=this.calendar_day_grid[days_until];this.selected_cell.addClassName("selected");}},reparse:function(){this.parseDate();this.refresh();},dateString:function(){return(this.selection_made)?this.selected_date.toFormattedString(this.use_time):"&#160;";},parseDate:function()
{var value=$F(this.target_element).strip()
this.selection_made=(value!="");this.date=value==""?NaN:Date.parseFormattedString(this.options.get("date")||value);if(isNaN(this.date))this.date=new Date();if(!this.validYear(this.date.getFullYear()))this.date.setYear((this.date.getFullYear()<this.yearRange().start)?this.yearRange().start:this.yearRange().end);this.selected_date=new Date(this.date);this.use_time=/[0-9]:[0-9]{2}/.exec(value)?true:false;this.date.setDate(1);},updateFooter:function(text){if(!text)text=this.dateString();this.footer_div.purgeChildren();this.footer_div.build("span",{innerHTML:text});},updateSelectedDate:function(partsOrElement,via_click){var parts=$H(partsOrElement);if((this.target_element.disabled||this.target_element.readOnly)&&this.options.get("popup")!="force")return false;if(parts.get("day")){var t_selected_date=this.selected_date,vdc=this.options.get("valid_date_check");for(var x=0;x<=3;x++)t_selected_date.setDate(parts.get("day"));t_selected_date.setYear(parts.get("year"));t_selected_date.setMonth(parts.get("month"));if(vdc&&!vdc(t_selected_date.stripTime())){return false;}
this.selected_date=t_selected_date;this.selection_made=true;}
if(!isNaN(parts.get("hour")))this.selected_date.setHours(parts.get("hour"));if(!isNaN(parts.get("minute")))this.selected_date.setMinutes(Math.floor_to_interval(parts.get("minute"),this.options.get("minute_interval")));if(parts.get("hour")===""||parts.get("minute")==="")
this.setUseTime(false);else if(!isNaN(parts.get("hour"))||!isNaN(parts.get("minute")))
this.setUseTime(true);this.updateFooter();this.setSelectedClass();if(this.selection_made)this.updateValue();if(this.closeOnClick()){this.close();}
if(via_click&&!this.options.get("embedded")){if((new Date()-this.last_click_at)<333)this.close();this.last_click_at=new Date();}},closeOnClick:function(){if(this.options.get("embedded"))return false;if(this.options.get("close_on_click")===nil)
return(this.options.get("time"))?false:true
else
return(this.options.get("close_on_click"))},navMonth:function(month){(target_date=new Date(this.date)).setMonth(month);return(this.navTo(target_date));},navYear:function(year){(target_date=new Date(this.date)).setYear(year);return(this.navTo(target_date));},navTo:function(date){if(!this.validYear(date.getFullYear()))return false;this.date=date;this.date.setDate(1);this.refresh();this.callback("after_navigate",this.date);return true;},setUseTime:function(turn_on){this.use_time=this.options.get("time")&&(this.options.get("time")=="mixed"?turn_on:true)
if(this.use_time&&this.selected_date){var minute=Math.floor_to_interval(this.selected_date.getMinutes(),this.options.get("minute_interval"));var hour=this.selected_date.getHours();this.hour_select.setValue(hour);this.minute_select.setValue(minute)}else if(this.options.get("time")=="mixed"){this.hour_select.setValue("");this.minute_select.setValue("");}},updateValue:function(){var last_value=this.target_element.value;this.target_element.value=this.dateString();if(last_value!=this.target_element.value)this.callback("onchange");},today:function(now){var d=new Date();this.date=new Date();var o=$H({day:d.getDate(),month:d.getMonth(),year:d.getFullYear(),hour:d.getHours(),minute:d.getMinutes()});if(!now)o=o.merge({hour:"",minute:""});this.updateSelectedDate(o,true);this.refresh();},close:function(){if(this.closed)return false;this.callback("before_close");this.target_element.calendar_date_select=nil;Event.stopObserving(document,"mousedown",this.closeIfClickedOut_handler);Event.stopObserving(document,"keypress",this.keyPress_handler);this.calendar_div.remove();this.closed=true;if(this.iframe)this.iframe.remove();if(this.target_element.type!="hidden")this.target_element.focus();this.callback("after_close");},closeIfClickedOut:function(e){if(!$(Event.element(e)).descendantOf(this.calendar_div))this.close();},keyPress:function(e){if(e.keyCode==Event.KEY_ESC)this.close();},callback:function(name,param){if(this.options.get(name)){this.options.get(name).bind(this.target_element)(param);}}};(function($){$.fn.ajaxSubmit=function(options){if(!this.length){log('ajaxSubmit: skipping submit process - no element selected');return this;}
var method,action,url,$form=this;if(typeof options=='function'){options={success:options};}
method=this.attr('method');action=this.attr('action');url=(typeof action==='string')?$.trim(action):'';url=url||window.location.href||'';if(url){url=(url.match(/^([^#]+)/)||[])[1];}
options=$.extend(true,{url:url,success:$.ajaxSettings.success,type:method||'GET',iframeSrc:/^https/i.test(window.location.href||'')?'javascript:false':'about:blank'},options);var veto={};this.trigger('form-pre-serialize',[this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');return this;}
if(options.beforeSerialize&&options.beforeSerialize(this,options)===false){log('ajaxSubmit: submit aborted via beforeSerialize callback');return this;}
var traditional=options.traditional;if(traditional===undefined){traditional=$.ajaxSettings.traditional;}
var qx,n,v,a=this.formToArray(options.semantic);if(options.data){options.extraData=options.data;qx=$.param(options.data,traditional);}
if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){log('ajaxSubmit: submit aborted via beforeSubmit callback');return this;}
this.trigger('form-submit-validate',[a,this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-submit-validate trigger');return this;}
var q=$.param(a,traditional);if(qx){q=(q?(q+'&'+qx):qx);}
if(options.type.toUpperCase()=='GET'){options.url+=(options.url.indexOf('?')>=0?'&':'?')+q;options.data=null;}
else{options.data=q;}
var callbacks=[];if(options.resetForm){callbacks.push(function(){$form.resetForm();});}
if(options.clearForm){callbacks.push(function(){$form.clearForm(options.includeHidden);});}
if(!options.dataType&&options.target){var oldSuccess=options.success||function(){};callbacks.push(function(data){var fn=options.replaceTarget?'replaceWith':'html';$(options.target)[fn](data).each(oldSuccess,arguments);});}
else if(options.success){callbacks.push(options.success);}
options.success=function(data,status,xhr){var context=options.context||options;for(var i=0,max=callbacks.length;i<max;i++){callbacks[i].apply(context,[data,status,xhr||$form,$form]);}};var fileInputs=$('input:file:enabled[value]',this);var hasFileInputs=fileInputs.length>0;var mp='multipart/form-data';var multipart=($form.attr('enctype')==mp||$form.attr('encoding')==mp);var fileAPI=!!(hasFileInputs&&fileInputs.get(0).files&&window.FormData);log("fileAPI :"+fileAPI);var shouldUseFrame=(hasFileInputs||multipart)&&!fileAPI;if(options.iframe!==false&&(options.iframe||shouldUseFrame)){if(options.closeKeepAlive){$.get(options.closeKeepAlive,function(){fileUploadIframe(a);});}
else{fileUploadIframe(a);}}
else if((hasFileInputs||multipart)&&fileAPI){options.progress=options.progress||$.noop;fileUploadXhr(a);}
else{$.ajax(options);}
this.trigger('form-submit-notify',[this,options]);return this;function fileUploadXhr(a){var formdata=new FormData();for(var i=0;i<a.length;i++){if(a[i].type=='file')
continue;formdata.append(a[i].name,a[i].value);}
$form.find('input:file:enabled').each(function(){var name=$(this).attr('name'),files=this.files;if(name){for(var i=0;i<files.length;i++)
formdata.append(name,files[i]);}});if(options.extraData){for(var k in options.extraData)
formdata.append(k,options.extraData[k])}
options.data=null;var s=$.extend(true,{},$.ajaxSettings,options,{contentType:false,processData:false,cache:false,type:'POST'});s.context=s.context||s;s.data=null;var beforeSend=s.beforeSend;s.beforeSend=function(xhr,o){o.data=formdata;if(xhr.upload){xhr.upload.onprogress=function(event){o.progress(event.position,event.total);};}
if(beforeSend)
beforeSend.call(o,xhr,options);};$.ajax(s);}
function fileUploadIframe(a){var form=$form[0],el,i,s,g,id,$io,io,xhr,sub,n,timedOut,timeoutHandle;var useProp=!!$.fn.prop;if(a){if(useProp){for(i=0;i<a.length;i++){el=$(form[a[i].name]);el.prop('disabled',false);}}else{for(i=0;i<a.length;i++){el=$(form[a[i].name]);el.removeAttr('disabled');}};}
if($(':input[name=submit],:input[id=submit]',form).length){alert('Error: Form elements must not have name or id of "submit".');return;}
s=$.extend(true,{},$.ajaxSettings,options);s.context=s.context||s;id='jqFormIO'+(new Date().getTime());if(s.iframeTarget){$io=$(s.iframeTarget);n=$io.attr('name');if(n==null)
$io.attr('name',id);else
id=n;}
else{$io=$('<iframe name="'+id+'" src="'+s.iframeSrc+'" />');$io.css({position:'absolute',top:'-1000px',left:'-1000px'});}
io=$io[0];xhr={aborted:0,responseText:null,responseXML:null,status:0,statusText:'n/a',getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(status){var e=(status==='timeout'?'timeout':'aborted');log('aborting upload... '+e);this.aborted=1;$io.attr('src',s.iframeSrc);xhr.error=e;s.error&&s.error.call(s.context,xhr,e,status);g&&$.event.trigger("ajaxError",[xhr,s,e]);s.complete&&s.complete.call(s.context,xhr,e);}};g=s.global;if(g&&!$.active++){$.event.trigger("ajaxStart");}
if(g){$.event.trigger("ajaxSend",[xhr,s]);}
if(s.beforeSend&&s.beforeSend.call(s.context,xhr,s)===false){if(s.global){$.active--;}
return;}
if(xhr.aborted){return;}
sub=form.clk;if(sub){n=sub.name;if(n&&!sub.disabled){s.extraData=s.extraData||{};s.extraData[n]=sub.value;if(sub.type=="image"){s.extraData[n+'.x']=form.clk_x;s.extraData[n+'.y']=form.clk_y;}}}
var CLIENT_TIMEOUT_ABORT=1;var SERVER_ABORT=2;function getDoc(frame){var doc=frame.contentWindow?frame.contentWindow.document:frame.contentDocument?frame.contentDocument:frame.document;return doc;}
var csrf_token=$('meta[name=csrf-token]').attr('content');var csrf_param=$('meta[name=csrf-param]').attr('content');if(csrf_param&&csrf_token){s.extraData=s.extraData||{};s.extraData[csrf_param]=csrf_token;}
function doSubmit(){var t=$form.attr('target'),a=$form.attr('action');form.setAttribute('target',id);if(!method){form.setAttribute('method','POST');}
if(a!=s.url){form.setAttribute('action',s.url);}
if(!s.skipEncodingOverride&&(!method||/post/i.test(method))){$form.attr({encoding:'multipart/form-data',enctype:'multipart/form-data'});}
if(s.timeout){timeoutHandle=setTimeout(function(){timedOut=true;cb(CLIENT_TIMEOUT_ABORT);},s.timeout);}
function checkState(){try{var state=getDoc(io).readyState;log('state = '+state);if(state.toLowerCase()=='uninitialized')
setTimeout(checkState,50);}
catch(e){log('Server abort: ',e,' (',e.name,')');cb(SERVER_ABORT);timeoutHandle&&clearTimeout(timeoutHandle);timeoutHandle=undefined;}}
var extraInputs=[];try{if(s.extraData){for(var n in s.extraData){extraInputs.push($('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n]).appendTo(form)[0]);}}
if(!s.iframeTarget){$io.appendTo('body');io.attachEvent?io.attachEvent('onload',cb):io.addEventListener('load',cb,false);}
setTimeout(checkState,15);form.submit();}
finally{form.setAttribute('action',a);if(t){form.setAttribute('target',t);}else{$form.removeAttr('target');}
$(extraInputs).remove();}}
if(s.forceSync){doSubmit();}
else{setTimeout(doSubmit,10);}
var data,doc,domCheckCount=50,callbackProcessed;function cb(e){if(xhr.aborted||callbackProcessed){return;}
try{doc=getDoc(io);}
catch(ex){log('cannot access response document: ',ex);e=SERVER_ABORT;}
if(e===CLIENT_TIMEOUT_ABORT&&xhr){xhr.abort('timeout');return;}
else if(e==SERVER_ABORT&&xhr){xhr.abort('server abort');return;}
if(!doc||doc.location.href==s.iframeSrc){if(!timedOut)
return;}
io.detachEvent?io.detachEvent('onload',cb):io.removeEventListener('load',cb,false);var status='success',errMsg;try{if(timedOut){throw'timeout';}
var isXml=s.dataType=='xml'||doc.XMLDocument||$.isXMLDoc(doc);log('isXml='+isXml);if(!isXml&&window.opera&&(doc.body==null||doc.body.innerHTML=='')){if(--domCheckCount){log('requeing onLoad callback, DOM not available');setTimeout(cb,250);return;}}
var docRoot=doc.body?doc.body:doc.documentElement;xhr.responseText=docRoot?docRoot.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;if(isXml)
s.dataType='xml';xhr.getResponseHeader=function(header){var headers={'content-type':s.dataType};return headers[header];};if(docRoot){xhr.status=Number(docRoot.getAttribute('status'))||xhr.status;xhr.statusText=docRoot.getAttribute('statusText')||xhr.statusText;}
var dt=(s.dataType||'').toLowerCase();var scr=/(json|script|text)/.test(dt);if(scr||s.textarea){var ta=doc.getElementsByTagName('textarea')[0];if(ta){xhr.responseText=ta.value;xhr.status=Number(ta.getAttribute('status'))||xhr.status;xhr.statusText=ta.getAttribute('statusText')||xhr.statusText;}
else if(scr){var pre=doc.getElementsByTagName('pre')[0];var b=doc.getElementsByTagName('body')[0];if(pre){xhr.responseText=pre.textContent?pre.textContent:pre.innerText;}
else if(b){xhr.responseText=b.textContent?b.textContent:b.innerText;}}}
else if(dt=='xml'&&!xhr.responseXML&&xhr.responseText!=null){xhr.responseXML=toXml(xhr.responseText);}
try{data=httpData(xhr,dt,s);}
catch(e){status='parsererror';xhr.error=errMsg=(e||status);}}
catch(e){log('error caught: ',e);status='error';xhr.error=errMsg=(e||status);}
if(xhr.aborted){log('upload aborted');status=null;}
if(xhr.status){status=(xhr.status>=200&&xhr.status<300||xhr.status===304)?'success':'error';}
if(status==='success'){s.success&&s.success.call(s.context,data,'success',xhr);g&&$.event.trigger("ajaxSuccess",[xhr,s]);}
else if(status){if(errMsg==undefined)
errMsg=xhr.statusText;s.error&&s.error.call(s.context,xhr,status,errMsg);g&&$.event.trigger("ajaxError",[xhr,s,errMsg]);}
g&&$.event.trigger("ajaxComplete",[xhr,s]);if(g&&!--$.active){$.event.trigger("ajaxStop");}
s.complete&&s.complete.call(s.context,xhr,status);callbackProcessed=true;if(s.timeout)
clearTimeout(timeoutHandle);setTimeout(function(){if(!s.iframeTarget)
$io.remove();xhr.responseXML=null;},100);}
var toXml=$.parseXML||function(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.nodeName!='parsererror')?doc:null;};var parseJSON=$.parseJSON||function(s){return window['eval']('('+s+')');};var httpData=function(xhr,type,s){var ct=xhr.getResponseHeader('content-type')||'',xml=type==='xml'||!type&&ct.indexOf('xml')>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.nodeName==='parsererror'){$.error&&$.error('parsererror');}
if(s&&s.dataFilter){data=s.dataFilter(data,type);}
if(typeof data==='string'){if(type==='json'||!type&&ct.indexOf('json')>=0){data=parseJSON(data);}else if(type==="script"||!type&&ct.indexOf("javascript")>=0){$.globalEval(data);}}
return data;};}};$.fn.ajaxForm=function(options){if(this.length===0){var o={s:this.selector,c:this.context};if(!$.isReady&&o.s){log('DOM not ready, queuing ajaxForm');$(function(){$(o.s,o.c).ajaxForm(options);});return this;}
log('terminating; zero elements found by selector'+($.isReady?'':' (DOM not ready)'));return this;}
return this.ajaxFormUnbind().bind('submit.form-plugin',function(e){if(!e.isDefaultPrevented()){e.preventDefault();$(this).ajaxSubmit(options);}}).bind('click.form-plugin',function(e){var target=e.target;var $el=$(target);if(!($el.is(":submit,input:image"))){var t=$el.closest(':submit');if(t.length==0){return;}
target=t[0];}
var form=this;form.clk=target;if(target.type=='image'){if(e.offsetX!=undefined){form.clk_x=e.offsetX;form.clk_y=e.offsetY;}else if(typeof $.fn.offset=='function'){var offset=$el.offset();form.clk_x=e.pageX-offset.left;form.clk_y=e.pageY-offset.top;}else{form.clk_x=e.pageX-target.offsetLeft;form.clk_y=e.pageY-target.offsetTop;}}
setTimeout(function(){form.clk=form.clk_x=form.clk_y=null;},100);});};$.fn.ajaxFormUnbind=function(){return this.unbind('submit.form-plugin click.form-plugin');};$.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;}
var i,j,n,v,el,max,jmax;for(i=0,max=els.length;i<max;i++){el=els[i];n=el.name;if(!n){continue;}
if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el){a.push({name:n,value:$(el).val(),type:el.type});a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});}
continue;}
v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(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,type:el.type});}}
if(!semantic&&form.clk){var $input=$(form.clk),input=$input[0];n=input.name;if(n&&!input.disabled&&input.type=='image'){a.push({name:n,value:$input.val()});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(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=op.value;if(!v){v=(op.attributes&&op.attributes['value']&&!(op.attributes['value'].specified))?op.text:op.value;}
if(one){return v;}
a.push(v);}}
return a;}
return $(el).val();};$.fn.clearForm=function(includeHidden){return this.each(function(){$('input,select,textarea',this).clearFields(includeHidden);});};$.fn.clearFields=$.fn.clearInputs=function(includeHidden){var re=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(re.test(t)||tag=='textarea'||(includeHidden&&/hidden/.test(t))){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.selected=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').selected(false);}
this.selected=select;}});};$.fn.ajaxSubmit.debug=false;function log(){if(!$.fn.ajaxSubmit.debug)
return;var msg='[jquery.form] '+Array.prototype.join.call(arguments,'');if(window.console&&window.console.log){window.console.log(msg);}
else if(window.opera&&window.opera.postError){window.opera.postError(msg);}};})(jQuery);$j(document).ready(function(){$j('.inline_edit form').live('submit',function(evt){$j(this).ajaxSubmit();evt.preventDefault();return false;});$j('.inline_edit_cancel').live('click',function(evt){if(confirm('Are you sure you want to discard your changes?')){$j(evt.target).parents('tr.inline_edit').remove();}
evt.preventDefault();});$j('#browse_table form#schedule_publication_batch').submit(function(){var checked_batch=$j('#browse_table .batch_checkbox:checked')
$j(this).find('input.batch_item').remove().end().find('input#total_results').val(checked_batch.length);checked_batch.each(function(idx){$j('<input>').attr('type','hidden').attr('name','batch_item_'+idx).val($j(this).val()).appendTo($j('form#schedule_publication_batch'));});});$j('#browse_table .remote_edit_link').live('click',function(evt){var target_id=evt.target.id;var id_match;if(id_match=target_id.match(/\w+_(\d+)$/)){evt.preventDefault();$j.ajax({url:$j(evt.target).attr('href'),context:$j(evt.target).parents('tr'),success:function(data){if(!data.match(/window\.location/)){$j(this).after(data);}}});}});});
