var ncSearchForm=Class.create();ncSearchForm.prototype={initialize:function(query)
{this.options=Object.extend({apiKey:false,cseIdentifier:false,searchForm:undefined,searchLabel:'Search…',resultsContainer:undefined,waitingContainer:undefined,paging:true,count:10,collapse:false,resultsTemplate:'<li#{first}><a href="#{link}"#{onclick}><span class="heading">#{htmlTitle}</span><span class="url">#{link}</span><span class="summary">#{htmlSnippet}</span></a></li>'},arguments[1]||{});this.searchForm=$(this.options.searchForm);if(!this.searchForm){return;}
this.searchField=this.searchForm.down('input.search');this.searchField.writeAttribute('autocomplete','off');this.searchField.observe('focus',this.focus.bindAsEventListener(this));this.searchField.observe('blur',this.blur.bindAsEventListener(this));this.searchField.observe('keydown',this.keyDown.bindAsEventListener(this));this.searchForm.observe('submit',this.submit.bindAsEventListener(this));this.resultsContainer=$(this.options.resultsContainer);this.resultsList=this.resultsContainer.down('ol');this.waitingContainer=$(this.options.waitingContainer);this.searchCache=$H();if(query){this.searchField.setValue(query);this.search();}else{this.searchField.setValue(this.options.searchLabel);}
if(this.searchField.getValue()==this.options.searchLabel){this.searchField.addClassName('placeholder');}},keyDown:function(e)
{if(this.observer)
clearTimeout(this.observer);switch(e.keyCode){case Event.KEY_ESC:this.searchField.value='';this.close();break;case Event.KEY_RETURN:this.submit();e.stop();break;case Event.KEY_UP:this.prev();e.stop();break;case Event.KEY_DOWN:this.next();e.stop();break;default:this.observer=setTimeout(this.search.bind(this),1000);break;}},search:function()
{if(this.searchEmpty()){this.close();}else{if(!this.resultsContainer.visible()){this.showSearch();}else{this.performSearch();}}},showSearch:function()
{new Effect.BlindDown(this.resultsContainer,{duration:0.2,afterFinish:function(){this.performSearch();}.bind(this)});},performSearch:function(startIndex)
{if(this.searchEmpty()){return;}
if(!startIndex){startIndex=1;}
var value=this.searchField.getValue();if(this.currentValue==value&&startIndex<=this.currentIndex){return;}
this.currentValue=value;var searchCache=this.searchCache.get(this.currentValue+'.startIndex.'+startIndex);if(searchCache){this.populateSearch(searchCache);return;}
var cache={items:[],start:startIndex,count:0,total:0};new Ajax.JSONRequest('https://www.googleapis.com/customsearch/v1',{callbackParamName:'callback',parameters:{key:this.options.apiKey,cx:this.options.cseIdentifier,q:this.currentValue,num:this.options.count,start:startIndex},onSuccess:function(response){if(response.status===200){cache={items:response.responseJSON.items,start:parseInt(response.responseJSON.queries.request[0].startIndex),count:parseInt(response.responseJSON.queries.request[0].count),total:parseInt(response.responseJSON.queries.request[0].totalResults)}
this.currentIndex=startIndex+cache.count-1;this.searchCache.set(this.currentValue+'.startIndex.'+startIndex,cache);this.populateSearch(cache);}else{this.searchCache.set(this.currentValue+'.startIndex.'+startIndex,cache);this.populateSearch(cache);}}.bind(this),onFailure:function(response){this.searchCache.set(this.currentValue+'.startIndex.'+startIndex,cache);this.populateSearch(cache);}.bind(this)});},populateSearch:function(response)
{var more=this.resultsList.select('li.more');if(more.size()){more.invoke('remove');}
var results=new Array();if(response.items.length>0){if(response.items.length>this.options.count){response.items.length=this.options.count;}
var first=true;var resultsTemplate=new Template(this.options.resultsTemplate);response.items.each(function(result){result.first='';if(first&&response.start==1){result.first=' class="first"';first=false;}
result.onclick='';if(result.link.match(/\.pdf$/)){result.onclick=' onclick="window.open(this.href); return false;"';}
results.push(resultsTemplate.evaluate(result));});}else{results.push('<li class="first error">No results matched your query.</li>');}
if(this.options.paging&&response.total>(response.start+response.count-1)){results.push('<li class="more"><a class="clearfix" href="#show-more" rel="'+(response.start+response.count)+'"><span>Displaying first '+(response.start+response.count-1)+' results — click to show more results…</span><img src="'+_nc.baseUrl+'images/wait.gif" /></a></li>');}
if(response.start==1){this.resultsList.update(results.join(''));}else{this.resultsList.insert(results.join(''));}
more=this.resultsList.down('li.more');if(more){wait=more.down('img').setOpacity(0);more.down('a').observe('click',function(event){event.stop();more.down('a').stopObserving();more.down('a span').hide();new Effect.Opacity(wait,{to:1,duration:0.4});this.performSearch(response.start+response.count);}.bind(this));}
if(!this.resultsList.visible()){new Effect.BlindDown(this.resultsList,{duration:0.2});}
this.waitingContainer.absolutize();this.waitingContainer.hide();},focus:function(e)
{if(this.searchField.hasClassName('placeholder')){this.searchField.value='';this.searchField.removeClassName('placeholder');}else if(this.searchField.value!=''){this.search();}},blur:function(e)
{if(this.searchEmpty()){this.searchField.value='Search for it here…';this.searchField.addClassName('placeholder');}
this.closer=setTimeout(this.close.bind(this),400);},next:function()
{if(selected=this.resultsContainer.down('li.selected')){if(next=selected.next()){next.addClassName('selected');selected.removeClassName('selected');}}else{next=this.resultsContainer.down('li');if(!next.hasClassName('error')){next.addClassName('selected');}}},prev:function()
{if(selected=this.resultsContainer.down('li.selected')){selected.removeClassName('selected');if(previous=selected.previous()){previous.addClassName('selected');}}else{previous=this.resultsContainer.down('li');if(!previous.hasClassName('error')){previous.addClassName('selected');}}},close:function()
{if(!this.options.collapse){return;}
new Effect.BlindUp(this.resultsContainer,{duration:0.2,afterFinish:this.resetList.bind(this)});},submit:function()
{clearTimeout(this.closer);if(selected=this.resultsContainer.down('li.selected')){var href=selected.down('a').href;if(href.match(/^http:\/\/ncpic\.org\.au/)&&!href.match(/\.pdf$/)){window.location.href=href;}else{window.open(href);}}else{if(this.searchField.getValue()!=this.options.searchLabel&&!this.searchEmpty()){this.searchForm.submit();}}},resetList:function()
{if(this.currentValue!=this.searchField.getValue()){this.resultsList.update('');this.resultsList.hide();this.waitingContainer.relativize();this.waitingContainer.show();}},searchEmpty:function()
{if(this.searchField.getValue().strip()=='')
return true;return false;}};;var products;var totalPrice=0;var forceDelivery=false;function orderOnloads(productSet,pricing)
{products=productSet;if(pricing){var checkEventType=(Prototype.Browser.IE)?'click':'change';products.each(function(pair){if(pair.value.stockconstraint){return;}
var freeCheckbox=$(pair.key+'Free');var quantityInput=$(pair.key+'Quantity');if(freeCheckbox){quantityInput.observe('blur',calculateProductPrice);$(pair.key+'Free').observe(checkEventType,calculateProductPrice);}else{quantityInput.observe('blur',checkFreeProducts);}});$('deliverySame').observe(checkEventType,function(event){checkbox=event.element();if(checkbox.checked){if(Prototype.Browser.IE){$('deliveryAddress').hide();}else{Effect.BlindUp('deliveryAddress',{'duration':0.2});}
$('deliveryStreet').value='';$('deliveryTown').value='';$('deliveryState').selectedIndex=0;$('deliveryPostcode').value='';}else{if(Prototype.Browser.IE){$('deliveryAddress').show();}else{Effect.BlindDown('deliveryAddress',{'duration':0.2});}}});}else{products.each(function(pair){console.log(pair);if(pair.value.stockconstraint){return;}
$(pair.key+'Quantity').observe('keyup',checkFreeProducts);});}
if(billingStreet=$('billingStreet')){billingStreet.observe('blur',checkAddress);}
$('ncOrderForm').observe('submit',orderPost);}
function calculateProductPrice(event)
{var inputObj=event.element();if(inputObj.id.substr(inputObj.id.length-8,8)=='Quantity'){var theProductName=inputObj.id.slice(0,-8);}else if(inputObj.id.substr(inputObj.id.length-4,4)=='Free'){var theProductName=inputObj.id.slice(0,-4);}
var theProduct=products.get(theProductName);var quantityObject=$(theProductName+'Quantity');var priceObject=$(theProductName+'Price');var freeObject=$(theProductName+'Free');var freeAmount=0;if(freeObject.checked){freeAmount=theProduct.free;}
var price=0;var priceFormatted='$0.00';if(quantityObject.value){var cleanValue=quantityObject.value.sub(/[^0-9]/,'').sub(/^0+/,'');if(quantityObject.value!=cleanValue){quantityObject.value=cleanValue;}}
if(!isNaN(quantityObject.value)&&quantityObject.value>0&&quantityObject.value>freeAmount){price=theProduct.price*(quantityObject.value-freeAmount);if(price.toFixed){priceFormatted='$'+price.toFixed(2);}else{priceFormatted='$'+price;}}
if(!isNaN(quantityObject.value)&&quantityObject.value>0){theProduct.quantity=quantityObject.value;}else{theProduct.quantity=0;}
priceObject.update(priceFormatted);theProduct.total=price;updateTotalPrice();}
function updateTotalPrice()
{var totalPrice=0;var agency=false;products.each(function(pair){var product=$H(pair.value);if(product.get('total')){totalPrice+=product.get('total');}
if(product.get('quantity')>0&&product.get('agency')){agency=true;}});agencyToggle(agency);if(totalPrice.toFixed){priceFormatted='$'+totalPrice.toFixed(2);}else{priceFormatted='$'+totalPrice;}
$('totalPrice').value=priceFormatted;$('totalPriceDisplay').update(priceFormatted);}
function checkFreeProducts(event)
{var inputObj=event.element();var productName=inputObj.id.slice(0,-8);var product=$H(products.get(productName));var errorMessage=inputObj.up('div.notice');var freeAmount=product.get('free');if(inputObj.value){var cleanValue=inputObj.value.sub(/[^0-9]/,'').sub(/^0+/,'');if(inputObj.value!=cleanValue){inputObj.value=cleanValue;}}
var labelObject=$('ncOrderForm').down('label[for="'+productName+'"]')||$(productName+'Label');if(!isNaN(inputObj.value)&&inputObj.value>0&&inputObj.value>freeAmount){if(!errorMessage){labelObject.up().addClassName('notice');var error=generateMessage('You can only order '+freeAmount+' of this item. <span class="automatic">The quantity has been automatically adjusted.</span>',{type:'notice',classNames:'formAlert'});labelObject.insert({before:error});error.addClassName('quantity');new Effect.BlindDown(error,{duration:0.5});}
inputObj.value=freeAmount;}else{if(errorMessage){labelObject.up().removeClassName('notice');var error=labelObject.up().down('div.formAlert.quantity');if(error){new Effect.BlindUp(error,{duration:0.5,afterFinish:function(){error.remove();}});}}}
if(product.get('agency')){var agency=false;if(!isNaN(inputObj.value)&&inputObj.value>0){agency=true;}
agencyToggle(agency);}}
function agencyToggle(agency)
{var container=$('agencyDetails');if(!container)return;var agencyVisible=container.visible();if(agency&&!agencyVisible){if(Prototype.Browser.IE){container.show();}else{Effect.BlindDown(container,{'duration':0.2});}
$('agencyName').observe('blur',checkAgencyName);var checkEventType=(Prototype.Browser.IE)?'click':'change';$('agencyTrainingCheck').observe(checkEventType,checkAgencyTraining);}else if(!agency&&agencyVisible){if(Prototype.Browser.IE){container.hide();$('agencyTrainingDetailsField').hide();}else{Effect.BlindUp('agencyDetails',{'duration':0.2});Effect.BlindUp('agencyTrainingDetailsField',{'duration':0.2});}
$('agencyName').value='';$('agencyName').stopObserving();$('agencyTargetNeedsCheck').checked=false;$('agencyStaff').select('input[type="checkbox"]').each(function(c){c.checked=false;});$('agencyTrainingCheck').checked=false;$('agencyTrainingDetails').value='';$('agencyTrainingCheck').stopObserving();$('agencyAgreementCheck').checked=false;}}
function checkAgencyName(event)
{var inputObj=event.element();var t=$('organisationName');if(inputObj.value&&t.value==''){t.value=inputObj.value;}}
function checkAgencyTraining(event)
{var inputObj=event.element();var t=$('agencyTrainingDetailsField');var tv=t.visible();if(inputObj.checked&&!tv){if(Prototype.Browser.IE){t.show();}else{Effect.BlindDown(t,{'duration':0.2});}}else if(!inputObj.checked&&tv){if(Prototype.Browser.IE){t.hide();}else{Effect.BlindUp(t,{'duration':0.2});}
$('agencyTrainingDetails').value='';}}
var _errorMessage=new Element('div');var _errorParagraph=new Element('p');_errorMessage.insert(_errorParagraph);function generateMessage(message)
{var options=Object.extend({show:false,type:'error',className:'formAlert'},arguments[1]||{});var errorMessage=_errorMessage.cloneNode(true);errorMessage.down('p').insert(message);if(options.type){errorMessage.down('p').addClassName(options.type);}
if(options.className){errorMessage.addClassName(options.className);}
if(options.show){errorMessage.show();}else{errorMessage.hide();}
return errorMessage;}
function orderPost(event)
{var formObject=event.element();var formParameters=formObject.serialize(true);formParameters.ajax='1 ';var failureCallback=function()
{formObject.select('.formMessage:not(.persistent), .formAlert').invoke('remove');window.scrollTo(0,0);var message='There was a communication error with the server, the order attempt has failed.';var error=generateMessage(message,{type:json.alertClass,className:'formMessage'});formObject.down('div.note').insert({after:error});new Effect.Parallel([new Effect.BlindDown(error,{sync:true}),new Effect.Appear(error,{sync:true})],{duration:0.3});formObject.fire('submit:finished');}
new Ajax.Request(formObject.action,{parameters:formParameters,onSuccess:function(transport,json){formObject.select('.formMessage:not(.persistent), .formAlert').invoke('remove');formObject.select('div.label','label').each(function(labelObject){labelObject.up().removeClassName('error').removeClassName('notice');});window.scrollTo(0,0);if(json.showDelivery&&!$('deliveryAddress').visible()){new Effect.BlindDown('deliveryAddress',{duration:0.2});$('deliverySame').checked=false;forceDelivery=true;}
var error=generateMessage(json.alert,{type:json.alertClass,className:'formMessage'});formObject.down('div.note').insert({after:error});new Effect.Parallel([new Effect.BlindDown(error,{sync:true}),new Effect.Appear(error,{sync:true})],{duration:0.3});if(json.errors){$H(json.errors).each(function(pair){var labelObject=formObject.down('label[for="'+pair.key+'"]')||$(pair.key+'Label');if(labelObject){labelObject.up().addClassName('error');var error=generateMessage(pair.value,{type:'error',classNames:'formAlert'});labelObject.insert({before:error});new Effect.Parallel([new Effect.BlindDown(error,{sync:true}),new Effect.Appear(error,{sync:true})],{duration:0.3});}});}
if(json.curlReturn){alert(json.curlReturn);}
formObject.fire('submit:finished');},onFailure:failureCallback,on404:failureCallback});}
function checkAddress(event)
{var billingAddressObj=event.element();var billingAddress=billingAddressObj.getValue().strip();var poBox=billingAddress.match(/^P[.\-\/\\\s]*O[.\s]*Box/gi);if(!poBox){if(forceDelivery&&$('deliveryAddress').visible()){new Effect.BlindUp('deliveryAddress',{duration:0.2});$('deliverySame').checked=true;forceDelivery=false;}
return;}
if(!$('deliveryAddress').visible()){new Effect.BlindDown('deliveryAddress',{duration:0.2});$('deliverySame').checked=false;forceDelivery=true;}}
function showSOTGForm(event)
{event.stop();var overlay=$('ncContent').down('.overlay');var orderForm=$('ncContent').down('div.orderForm');new Effect.Parallel([new Effect.Appear(overlay,{to:0.7,sync:true}),new Effect.Appear(orderForm,{sync:true})],{duration:0.4});}
function hideSOTGForm()
{var overlay=$('ncContent').down('.overlay');var orderForm=$('ncContent').down('div.orderForm');new Effect.Parallel([new Effect.Fade(overlay,{sync:true}),new Effect.Fade(orderForm,{sync:true})],{duration:0.4});}
function stayOffTheGrass(form,productSet)
{var form=$(form);var currentFieldset=form.down('fieldset');products=productSet;products.each(function(pair){if(pair.value.stockconstraint){return;}
$(pair.key+'Quantity').observe('keyup',checkFreeProducts);});var nextButton=form.down('input.next');var prevButton=form.down('button.previous');var nextFieldset=function(event){event.stop();var valid=true;currentFieldset.select('.error').invoke('remove');var nextFieldset=currentFieldset.next('fieldset');if(currentFieldset.hasClassName('products')){var validate=products.find(function(pair){if(pair.value.stockconstraint){return;}
var input=$(pair.key+'Quantity');var value=$F(input).strip();if(!value){return false;}
value=parseInt(value);if(isNaN(value)||value<1||value>5){return false;}
return true;});if(!validate){valid=false;var errorMessage=new Element('p',{className:'error'}).insert('You haven&rsquo;t ordered anything.').hide();currentFieldset.insert({top:errorMessage});new Effect.BlindDown(errorMessage,{duration:0.2});}}else if(nextFieldset.hasClassName('submit')){var value=1;valid=false;form.request({parameters:{ajax:value+' '},onSuccess:function(transport,json){currentFieldset.hide();form.down('fieldset.submit').hide();var resultContainer=form.down('fieldset.result');var messageContainer=resultContainer.down('.formMessage');resultContainer.down('legend').update(json.alertTitle);var message=new Element('p',{className:json.alertClass}).insert(json.alert);messageContainer.insert(message);resultContainer.show();resultContainer.down('.close').observe('click',function(event){event.stop();hideSOTGForm();});}});}else{currentFieldset.select('.mandatory').each(function(field){var label=field.down('.label');var fieldName=label.innerHTML.stripTags().strip();fieldName=fieldName.substring(1,fieldName.length).toLowerCase();var vowelStart=['a','e','i','o','u'].find(function(vowel){return fieldName.startsWith(vowel);});var article=(vowelStart)?'an ':'a ';if(field.hasClassName('radios')){var chosen=field.select('input').find(function(i){return i.checked});if(!chosen){valid=false;var errorMessage=new Element('span',{className:'error'}).insert('You must choose '+article+fieldName+'.').hide();label.insert({before:errorMessage});new Effect.BlindDown(errorMessage,{duration:0.2});}}else{var input=field.down('input, textarea, select');var value=$F(input).strip();if(!value){valid=false;var errorMessage=new Element('span',{className:'error'}).insert('You must supply '+article+fieldName.toLowerCase()+'.').hide();label.insert({before:errorMessage});new Effect.BlindDown(errorMessage,{duration:0.2});}}});}
if(valid){if(nextFieldset.hasClassName('details')){nextButton.up('.field').hide();nextButton.up('fieldset').down('div.submit').show();}
currentFieldset.hide();nextFieldset.show();if(!prevButton.visible()){prevButton.show();}
currentFieldset=nextFieldset;var fieldsetElements=Form.getElements(currentFieldset).findAll(function(element){return'hidden'!=element.type&&!element.disabled;});var firstByIndex=fieldsetElements.findAll(function(element){return element.hasAttribute('tabIndex')&&element.tabIndex>=0;}).sortBy(function(element){return element.tabIndex}).first();var firstElement=(firstByIndex)?firstByIndex:fieldsetElements.find(function(element){return /^(?:input|select|textarea)$/i.test(element.tagName);});if(firstElement){firstElement.activate();}}}
var previousFieldset=function(event){event.stop();currentFieldset.select('.error').invoke('remove');var previousFieldset=currentFieldset.previous('fieldset');currentFieldset.hide();previousFieldset.show();if(previousFieldset.hasClassName('first')){prevButton.hide();}
currentFieldset=previousFieldset;}
var cancelButton=form.down('.cancel');cancelButton.observe('click',function(event){event.stop();hideSOTGForm();});form.observe('submit',nextFieldset);nextButton.observe('click',nextFieldset);prevButton.observe('click',previousFieldset);}
