/*
 * jQuery validation plug-in 1.5.5
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){$.extend($.fn,{validate:function(options){if(!this.length){options&&options.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return;}var validator=$.data(this[0],'validator');if(validator){return validator;}validator=new $.validator(options,this[0]);$.data(this[0],'validator',validator);if(validator.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){validator.cancelSubmit=true;});if(validator.settings.submitHandler){this.find("input, button").filter(":submit").click(function(){validator.submitButton=this;});}this.submit(function(event){if(validator.settings.debug)event.preventDefault();function handle(){if(validator.settings.submitHandler){if(validator.submitButton){var hidden=$("<input type='hidden'/>").attr("name",validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);}validator.settings.submitHandler.call(validator,validator.currentForm);if(validator.submitButton){hidden.remove();}return false;}return true;}if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();}if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;}return handle();}else{validator.focusInvalid();return false;}});}return validator;},valid:function(){if($(this[0]).is('form')){return this.validate().form();}else{var valid=true;var validator=$(this[0].form).validate();this.each(function(){valid&=validator.element(this);});return valid;}},removeAttrs:function(attributes){var result={},$element=this;$.each(attributes.split(/\s/),function(index,value){result[value]=$element.attr(value);$element.removeAttr(value);});return result;},rules:function(command,argument){var element=this[0];if(command){var settings=$.data(element.form,'validator').settings;var staticRules=settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;if(argument.messages)settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;}var filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}}var data=$.validator.normalizeRules($.extend({},$.validator.metadataRules(element),$.validator.classRules(element),$.validator.attributeRules(element),$.validator.staticRules(element)),element);if(data.required){var param=data.required;delete data.required;data=$.extend({required:param},data);}return data;}});$.extend($.expr[":"],{blank:function(a){return!$.trim(a.value);},filled:function(a){return!!$.trim(a.value);},unchecked:function(a){return!a.checked;}});$.validator=function(options,form){this.settings=$.extend({},$.validator.defaults,options);this.currentForm=form;this.init();};$.validator.format=function(source,params){if(arguments.length==1)return function(){var args=$.makeArray(arguments);args.unshift(source);return $.validator.format.apply(this,args);};if(arguments.length>2&&params.constructor!=Array){params=$.makeArray(arguments).slice(1);}if(params.constructor!=Array){params=[params];}$.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),n);});return source;};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,element,this.settings.errorClass,this.settings.validClass);this.errorsFor(element).hide();}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element){if(element.name in this.submitted||element==this.lastElement){this.element(element);}},onclick:function(element){if(element.name in this.submitted)this.element(element);},highlight:function(element,errorClass,validClass){$(element).addClass(errorClass).removeClass(validClass);},unhighlight:function(element,errorClass,validClass){$(element).removeClass(errorClass).addClass(validClass);}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",dateDE:"Bitte geben Sie ein gültiges Datum ein.",number:"Please enter a valid number.",numberDE:"Bitte geben Sie eine Nummer ein.",digits:"Please enter only digits",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.validator.format("Please enter no more than {0} characters."),minlength:$.validator.format("Please enter at least {0} characters."),rangelength:$.validator.format("Please enter a value between {0} and {1} characters long."),range:$.validator.format("Please enter a value between {0} and {1}."),max:$.validator.format("Please enter a value less than or equal to {0}."),min:$.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={});$.each(this.settings.groups,function(key,value){$.each(value.split(/\s/),function(index,name){groups[name]=key;});});var rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){var validator=$.data(this[0].form,"validator");validator.settings["on"+event.type]&&validator.settings["on"+event.type].call(validator,this[0]);}$(this.currentForm).delegate("focusin focusout keyup",":text, :password, :file, select, textarea",delegate).delegate("click",":radio, :checkbox",delegate);if(this.settings.invalidHandler)$(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())$(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);}return this.valid();},element:function(element){element=this.clean(element);this.lastElement=element;this.prepareElement(element);this.currentElements=$(element);var result=this.check(element);if(result){delete this.invalid[element.name];}else{this.invalid[element.name]=true;}if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers);}this.showErrors();return result;},showErrors:function(errors){if(errors){$.extend(this.errorMap,errors);this.errorList=[];for(var name in errors){this.errorList.push({message:errors[name],element:this.findByName(name)[0]});}this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors();},resetForm:function(){if($.fn.resetForm)$(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass);},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0;for(var i in obj)count++;return count;},hideErrors:function(){this.addWrapper(this.toHide).hide();},valid:function(){return this.size()==0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus();}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name==lastActive.name;}).length==1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&validator.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in rulesCache||!validator.objectLength($(this).rules()))return false;rulesCache[this.name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){return $(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext);},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);this.formSubmitted=false;this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},check:function(element){element=this.clean(element);if(this.checkable(element)){element=this.findByName(element.name)[0];}var rules=$(element).rules();var dependencyMismatch=false;for(method in rules){var rule={method:method,parameters:rules[method]};try{var result=$.validator.methods[method].call(this,element.value.replace(/\r/g,""),element,rule.parameters);if(result=="dependency-mismatch"){dependencyMismatch=true;continue;}dependencyMismatch=false;if(result=="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;}if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){this.settings.debug&&window.console&&console.log("exception occured when checking element "+element.id
+", check the '"+rule.method+"' method");throw e;}}if(dependencyMismatch)return;if(this.objectLength(rules))this.successList.push(element);return true;},customMetaMessage:function(element,method){if(!$.metadata)return;var meta=this.settings.meta?$(element).metadata()[this.settings.meta]:$(element).metadata();return meta&&meta.messages&&meta.messages[method];},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor==String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined)return arguments[i];}return undefined;},defaultMessage:function(element,method){return this.findDefined(this.customMessage(element.name,method),this.customMetaMessage(element,method),!this.settings.ignoreTitle&&element.title||undefined,$.validator.messages[method],"<strong>Warning: No message defined for "+element.name+"</strong>");},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule.method);if(typeof message=="function")message=message.call(this,rule.parameters,element);this.errorList.push({message:message,element:element});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper)toToggle=toToggle.add(toToggle.parent(this.settings.wrapper));return toToggle;},defaultShowErrors:function(){for(var i=0;this.errorList[i];i++){var error=this.errorList[i];this.settings.highlight&&this.settings.highlight.call(this,error.element,this.settings.errorClass,this.settings.validClass);this.showLabel(error.element,error.message);}if(this.errorList.length){this.toShow=this.toShow.add(this.containers);}if(this.settings.success){for(var i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}}if(this.settings.unhighlight){for(var i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass,this.settings.validClass);}}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var label=this.errorsFor(element);if(label.length){label.removeClass().addClass(this.settings.errorClass);label.attr("generated")&&label.html(message);}else{label=$("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(element),generated:true}).addClass(this.settings.errorClass).html(message||"");if(this.settings.wrapper){label=label.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();}if(!this.labelContainer.append(label).length)this.settings.errorPlacement?this.settings.errorPlacement(label,$(element)):label.insertAfter(element);}if(!message&&this.settings.success){label.text("");typeof this.settings.success=="string"?label.addClass(this.settings.success):this.settings.success(label);}this.toShow=this.toShow.add(label);},errorsFor:function(element){return this.errors().filter("[for='"+this.idOrName(element)+"']");},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},checkable:function(element){return/radio|checkbox/i.test(element.type);},findByName:function(name){var form=this.currentForm;return $(document.getElementsByName(name)).map(function(index,element){return element.form==form&&element.name==name&&element||null;});},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case'select':return $("option:selected",element).length;case'input':if(this.checkable(element))return this.findByName(element.name).filter(':checked').length;}return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param,element){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){return!$.validator.methods.required.call(this,$.trim(element.value),element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[element.name];if(valid&&this.pendingRequest==0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();}else if(!valid&&this.pendingRequest==0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);}},previousValue:function(element){return $.data(element,"previousValue")||$.data(element,"previousValue",previous={old:null,valid:true,message:this.defaultMessage(element,"remote")});}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(className,rules){className.constructor==String?this.classRuleSettings[className]=rules:$.extend(this.classRuleSettings,className);},classRules:function(element){var rules={};var classes=$(element).attr('class');classes&&$.each(classes.split(' '),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});return rules;},attributeRules:function(element){var rules={};var $element=$(element);for(method in $.validator.methods){var value=$element.attr(method);if(value){rules[method]=value;}}if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;}return rules;},metadataRules:function(element){if(!$.metadata)return{};var meta=$.data(element.form,'validator').settings.meta;return meta?$(element).metadata()[meta]:$(element).metadata();},staticRules:function(element){var rules={};var validator=$.data(element.form,'validator');if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};}return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;}if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;}if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)?parameter(element):parameter;});$.each(['minlength','maxlength','min','max'],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(['rangelength','range'],function(){if(rules[this]){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}});if($.validator.autoCreateRanges){if(rules.min&&rules.max){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;}if(rules.minlength&&rules.maxlength){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}}if(rules.messages){delete rules.messages}return rules;},normalizeRule:function(data){if(typeof data=="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;}return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message||$.validator.messages[name];if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element))return"dependency-mismatch";switch(element.nodeName.toLowerCase()){case'select':var options=$("option:selected",element);return options.length>0&&(element.type=="select-multiple"||($.browser.msie&&!(options[0].attributes['value'].specified)?options[0].text:options[0].value).length>0);case'input':if(this.checkable(element))return this.getLength(value,element)>0;default:return $.trim(value).length>0;}},remote:function(value,element,param){if(this.optional(element))return"dependency-mismatch";var previous=this.previousValue(element);if(!this.settings.messages[element.name])this.settings.messages[element.name]={};this.settings.messages[element.name].remote=typeof previous.message=="function"?previous.message(value):previous.message;param=typeof param=="string"&&{url:param}||param;if(previous.old!==value){previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax($.extend(true,{url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){var valid=response===true;if(valid){var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}else{var errors={};errors[element.name]=previous.message=response||validator.defaultMessage(element,"remote");validator.showErrors(errors);}previous.valid=valid;validator.stopRequest(element,valid);}},param));return"pending";}else if(this.pending[element.name]){return"pending";}return previous.valid;},minlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)<=param;},rangelength:function(value,element,param){var length=this.getLength($.trim(value),element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},email:function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);},url:function(value,element){return this.optional(element)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value));},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);},dateDE:function(value,element){return this.optional(element)||/^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);},number:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);},numberDE:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},creditcard:function(value,element){if(this.optional(element))return"dependency-mismatch";if(/[^0-9-]+/.test(value))return false;var nCheck=0,nDigit=0,bEven=false;value=value.replace(/\D/g,"");for(n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);var nDigit=parseInt(cDigit,10);if(bEven){if((nDigit*=2)>9)nDigit-=9;}nCheck+=nDigit;bEven=!bEven;}return(nCheck%10)==0;},accept:function(value,element,param){param=typeof param=="string"?param.replace(/,/g,'|'):"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){return value==$(param).val();}}});$.format=$.validator.format;})(jQuery);;(function($){var ajax=$.ajax;var pendingRequests={};$.ajax=function(settings){settings=$.extend(settings,$.extend({},$.ajaxSettings,settings));var port=settings.port;if(settings.mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}return(pendingRequests[port]=ajax.apply(this,arguments));}return ajax.apply(this,arguments);};})(jQuery);;(function($){$.each({focus:'focusin',blur:'focusout'},function(original,fix){$.event.special[fix]={setup:function(){if($.browser.msie)return false;this.addEventListener(original,$.event.special[fix].handler,true);},teardown:function(){if($.browser.msie)return false;this.removeEventListener(original,$.event.special[fix].handler,true);},handler:function(e){arguments[0]=$.event.fix(e);arguments[0].type=fix;return $.event.handle.apply(this,arguments);}};});$.extend($.fn,{delegate:function(type,delegate,handler){return this.bind(type,function(event){var target=$(event.target);if(target.is(delegate)){return handler.apply(target,arguments);}});},triggerEvent:function(type,target){return this.triggerHandler(type,[$.event.fix({type:type,target:target})]);}})})(jQuery);/****************************************************************************
  jpost plugin for jQuery
  http://www.codigomanso.com/projects/jpost

  Written by Pau Sanchez (contact@pausanchez.com) for jimi PHP Framework
****************************************************************************/

;(function() {
  var _jpost_settings = {
    data          : null, // extra data to be sent
    image         : null, // '/themes/default/images/loading.gif',
    normalize     : true, // normalize checkboxes?
    onComplete    : null,
    afterComplete : null,
    msgbox        : null, // where should the messages be shown?
    timelapse     : 5000
  };
  
  // this function returns or sets the current settings
  window.jQuery.jpostSettings = function() {
    var old_settings = _jpost_settings;
    _jpost_settings  = $.extend (_jpost_settings, arguments[0] || {});
    return old_settings;
  };
})();

/**
 * This is equivalent to serialize function BUT it appends ALL checkboxes
 * setting the value of 1 when are checked and 0 when unchecked.
 */
jQuery.fn.jserialize = function () {
  var options = $.extend ({
    data          : null, // extra data to be sent
    normalize     : true  // normalize checkboxes?
  }, arguments[0] || {});  

  var serialized = this.serialize();

  // append normal data
  if (options.normalize) {
    $(this).find(':checkbox').each (function() {
      var tofind    = $(this).attr('name') + "=" + $(this).val();
      var toreplace = $(this).attr('name') + "=" + (this.checked ? '1' : '0');
      
      if (this.checked)   { serialized = serialized.replace (tofind, toreplace); }
      else                { serialized += "&" + toreplace; } 
    });
  }

  // append extra data (if any)
  if (options.data != null) {
    if (serialized) serialized += "&";
    serialized += jQuery.param(options.data);
  }

  return serialized;
};

/**
 * This function sends an AJAX request and waits for a response
 *
 * The return value will be true when the normal submit should be
 * executed and false when the normal form submit should be avoided
 * This return value could be directly passed as a return value to
 * the submit event
 */
jQuery.fn.jpost = function() {
  var options = $.extend (jQuery.jpostSettings(), arguments[0] || {});

  // Handle each selector
  var form   = $(this);
  var submit = form.find (':submit');
  var added_image = null;

  if (options.image != null) {
    submit.hide();
    added_image = $('<img src="' + options.image + '" />');
    submit.after (added_image);
  }
  else {
    submit.attr ('disabled', true);
  }

  // function to be executed when response is received
  // This function restores 'submit' button and calls onComplete callback
  var handle_json_response = function(json_response, textStatus)
  {
    if (added_image != null) { added_image.remove(); }

    if (options.onComplete != null) {
      options.onComplete (json_response, form);
      submit.removeAttr ('disabled');
      submit.show();
    }
    else {
      submit.removeAttr ('disabled');
      submit.show();

      if (('msg' in json_response) && (options.msgbox != null)) {
        $(options.msgbox)
          .html (json_response.msg)
          .stop(true)
          .removeClass('jpost-ok jpost-error')
          .hide()
          .fadeIn();

        // add jpost-ok or jpost-error classes depending on the response of the server
        if ('ok' in json_response) { 
          if (json_response.ok)  { $(options.msgbox).addClass ('jpost-ok'); }
          else                   { $(options.msgbox).addClass ('jpost-error'); }
        }

        // clear the previous timeout(just in case)
        if ($(options.msgbox).data ('__jpost-timeout-id') != undefined) 
          clearTimeout ($(options.msgbox).data ('__jpost-timeout-id'));

        var timeoutID = setTimeout (function() { $(options.msgbox).fadeOut(); }, options.timelapse);
        $(options.msgbox).data ('__jpost-timeout-id', timeoutID);
      }
    }

    if (options.afterComplete != null) {
      options.afterComplete (json_response, form);
    }
  };

  // DECISION: normal ajax submit or use a hidden iframe?
  //  - iframe trick will ONLY be used if form enctype is 'multiplart/form-data' 
  //    AND the user has selected one or more files
  //
  //  - any other cases data will be sent using standard ajax
  //     - this includes if there are input "file" but the user
  //       has not selected any file
  var doIframeRequest = 
    (form.attr ('enctype') == 'multipart/form-data') &&
    ((form.find (':file[value!=""]').length > 0)); 

  if (doIframeRequest)
  {
    // Seems that the user is trying to send some images
    // Let's send the whole form without doing a page refresh :)
    var frameName = 'jpost_iframe_' + ((new Date()).getTime());
    var iframe    = $('<iframe name="' + frameName + '" style="display:none;"></iframe>').hide().appendTo('body');
    var orgTarget = form.attr ('target');
    form.attr ('target', frameName);

    // update checkboxes to send 0 or 1
    // Trick: disable checkboxes before submit, and append hidden fields using the same name as the checkboxes
    if (options.normalize) {
      form.find(':checkbox').each (function() {
        var disabled = $(this).attr ('disabled');
        $(this).data ('jpost-original-disabled', disabled);
        $(this).attr ('disabled', 'disabled');
        
        if (disabled == 'undefined' || !disabled) {
          form.append ($('<input type="hidden" name="' + $(this).attr ('name') + '" value="' + (this.checked ? '1' : '0') + '"/>'));
        }
      });
    }

    // this is not very clean, but it is a way to let know the server this call should be treated as ajax
    $('<input type="hidden" name="XMLHttpRequest" value="1" />').appendTo (form);

    // append extra data as input fields
    if (options.data != null) {
      for (i in options.data)
        $('<textarea style="display: none;" name="' + i + '">' + options.data[i] + '</textarea>').appendTo (form);
    }

    iframe.load (function() {
      var response = iframe.contents().find('body').text();
      if (response.length == 0) response = '{}';
      try       { eval ("var json_response = " + response + ";"); }
      catch (e) { var json_response = {ok : false, msg : "Error in data returned by the server" }; }
      handle_json_response (json_response, 'undefined');
      
      // restore original form
      if (orgTarget != 'undefined') {
        form.attr ('target', orgTarget);
      }

      // restore checkboxes and remove hidden fields
      if (options.normalize) {
        form.find(':checkbox').each (function() {
          var disabled = $(this).data ('jpost-original-disabled');
          $(this).removeData ('jpost-original-disabled');

          if (disabled == 'undefined' || !disabled) {
            // remove the hidden fields that have been created
            form.find ('input[name="' +$(this).attr ('name') + '"]:hidden').remove();
            $(this).removeAttr ('disabled');
          }
        });
      }
      
      // remove extra hidden input fields
      if (options.data != null) {
        for (i in options.data) { form.find ("input[name=" + i +"]").remove(); }
      }

      // remove the hidden XMLHttpRequest...
      form.find ("input[name=XMLHttpRequest]:hidden").remove();

      // the timeout is to make all browsers stop the "loading iframe" animation
      setTimeout (function() { iframe.remove(); }, 100);
    });

    return true;
  }
  // use a normal AJAX post!
  else {
    $.ajax ({
      url      : form.attr ('action'),
      type     : 'POST',
      cache    : false,
      data     : form.jserialize({data : options.data, normalize : options.normalize}),
      dataType : 'json',
      success  : handle_json_response,
      error    : function (XMLHttpRequest, textStatus, errorThrown) {
        var data = {'ok' : false, 'error' : true, 'msg' : 'Error in data received from server'};
        handle_json_response (data, textStatus);
      }
    });
  }
  return false;
}

/**
 * jMakeAsync ([fn], {params})
 * This function transform a normal FORM into an asynchronous one
 * 
 * fn(response)   is the function to be called once the response 
 *                from the server has been received
 *
 * params         are the same as jpost
 */
jQuery.fn.jMakeAsync = function() {
  var options = $.extend ({
    onComplete : arguments[0]
  }, arguments[1] || {});

  return this.filter ('form').each (function () {
    var form = $(this);
    form.submit (function () { return form.jpost (options); });
  });
}

// ----------------------------------------------------------------------------
// markItUp! Universal MarkUp Engine, JQuery plugin
// v 1.1.5
// Dual licensed under the MIT and GPL licenses.
// ----------------------------------------------------------------------------
// Copyright (C) 2007-2008 Jay Salvat
// http://markitup.jaysalvat.com/
// ----------------------------------------------------------------------------
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(3($){$.24.T=3(f,g){E k,v,A,F;v=A=F=7;k={C:\'\',12:\'\',U:\'\',1j:\'\',1A:8,25:\'26\',1k:\'~/2Q/1B.1C\',1b:\'\',27:\'28\',1l:8,1D:\'\',1E:\'\',1F:{},1G:{},1H:{},1I:{},29:[{}]};$.V(k,f,g);2(!k.U){$(\'2R\').1c(3(a,b){1J=$(b).14(0).2S.2T(/(.*)2U\\.2V(\\.2W)?\\.2X$/);2(1J!==2a){k.U=1J[1]}})}4 G.1c(3(){E d,u,15,16,p,H,L,P,17,1m,w,1n,M,18;d=$(G);u=G;15=[];18=7;16=p=0;H=-1;k.1b=1d(k.1b);k.1k=1d(k.1k);3 1d(a,b){2(b){4 a.W(/("|\')~\\//g,"$1"+k.U)}4 a.W(/^~\\//,k.U)}3 2b(){C=\'\';12=\'\';2(k.C){C=\'C="\'+k.C+\'"\'}l 2(d.1K("C")){C=\'C="T\'+(d.1K("C").2c(0,1).2Y())+(d.1K("C").2c(1))+\'"\'}2(k.12){12=\'N="\'+k.12+\'"\'}d.1L(\'<z \'+12+\'></z>\');d.1L(\'<z \'+C+\' N="T"></z>\');d.1L(\'<z N="2Z"></z>\');d.2d("2e");17=$(\'<z N="30"></z>\').2f(d);$(1M(k.29)).1N(17);1m=$(\'<z N="31"></z>\').1O(d);2(k.1l===8&&$.X.32!==8){1l=$(\'<z N="33"></z>\').1O(d).1e("34",3(e){E h=d.2g(),y=e.2h,1o,1p;1o=3(e){d.2i("2g",35.36(20,e.2h+h-y)+"37");4 7};1p=3(e){$("1C").1P("2j",1o).1P("1q",1p);4 7};$("1C").1e("2j",1o).1e("1q",1p)});1m.2k(1l)}d.2l(1Q).38(1Q);d.1e("1R",3(e,a){2(a.1r!==7){14()}2(u===$.T.2m){Y(a)}});d.1f(3(){$.T.2m=G})}3 1M(b){E c=$(\'<Z></Z>\'),i=0;$(\'B:2n > Z\',c).2i(\'39\',\'q\');$.1c(b,3(){E a=G,t=\'\',1s,B,j;1s=(a.19)?(a.1S||\'\')+\' [3a+\'+a.19+\']\':(a.1S||\'\');19=(a.19)?\'2o="\'+a.19+\'"\':\'\';2(a.2p){B=$(\'<B N="3b">\'+(a.2p||\'\')+\'</B>\').1N(c)}l{i++;2q(j=15.6-1;j>=0;j--){t+=15[j]+"-"}B=$(\'<B N="2r 2r\'+t+(i)+\' \'+(a.3c||\'\')+\'"><a 3d="" \'+19+\' 1s="\'+1s+\'">\'+(a.1S||\'\')+\'</a></B>\').1e("3e",3(){4 7}).2s(3(){4 7}).1q(3(){2(a.2t){3f(a.2t)()}Y(a);4 7}).2n(3(){$(\'> Z\',G).3g();$(D).3h(\'2s\',3(){$(\'Z Z\',17).2u()})},3(){$(\'> Z\',G).2u()}).1N(c);2(a.2v){15.3i(i);$(B).2d(\'3j\').2k(1M(a.2v))}}});15.3k();4 c}3 2w(c){2(c){c=c.3l();c=c.W(/\\(\\!\\(([\\s\\S]*?)\\)\\!\\)/g,3(x,a){E b=a.1T(\'|!|\');2(F===8){4(b[1]!==2x)?b[1]:b[0]}l{4(b[1]===2x)?"":b[0]}});c=c.W(/\\[\\!\\[([\\s\\S]*?)\\]\\!\\]/g,3(x,a){E b=a.1T(\':!:\');2(18===8){4 7}1U=3m(b[0],(b[1])?b[1]:\'\');2(1U===2a){18=8}4 1U});4 c}4""}3 I(a){2($.3n(a)){a=a(P)}4 2w(a)}3 1g(a){J=I(L.J);1a=I(L.1a);Q=I(L.Q);O=I(L.O);2(Q!==""){q=J+Q+O}l 2(m===\'\'&&1a!==\'\'){q=J+1a+O}l{q=J+(a||m)+O}4{q:q,J:J,Q:Q,1a:1a,O:O}}3 Y(a){E b,j,n,i;P=L=a;14();$.V(P,{1t:"",U:k.U,u:u,m:(m||\'\'),p:p,v:v,A:A,F:F});I(k.1D);I(L.1D);2(v===8&&A===8){I(L.3o)}$.V(P,{1t:1});2(v===8&&A===8){R=m.1T(/\\r?\\n/);2q(j=0,n=R.6,i=0;i<n;i++){2($.3p(R[i])!==\'\'){$.V(P,{1t:++j,m:R[i]});R[i]=1g(R[i]).q}l{R[i]=""}}o={q:R.3q(\'\\n\')};11=p;b=o.q.6+(($.X.1V)?n:0)}l 2(v===8){o=1g(m);11=p+o.J.6;b=o.q.6-o.J.6-o.O.6;b-=1u(o.q)}l 2(A===8){o=1g(m);11=p;b=o.q.6;b-=1u(o.q)}l{o=1g(m);11=p+o.q.6;b=0;11-=1u(o.q)}2((m===\'\'&&o.Q===\'\')){H+=1W(o.q);11=p+o.J.6;b=o.q.6-o.J.6-o.O.6;H=d.K().1h(p,d.K().6).6;H-=1W(d.K().1h(0,p))}$.V(P,{p:p,16:16});2(o.q!==m&&18===7){2y(o.q);1X(11,b)}l{H=-1}14();$.V(P,{1t:\'\',m:m});2(v===8&&A===8){I(L.3r)}I(L.1E);I(k.1E);2(w&&k.1A){1Y()}A=F=v=18=7}3 1W(a){2($.X.1V){4 a.6-a.W(/\\n*/g,\'\').6}4 0}3 1u(a){2($.X.2z){4 a.6-a.W(/\\r*/g,\'\').6}4 0}3 2y(a){2(D.m){E b=D.m.1Z();b.2A=a}l{d.K(d.K().1h(0,p)+a+d.K().1h(p+m.6,d.K().6))}}3 1X(a,b){2(u.2B){2($.X.1V&&$.X.3s>=9.5&&b==0){4 7}1i=u.2B();1i.3t(8);1i.2C(\'21\',a);1i.3u(\'21\',b);1i.3v()}l 2(u.2D){u.2D(a,a+b)}u.1v=16;u.1f()}3 14(){u.1f();16=u.1v;2(D.m){m=D.m.1Z().2A;2($.X.2z){E a=D.m.1Z(),1w=a.3w();1w.3x(u);p=-1;3y(1w.3z(a)){1w.2C(\'21\');p++}}l{p=u.2E}}l{p=u.2E;m=d.K().1h(p,u.3A)}4 m}3 1B(){2(!w||w.3B){2(k.1j){w=3C.2F(\'\',\'1B\',k.1j)}l{M=$(\'<2G N="3D"></2G>\');2(k.25==\'26\'){M.1O(1m)}l{M.2f(17)}w=M[M.6-1].3E||3F[M.6-1]}}l 2(F===8){2(M){M.3G()}w.2H();w=M=7}2(!k.1A){1Y()}}3 1Y(){2(w.D){3H{22=w.D.2I.1v}3I(e){22=0}w.D.2F();w.D.3J(2J());w.D.2H();w.D.2I.1v=22}2(k.1j){w.1f()}}3 2J(){2(k.1b!==\'\'){$.2K({2L:\'3K\',2M:7,2N:k.1b,28:k.27+\'=\'+3L(d.K()),2O:3(a){23=1d(a,1)}})}l{2(!1n){$.2K({2M:7,2N:k.1k,2O:3(a){1n=1d(a,1)}})}23=1n.W(/<!-- 3M -->/g,d.K())}4 23}3 1Q(e){A=e.A;F=e.F;v=(!(e.F&&e.v))?e.v:7;2(e.2L===\'2l\'){2(v===8){B=$("a[2o="+3N.3O(e.1x)+"]",17).1y(\'B\');2(B.6!==0){v=7;B.3P(\'1q\');4 7}}2(e.1x===13||e.1x===10){2(v===8){v=7;Y(k.1H);4 k.1H.1z}l 2(A===8){A=7;Y(k.1G);4 k.1G.1z}l{Y(k.1F);4 k.1F.1z}}2(e.1x===9){2(A==8||v==8||F==8){4 7}2(H!==-1){14();H=d.K().6-H;1X(H,0);H=-1;4 7}l{Y(k.1I);4 k.1I.1z}}}}2b()})};$.24.3Q=3(){4 G.1c(3(){$$=$(G).1P().3R(\'2e\');$$.1y(\'z\').1y(\'z.T\').1y(\'z\').Q($$)})};$.T=3(a){E b={1r:7};$.V(b,a);2(b.1r){4 $(b.1r).1c(3(){$(G).1f();$(G).2P(\'1R\',[b])})}l{$(\'u\').2P(\'1R\',[b])}}})(3S);',62,241,'||if|function|return||length|false|true|||||||||||||else|selection||string|caretPosition|block||||textarea|ctrlKey|previewWindow|||div|shiftKey|li|id|document|var|altKey|this|caretOffset|prepare|openWith|val|clicked|iFrame|class|closeWith|hash|replaceWith|lines||markItUp|root|extend|replace|browser|markup|ul||start|nameSpace||get|levels|scrollPosition|header|abort|key|placeHolder|previewParserPath|each|localize|bind|focus|build|substring|range|previewInWindow|previewTemplatePath|resizeHandle|footer|template|mouseMove|mouseUp|mouseup|target|title|line|fixIeBug|scrollTop|rangeCopy|keyCode|parent|keepDefault|previewAutoRefresh|preview|html|beforeInsert|afterInsert|onEnter|onShiftEnter|onCtrlEnter|onTab|miuScript|attr|wrap|dropMenus|appendTo|insertAfter|unbind|keyPressed|insertion|name|split|value|opera|fixOperaBug|set|refreshPreview|createRange||character|sp|phtml|fn|previewPosition|after|previewParserVar|data|markupSet|null|init|substr|addClass|markItUpEditor|insertBefore|height|clientY|css|mousemove|append|keydown|focused|hover|accesskey|separator|for|markItUpButton|click|call|hide|dropMenu|magicMarkups|undefined|insert|msie|text|createTextRange|moveStart|setSelectionRange|selectionStart|open|iframe|close|documentElement|renderPreview|ajax|type|async|url|success|trigger|templates|script|src|match|jquery|markitup|pack|js|toUpperCase|markItUpContainer|markItUpHeader|markItUpFooter|safari|markItUpResizeHandle|mousedown|Math|max|px|keyup|display|Ctrl|markItUpSeparator|className|href|contextmenu|eval|show|one|push|markItUpDropMenu|pop|toString|prompt|isFunction|beforeMultiInsert|trim|join|afterMultiInsert|version|collapse|moveEnd|select|duplicate|moveToElementText|while|inRange|selectionEnd|closed|window|markItUpPreviewFrame|contentWindow|frame|remove|try|catch|write|POST|encodeURIComponent|content|String|fromCharCode|triggerHandler|markItUpRemove|removeClass|jQuery'.split('|'),0,{}));// ----------------------------------------------------------------------------
// markItUp! Comment Set
// ----------------------------------------------------------------------------
commentSettings = {
	markupSet:  [
		{name:'Quote', key:'Q', openWith:'[q]', closeWith:'[/q]', className:"quote-button"  },
		{separator:'---------------' },
		{name:'Poll', openWith:function() {
				return '[poll='+new Date().getTime()+']';
		 	}, closeWith:	 function() {
					if(placeHolder==false) {
						openWith = null;
						return false;
					} else {
						return '[/poll]';
					}
			 }, placeHolder:function() {
					var num_answers=prompt("How many answers?",3);
					if(num_answers==null)  {
						alert('The number of answers cannot be blank, please try again');
						return false;
					}
					num_answers = parseInt(num_answers);
					if(num_answers=='' || isNaN(num_answers))  {
						alert('The number of answers is invalid, please try again');
						return false;
					}
					var poll = new Array();
					poll[0] = prompt("Question", null);
					//var poll = new Array("[![Question]!]");
					if(poll[0] == null || poll[0] == '') {
						alert('The question cannot be blank, please try again');
						return false;
					}
					var answer = null;
					for(i=1;i<=num_answers;i++) {
						answer = prompt("Answer "+i, null);
						if(answer != null && answer != '') poll[i] = answer;
						//poll[i] =  "[![Answer "+i+"]!]";
					}
					if(poll.length != (num_answers + 1)) {
						alert('One or more answers were blank, please try again');
						return false;
					}
					return poll.join(":");
			 },
			className:"poll-button"}
	]
};/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};(function($) {
 
  $.fn.tweet = function(o){
    var s = {
      username: ["seaofclouds"],              // [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
      avatar_size: null,                      // [integer]  height and width of avatar if displayed (48px max)
      count: 3,                               // [integer]  how many tweets to display?
      intro_text: null,                       // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                       // [string]   do you want text AFTER your tweets?
      join_text:  null,                       // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",      // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                 // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "i am",             // [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",   // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at", // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                     // [string]   optional loading text, displayed while tweets load
      query: null,                            // [string]   optional search query
      reply: null,
      link_username: null,
      template: null
    };

    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"$1\" target=\"_blank\">$1</a>"))
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>"))
        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all" target=\"_blank\">#$1</a>'))// &from='+s.username.join("%2BOR%2B")+'
        });
        return $(returning);
      },
      capAwesome: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(a|A)wesome/gi, 'AWESOME'))
        });
        return $(returning);
      },
      capEpic: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(e|E)pic/gi, 'EPIC'))
        });
        return $(returning);
      },
      makeHeart: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/[&lt;]+[3]/gi, "<tt class='heart'>&#x2665;</tt>"))
        });
        return $(returning);
      }
    });

    function relative_time(time_value) {
      var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < 120) {
      return 'about a minute ago';
      } else if(delta < (45*60)) {
      return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*60)) {
      return 'about an hour ago';
      } else if(delta < (24*60*60)) {
      return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
      return '1 day ago';
      } else {
      return (parseInt(delta / 86400)).toString() + ' days ago';
      }
    }

    if(o) $.extend(s, o);
    return this.each(function(){
      var list = $('<ul class="tweet_list">').appendTo(this);
      var intro = '<p class="tweet_intro">'+s.intro_text+'</p>'
      var outro = '<p class="tweet_outro">'+s.outro_text+'</p>'
      var loading = $('<p class="loading_">'+s.loading_text+'</p>');
      if(typeof(s.username) == "string"){
        s.username = [s.username];
      }
      var query = '';
      if(s.query) {
        query += 'q='+s.query;
      }
      query += '&q=from:'+s.username.join('%20OR%20from:');
      var url = 'http://search.twitter.com/search.json?&'+query+'&rpp='+s.count+'&callback=?';
      if (s.loading_text) $(this).append(loading);
      $.getJSON(url, function(data){
        if (s.loading_text) loading.remove();
        if (s.intro_text) list.before(intro);
        $.each(data.results, function(i,item){
          // auto join text based on verb tense and content
          if (s.join_text == "auto") {
            if (item.text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
              var join_text = s.auto_join_text_reply;
            } else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
              var join_text = s.auto_join_text_url;
            } else if (item.text.match(/^((\w+ed)|just) .*/im)) {
              var join_text = s.auto_join_text_ed;
            } else if (item.text.match(/^(\w*ing) .*/i)) {
              var join_text = s.auto_join_text_ing;
            } else {
              var join_text = s.auto_join_text_default;
            }
          } else {
            var join_text = s.join_text;
          };

          var join_template = '<span class="tweet_join"> '+join_text+' </span>';
          var join = ((s.join_text) ? join_template : ' ')
          var username = '<a class="tweet_username" href="http://twitter.com/'+item.from_user+'" target="_blank">'+item.from_user+'</a>';
          var avatar_template = '<a class="tweet_avatar"  target="_blank" href="http://twitter.com/'+item.from_user+'" style="display:block;background-image:url('+item.profile_image_url+');background-repeat:no-repeat;width:'+s.avatar_size+'px;height:'+s.avatar_size+'px;">&nbsp;</a>';
          var avatar = (s.avatar_size ? avatar_template : '')
          var reply_template = ' <a class="reply" href="http://twitter.com/home?status=.@'+ item.from_user+'" target="_blank">'+s.reply+'</a>';
          var reply = (s.reply ? reply_template : '')
          var date = '<div class="info"><a class="status" href="http://twitter.com/'+item.from_user+'/statuses/'+item.id+'" title="view tweet on twitter" target="_blank">'+relative_time(item.created_at)+'</a>'+reply+'</div>';
          var text = '<span class="tweet_text">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';

          if(s.template) {
            var template = s.template;
          } else {
            var template = '<li>[avatar]<div class="tweet_content">[date][join][text]</div></li>';
          }
          
          if(s.link_username) {
            template = template.replace(/\[username\]/i,username);
          }
          template = template.replace(/\[avatar\]/i,avatar);
          template = template.replace(/\[date\]/i,date);
          template = template.replace(/\[join\]/i,join);
          template = template.replace(/\[text\]/i,text);
          
          list.append(template);

          list.children('li:first').addClass('tweet_first');
          list.children('li:odd').addClass('tweet_even');
          list.children('li:even').addClass('tweet_odd');
        });
        if (s.outro_text) list.after(outro);
      });

    });
  };
})(jQuery);$(document).ready(function() {
    bindItemToggler();
    $('.item-list').each(function(){
      var list_name = $(this).attr('id');
      setItemLayoutFromCookies(list_name);
    });
});

function setItemLayoutFromCookies(list_name) {
  var list_id = '#'+list_name;
  var list_toggler_cookie = $.cookie(list_name); // Get cookie with name based upon item group
  var list_toggler_id = '#'+list_name+'-toggler';
  if(list_toggler_cookie == 'grid-layout') {
    $(list_toggler_id + ' .toggler-list').hide();
    $(list_toggler_id + ' .toggler-list-off').css('display', 'block');
    $(list_toggler_id + ' .toggler-grid').css('display', 'block');
    $(list_toggler_id + ' .toggler-grid-off').hide();
    if($(list_id).hasClass('grid-layout') != true) {
      $(list_id).addClass("grid-layout"); // Switch the layout type
    }
    $(list_id + ' .item-details.list').hide(); // Hide/Show description
    $(list_id + ' .item-details.grid').show(); // Hide/Show description
  } else if(list_toggler_cookie == 'list-layout') {
    $(list_toggler_id + ' .toggler-grid').hide();
    $(list_toggler_id + ' .toggler-grid-off').css('display', 'block');
    $(list_toggler_id + ' .toggler-list').css('display', 'block');
    $(list_toggler_id + ' .toggler-list-off').hide();
    if($(list_id).hasClass('grid-layout') == true) {
      $(list_id).removeClass("grid-layout"); // Switch the layout type
    }
    $(list_id + ' .item-details.grid').hide(); // Hide/Show description
    $(list_id + ' .item-details.list').show(); // Hide/Show description
  }
}

function bindItemToggler() {
  $('.item-toggler a.layout-toggler').unbind("click");
  $('.item-toggler a.layout-toggler').click(function(event) {
    event.preventDefault();
    var list_toggler_id = $(this).parent().attr('id'); // Get the toggler parent ID (contains item list id and item group)
    var settings = list_toggler_id.split('-');
    var list_id = '#' + settings[0]; // Set the list ID
    var list_toggler_id = '#' + list_toggler_id; // Set the list toggler ID

    var cookie_name = settings[0]; // Set cookie name based upon item group
    var url_root = window.location.pathname.split("/")[1];
    
    if($(list_id).hasClass('grid-layout')) {
      $(list_toggler_id + ' .toggler-grid').hide();
      $(list_toggler_id + ' .toggler-grid-off').css('display', 'block');
      $(list_toggler_id + ' .toggler-list').css('display', 'block');
      $(list_toggler_id + ' .toggler-list-off').hide();
      // Set cookie for list layout
      if(url_root=='page' || url_root=='archive') {
        $.cookie('page', 'list-layout', {expires: 360, path: '/page'});
        $.cookie('archive', 'list-layout', {expires: 360, path: '/archive'});
      } else {
        $.cookie(cookie_name, 'list-layout', {expires: 360, path: '/'+url_root});
      }
    } else {
      $(list_toggler_id + ' .toggler-list').hide();
      $(list_toggler_id + ' .toggler-list-off').css('display', 'block');
      $(list_toggler_id + ' .toggler-grid').css('display', 'block');
      $(list_toggler_id + ' .toggler-grid-off').hide();
      // Set cookie for grid layout
      if(url_root=='page' || url_root=='archive') {
        $.cookie('page', 'grid-layout', {expires: 360, path: '/page'}); 
        $.cookie('archive', 'grid-layout', {expires: 360, path: '/archive'});
      } else {
        $.cookie(cookie_name, 'grid-layout', {expires: 360, path: '/'+url_root});
      }
    }
    
    $(list_id).toggleClass("grid-layout"); // Switch the layout type
    $(list_id + ' .item-details').toggle(); // Hide/Show description
  });
}

function rebindItemToggler(list_name) {
  bindItemToggler();
}$(document).ready(function(){ 
  // Search box default (change name=search to type=text to add default swapping for all text inputs)
  $('input[name=search_value]').focus(function(){ 
    if($(this).val() == $(this).attr('defaultValue')) {
      $(this).val('');
    }
  });
  $('input[name=search_value]').blur(function(){
    if($(this).val() == '') {
      $(this).val($(this).attr('defaultValue'));
    }
  });
});/*
 * jQuery Catfish Plugin - Version 1.3
 *
 * Copyright (c) 2007 Matt Oakes (http://www.gizone.co.uk)
 * Licensed under the MIT (LICENSE.txt)
 */

jQuery.fn.catfish = function(options) {
    this.settings = {
        closeLink: 'none',
        animation: 'slide',
        height: '85'
    }
    if(options)
        jQuery.extend(this.settings, options);
    
    if ( this.settings.animation != 'slide' && this.settings.animation != 'none' && this.settings.animation != 'fade' ) {
        alert('animation can only be set to \'slide\', \'none\' or \'fade\'');
    }
    
    var id = this.attr('id');
    settings = this.settings;
    jQuery(this).css('padding', '0').css('height', this.settings.height + 'px').css('margin', '0').css('width', '100%');
    //jQuery('html').css('padding', '0 0 ' + ( this.settings.height * 1 + 50 ) + 'px 0');
    if ( typeof document.body.style.maxHeight != "undefined" ) {
        jQuery(this).css('position', 'fixed').css('bottom', '0').css('left', '0');
    }
    
    if ( this.settings.animation == 'slide' ) {
        jQuery(this).slideDown('slow');
    }
    else if ( this.settings.animation == 'fade' ) {
        jQuery(this).fadeIn('slow');
    }
    else {
        jQuery(this).show();
    }
    if ( this.settings.closeLink != 'none' ) {
        jQuery(this.settings.closeLink).click(function(){
            jQuery.closeCatfish(id);
            return false;
        });
    }
    
    // Return jQuery to complete the chain
    return this;
};
jQuery.closeCatfish = function(id) {
    this.catfish = jQuery('#' + id);
    jQuery(this.catfish).hide();
    jQuery('html').css('padding', '0');
    jQuery('body').css('overflow', 'none'); // Change IE6 hack back
};/*
// Infinite Scroll jQuery plugin
// copyright Paul Irish, licensed GPL & MIT
// version 1.2.091002

// home and docs: http://www.infinite-scroll.com
*/
(function(A){A.fn.infinitescroll=function(N,L){function E(){if(B.debug){window.console&&console.log.call(console,arguments)}}function G(P){for(var O in P){if(O.indexOf&&O.indexOf("Selector")&&A(P[O]).length===0){E("Your "+O+" found no elements.");return false}return true}}function K(O){O.match(C)?O.match(C)[2]:O;if(O.match(/^(.*?)\b2\b(.*?$)/)){O=O.match(/^(.*?)\b2\b(.*?$)/).slice(1)}else{if(O.match(/^(.*?)2(.*?$)/)){if(O.match(/^(.*?page=)2(\/.*|$)/)){O=O.match(/^(.*?page=)2(\/.*|$)/).slice(1);return O}E("Trying backup next selector parse technique. Treacherous waters here, matey.");O=O.match(/^(.*?)2(.*?$)/).slice(1)}else{E("Sorry, we couldn't parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.");H.isInvalidPage=true}}return O}function I(){return B.localMode?(A(H.container)[0].scrollHeight&&A(H.container)[0].scrollHeight):A(document).height()}function F(Q,P){var O=I()-(Q.localMode?A(P.container).scrollTop():(A(P.container).scrollTop()||A(P.container.ownerDocument.body).scrollTop()))-A(Q.localMode?P.container:window).height();E("math:",O,P.pixelsFromNavToBottom);return(O-Q.bufferPx<P.pixelsFromNavToBottom)}function J(){H.loadingMsg.find("img").hide().parent().find("div").html(B.donetext).animate({opacity:1},2000).fadeOut("normal");B.errorCallback()}function D(R,Q,O,S){if(O.isDuringAjax||O.isInvalidPage||O.isDone){return }if(!F(Q,O)){return }O.isDuringAjax=true;O.loadingMsg.appendTo(Q.contentSelector).show();A(Q.navSelector).hide();O.currPage++;E("heading into ajax",R);var P=A(Q.contentSelector).is("table")?A("<tbody/>"):A("<div/>");P.attr("id","infscr-page-"+O.currPage).addClass("infscr-pages").appendTo(Q.contentSelector).load(R.join(O.currPage)+" "+Q.itemSelector,null,function(){if(O.isDone){J();return false}else{if(P.children().length==0){A.event.trigger("ajaxError",[{status:404}])}O.loadingMsg.fadeOut("normal");if(Q.animate){var T=A(window).scrollTop()+A("#infscr-loading").height()+Q.extraScrollPx+"px";A("html,body").animate({scrollTop:T},800,function(){O.isDuringAjax=false})}S.call(P[0]);if(!Q.animate){O.isDuringAjax=false}}})}var B=A.extend({},A.infinitescroll.defaults,N);var H=A.infinitescroll;L=L||function(){};if(!G(B)){return false}H.container=B.localMode?this:document.documentElement;B.contentSelector=B.contentSelector||this;var C=/(.*?\/\/).*?(\/.*)/;var M=A(B.nextSelector).attr("href");if(!M){E("Navigation selector not found");return }M=K(M);if(B.localMode){A(H.container)[0].scrollTop=0}H.pixelsFromNavToBottom=I()+(H.container==document.documentElement?0:A(H.container).offset().top)-A(B.navSelector).offset().top;H.loadingMsg=A('<div id="infscr-loading" style="text-align: center;"><img alt="Loading..." src="'+B.loadingImg+'" /><div>'+B.loadingText+"</div></div>");(new Image()).src=B.loadingImg;A(document).ajaxError(function(P,Q,O){E("Page not found. Self-destructing...");if(Q.status==404){J();H.isDone=true;A(B.localMode?this:window).unbind("scroll.infscr")}});A(B.localMode?this:window).bind("scroll.infscr",function(){D(M,B,H,L)}).trigger("scroll.infscr");return this};A.infinitescroll={defaults:{debug:false,preload:false,nextSelector:"div.navigation a:first",loadingImg:"http://www.infinite-scroll.com/loading.gif",loadingText:"<em>Loading the next set of posts...</em>",donetext:"<em>Congratulations, you've reached the end of the internet.</em>",navSelector:"div.navigation",contentSelector:null,extraScrollPx:150,itemSelector:"div.post",animate:false,localMode:false,bufferPx:40,errorCallback:function(){}},loadingImg:undefined,loadingMsg:undefined,container:undefined,currPage:1,currDOMChunk:null,isDuringAjax:false,isInvalidPage:false,isDone:false}})(jQuery);$(document).ready (function () {
	$('.mega-menu li').hover(
		function () {
			$(this).siblings('li').removeClass('hovering');
			$(this).addClass('hovering');
		},
		function () {
			$(this).removeClass('hovering');
		}
	);
	
	$('.dropdown').hover(
		function () {
			$(this).addClass('hovering');
		},
		function () {
			$(this).removeClass('hovering');
		}
	);
	
	$('.dropdown .dropdown-link').click(function(event) {
		event.preventDefault();
	});
	
	// $('#mg-search').hover(
	// 	function () {
	// 		$(this).addClass('hovering');
	// 	},
	// 	function () {
	// 		$(this).removeClass('hovering');
	// 		
	// 	}
	// );

	$('#mg-search-icon').click(function (event) {
		event.preventDefault();
		$("#mg-search").toggleClass("hovering");
	});

	$("body").click(function(event) {
		var $target = $(event.target);
		if( ! $target.is("#mg-search") && ! $target.parents().is("#mg-search")) {
			$("#mg-search").removeClass("hovering");
		}
	});

});/*
(c) Copyrights 2007 - 2008

Original idea by by Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/
 
jQuery Plugin by Tzury Bar Yochay 
tzury.by@gmail.com
http://evalinux.wordpress.com
http://facebook.com/profile.php?id=513676303

Project's sites: 
http://code.google.com/p/js-hotkeys/
http://github.com/tzuryby/hotkeys/tree/master

License: same as jQuery license. 

USAGE:
    // simple usage
    $(document).bind('keydown', 'Ctrl+c', function(){ alert('copy anyone?');});
    
    // special options such as disableInIput
    $(document).bind('keydown', {combi:'Ctrl+x', disableInInput: true} , function() {});
    
Note:
    This plugin wraps the following jQuery methods: $.fn.find, $.fn.bind and $.fn.unbind
*/

(function (jQuery){
    // keep reference to the original $.fn.bind, $.fn.unbind and $.fn.find
    jQuery.fn.__bind__ = jQuery.fn.bind;
    jQuery.fn.__unbind__ = jQuery.fn.unbind;
    jQuery.fn.__find__ = jQuery.fn.find;
    
    var hotkeys = {
        version: '0.7.9',
        override: /keypress|keydown|keyup/g,
        triggersMap: {},
        
        specialKeys: { 27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 
            20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
            35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 
            109: '-', 
            112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 
            120:'f9', 121:'f10', 122:'f11', 123:'f12', 191: '/'},
        
        shiftNums: { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&", 
            "8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<", 
            ".":">",  "/":"?",  "\\":"|" },
        
        newTrigger: function (type, combi, callback) { 
            // i.e. {'keyup': {'ctrl': {cb: callback, disableInInput: false}}}
            var result = {};
            result[type] = {};
            result[type][combi] = {cb: callback, disableInInput: false};
            return result;
        }
    };
    // add firefox num pad char codes
    //if (jQuery.browser.mozilla){
    // add num pad char codes
    hotkeys.specialKeys = jQuery.extend(hotkeys.specialKeys, { 96: '0', 97:'1', 98: '2', 99: 
        '3', 100: '4', 101: '5', 102: '6', 103: '7', 104: '8', 105: '9', 106: '*', 
        107: '+', 109: '-', 110: '.', 111 : '/'
        });
    //}
    
    // a wrapper around of $.fn.find 
    // see more at: http://groups.google.com/group/jquery-en/browse_thread/thread/18f9825e8d22f18d
    jQuery.fn.find = function( selector ) {
        this.query = selector;
        return jQuery.fn.__find__.apply(this, arguments);
	};
    
    jQuery.fn.unbind = function (type, combi, fn){
        if (jQuery.isFunction(combi)){
            fn = combi;
            combi = null;
        }
        if (combi && typeof combi === 'string'){
            var selectorId = ((this.prevObject && this.prevObject.query) || (this[0].id && this[0].id) || this[0]).toString();
            var hkTypes = type.split(' ');
            for (var x=0; x<hkTypes.length; x++){
                delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi];
            }
        }
        // call jQuery original unbind
        return  this.__unbind__(type, fn);
    };
    
    jQuery.fn.bind = function(type, data, fn){
        // grab keyup,keydown,keypress
        var handle = type.match(hotkeys.override);
        
        if (jQuery.isFunction(data) || !handle){
            // call jQuery.bind only
            return this.__bind__(type, data, fn);
        }
        else{
            // split the job
            var result = null,            
            // pass the rest to the original $.fn.bind
            pass2jq = jQuery.trim(type.replace(hotkeys.override, ''));
            
            // see if there are other types, pass them to the original $.fn.bind
            if (pass2jq){
                result = this.__bind__(pass2jq, data, fn);
            }            
            
            if (typeof data === "string"){
                data = {'combi': data};
            }
            if(data.combi){
                for (var x=0; x < handle.length; x++){
                    var eventType = handle[x];
                    var combi = data.combi.toLowerCase(),
                        trigger = hotkeys.newTrigger(eventType, combi, fn),
                        selectorId = ((this.prevObject && this.prevObject.query) || (this[0].id && this[0].id) || this[0]).toString();
                        
                    //trigger[eventType][combi].propagate = data.propagate;
                    trigger[eventType][combi].disableInInput = data.disableInInput;
                    
                    // first time selector is bounded
                    if (!hotkeys.triggersMap[selectorId]) {
                        hotkeys.triggersMap[selectorId] = trigger;
                    }
                    // first time selector is bounded with this type
                    else if (!hotkeys.triggersMap[selectorId][eventType]) {
                        hotkeys.triggersMap[selectorId][eventType] = trigger[eventType];
                    }
                    // make trigger point as array so more than one handler can be bound
                    var mapPoint = hotkeys.triggersMap[selectorId][eventType][combi];
                    if (!mapPoint){
                        hotkeys.triggersMap[selectorId][eventType][combi] = [trigger[eventType][combi]];
                    }
                    else if (mapPoint.constructor !== Array){
                        hotkeys.triggersMap[selectorId][eventType][combi] = [mapPoint];
                    }
                    else {
                        hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length] = trigger[eventType][combi];
                    }
                    
                    // add attribute and call $.event.add per matched element
                    this.each(function(){
                        // jQuery wrapper for the current element
                        var jqElem = jQuery(this);
                        
                        // element already associated with another collection
                        if (jqElem.attr('hkId') && jqElem.attr('hkId') !== selectorId){
                            selectorId = jqElem.attr('hkId') + ";" + selectorId;
                        }
                        jqElem.attr('hkId', selectorId);
                    });
                    result = this.__bind__(handle.join(' '), data, hotkeys.handler)
                }
            }
            return result;
        }
    };
    // work-around for opera and safari where (sometimes) the target is the element which was last 
    // clicked with the mouse and not the document event it would make sense to get the document
    hotkeys.findElement = function (elem){
        if (!jQuery(elem).attr('hkId')){
            if (jQuery.browser.opera || jQuery.browser.safari){
                while (!jQuery(elem).attr('hkId') && elem.parentNode){
                    elem = elem.parentNode;
                }
            }
        }
        return elem;
    };
    // the event handler
    hotkeys.handler = function(event) {
        var target = hotkeys.findElement(event.currentTarget), 
            jTarget = jQuery(target),
            ids = jTarget.attr('hkId');
        
        if(ids){
            ids = ids.split(';');
            var code = event.which,
                type = event.type,
                special = hotkeys.specialKeys[code],
                // prevent f5 overlapping with 't' (or f4 with 's', etc.)
                character = !special && String.fromCharCode(code).toLowerCase(),
                shift = event.shiftKey,
                ctrl = event.ctrlKey,            
                // patch for jquery 1.2.5 && 1.2.6 see more at:  
                // http://groups.google.com/group/jquery-en/browse_thread/thread/83e10b3bb1f1c32b
                alt = event.altKey || event.originalEvent.altKey,
                mapPoint = null;

            for (var x=0; x < ids.length; x++){
                if (hotkeys.triggersMap[ids[x]][type]){
                    mapPoint = hotkeys.triggersMap[ids[x]][type];
                    break;
                }
            }
            
            //find by: id.type.combi.options            
            if (mapPoint){ 
                var trigger;
                // event type is associated with the hkId
                if(!shift && !ctrl && !alt) { // No Modifiers
                    trigger = mapPoint[special] ||  (character && mapPoint[character]);
                }
                else{
                    // check combinations (alt|ctrl|shift+anything)
                    var modif = '';
                    if(alt) modif +='alt+';
                    if(ctrl) modif+= 'ctrl+';
                    if(shift) modif += 'shift+';
                    // modifiers + special keys or modifiers + character or modifiers + shift character or just shift character
                    trigger = mapPoint[modif+special];
                    if (!trigger){
                        if (character){
                            trigger = mapPoint[modif+character] 
                                || mapPoint[modif+hotkeys.shiftNums[character]]
                                // '$' can be triggered as 'Shift+4' or 'Shift+$' or just '$'
                                || (modif === 'shift+' && mapPoint[hotkeys.shiftNums[character]]);
                        }
                    }
                }
                if (trigger){
                    var result = false;
                    for (var x=0; x < trigger.length; x++){
                        if(trigger[x].disableInInput){
                            // double check event.currentTarget and event.target
                            var elem = jQuery(event.target);
                            if (jTarget.is("input") || jTarget.is("textarea") || jTarget.is("select") 
                                || elem.is("input") || elem.is("textarea") || elem.is("select")) {
                                return true;
                            }
                        }                       
                        // call the registered callback function
                        result = result || trigger[x].cb.apply(this, [event]);
                    }
                    return result;
                }
            }
        }
    };
    // place it under window so it can be extended and overridden by others
    window.hotkeys = hotkeys;
    return jQuery;
})(jQuery);
$(document).ready(function(){
	$(".spotlight-menu td .spotlight-link").live('click', function(event) {
		event.preventDefault();
		var link_id = $(this).attr("id");
		var settings = link_id.split("-");
		var listing_name = settings[0];
		var listing_id = '#'+listing_name;
		var item_type = settings[1];
		var listing_method = settings[2];
		var listing_search = settings[3];
		var listing_cols = settings[4];
		var listing_rows = settings[5];
		var listing_list_title_len = settings[6];
		var listing_list_desc_len = settings[7];
		var listing_grid_title_len = settings[8];
		var listing_grid_desc_len = settings[9];
		var language = settings[10];
		var your_content = settings[11];
		var show_inventory = settings[12];
		var inventory_amount = settings[13];
		var inventory_placement = settings[14];
		var inventory_location = settings[15];
		var listing_layout = 'list';
		
		if($(listing_id).hasClass("grid-layout"))
		{
			listing_layout = 'grid';
		}
		else if($(listing_id).hasClass("mini-layout"))
		{
			listing_layout = 'mini';
		}
		else if($(listing_id).hasClass("text-layout"))
		{
			listing_layout = 'text';
		}
		else if($(listing_id).hasClass("large-layout"))
		{
			listing_layout = 'large';
		}
		var menu_item_text = '';
		var menu_item_parent = '';
		if($('#'+link_id).parents('.dropdown').length) {
			var menu_item_parent_id = $("#"+ link_id).parents('.spotlight-dropdown').attr('id');
		} else {
			var menu_item_parent_id = $("#"+ link_id).parent().attr('id');
		}

		$.ajax({ 
			type: "GET", 
			url: "http://www.otaku.fm/themes/default/ajax/ajax.listing.php", 
			data: {listing_name : listing_name, item_type : item_type, listing_method: listing_method, listing_search : listing_search, language : language, listing_layout : listing_layout, listing_cols : listing_cols, listing_rows : listing_rows, listing_list_title_len : listing_list_title_len, listing_list_desc_len : listing_list_desc_len, listing_grid_title_len : listing_grid_title_len, listing_grid_desc_len : listing_grid_desc_len, your_content : your_content, show_inventory : show_inventory, inventory_amount : inventory_amount, inventory_placement : inventory_placement, inventory_location : inventory_location}, 
			cache: false,
			dataType: "html", 
			beforeSend: function(){
				if($('#'+link_id).parents('.dropdown').length) {
					$(listing_id+'-menu .spotlight-link').removeClass("active");
					$(listing_id+'-menu .dropdown').removeClass("hovering");
					menu_item_text = $("#"+ menu_item_parent_id).html();
					menu_item_parent = $("#"+ menu_item_parent_id).html();
					$("#"+ link_id).parents('.spotlight-dropdown').addClass("spotlight-loading");
					$(listing_id+'-menu td').removeClass("active");
					$("#"+ menu_item_parent_id).children('.dropdown-link').html('<span class="spotlight-link">'+menu_item_text+'</span>');
				} else {
					menu_item_text = $("#"+ link_id).html();
					menu_item_parent = $("#"+ menu_item_parent_id).html();
					$("#"+ link_id).parent().addClass("spotlight-loading");
					$(listing_id+'-menu td').removeClass("active");
					$(listing_id+'-menu .spotlight-link').removeClass("active");
					$("#"+ menu_item_parent_id).html('<span class="spotlight-link">'+menu_item_text+'</span>');
				}
			}, 
			error: function(){ 
				$(listing_id).html('Error loading document');
				$("#"+ menu_item_parent_id).html(menu_item_parent);
				if($('#'+link_id).parents('.dropdown').length) {
					$("#"+ link_id).parents('.spotlight-dropdown').removeClass("spotlight-loading");
				} else {
					$("#"+ link_id).parent().removeClass("spotlight-loading");
				}
			}, 
			success: function(data){
				$(listing_id+'-loading').hide();
				$(listing_id+'-list').html(data);
				$("#"+ menu_item_parent_id).html(menu_item_parent);
				if($('#'+link_id).parents('.dropdown').length) {
					$("#"+ link_id).parents('.spotlight-dropdown').removeClass("spotlight-loading");
					$("#"+ link_id).addClass("active");
					$("#"+ link_id).parents('.spotlight-dropdown').addClass("active");
				} else {
					$("#"+ link_id).parent().removeClass("spotlight-loading");
					$("#"+ link_id).parent().addClass("active");
				}
			},
			complete: function(){
				$('#'+link_id).parents('.dropdown').hover(
					function () {
						$(this).addClass('hovering');
					},
					function () {
						$(this).removeClass('hovering');
					}
				);

				$('#'+link_id).parents('.dropdown').children('.dropdown-link').click(function(event) {
					event.preventDefault();
				});
				rebindItemToggler(listing_name);
			}
		});
	});
});/// <reference path="jquery-1.2.6-vsdoc.js" />
(function($) {

    $.fn.annotateImage = function(options) {
        /// <summary>
        ///   Creates annotations on the given image.
        ///     Images are loaded from the "getUrl" propety passed into the options.
        /// </summary>
        //var opts = $.extend({}, $.fn.annotateImage.defaults, options);
        //var image = this;
        var id = this.attr('id').split('-');
        id = id[1];
        
        this.hover(function() {
          // Add the canvas
          var image = this;
          this.image = $(this);
          this.notes = new Array();
          this.mode = 'view';
          this.id = id;
          this.editable = true;
          this.canvas = $('<div class="image-annotate-canvas"><div class="image-annotate-view"></div><div class="image-annotate-edit"><div class="image-annotate-edit-area"></div></div></div>');
          this.canvas.children('.image-annotate-edit').hide();
          this.canvas.children('.image-annotate-view').hide();
          this.image.after(this.canvas);

          // Give the canvas and the container their size and background
          this.canvas.height(this.image.height());
          this.canvas.width(this.image.width());
          this.canvas.css('background-image', 'url("' + this.image.attr('src') + '")');
          this.canvas.css('background-repeat', 'no-repeat');
          this.canvas.css('background-position', 'center');
          this.canvas.children('.image-annotate-view, .image-annotate-edit').height(this.image.height());
          this.canvas.children('.image-annotate-view, .image-annotate-edit').width(this.image.width());

          // Add the behavior: hide/show the notes when hovering the picture
          this.canvas.hover(function() {
              if ($(this).children('.image-annotate-edit').css('display') == 'none') {
                  $(this).children('.image-annotate-view').show();
              }
          }, function() {
              $(this).children('.image-annotate-view').hide();
          });

          this.canvas.children('.image-annotate-view').hover(function() {
              $(this).show();
          }, function() {
              $(this).hide();
          });

          // Hide the original
          this.image.hide();
          
          $('image-annotate-canvas-'+id).attr('id','');
          this.canvas.attr('id','image-annotate-canvas-'+id);

          $('#image-annotate-canvas-'+id).prepend('<div style="display:none;" id="image-annotate-canvas-'+id+'-notice" class="image-annotate-canvas-notice"></div>');
          $('#image-annotate-canvas-'+id+'-notice').width(this.image.width()-12); // -12 for padding
          $('#image-annotate-canvas-'+id).prepend('<div style="display:none;" id="image-annotate-canvas-'+id+'-error" class="image-annotate-canvas-error"></div>');
          $('#image-annotate-canvas-'+id+'-error').width(this.image.width()-12);
          
          if($.cookie('melissa_display_name') && $.cookie('melissa_user_name') && $.cookie('melissa_avatar')) {
            this.button = $('<a class="image-annotate-add" id="image-annotate-add-'+id+'" href="#">写真メモ追加</a>');
            this.button.click(function(event) {
                event.preventDefault();
                $.fn.annotateImage.add(image);
            });
          } else {
            this.button = $('<a class="image-annotate-add" href="/melissa/site/ja/signin/?redirect=http://www.otaku.fm'+window.location.pathname+'#image-'+id+'">写真メモ追加</a>');
          }
          this.image.parents('.image-wrapper').children('.image-meta').append(this.button);
          
          $.fn.annotateImage.ajaxLoad(this);
        });
        
        
    };

    /**
    * Plugin Defaults
    **/
    $.fn.annotateImage.defaults = {
        getUrl: 'your-get.rails',
        saveUrl: 'your-save.rails',
        deleteUrl: 'your-delete.rails',
        editable: true,
        useAjax: true,
        notes: new Array()
    };

    $.fn.annotateImage.clear = function(image) {
        /// <summary>
        ///   Clears all existing annotations from the image.
        /// </summary>    
        for (var i = 0; i < image.notes.length; i++) {
            image.notes[image.notes[i]].destroy();
        }
        image.notes = new Array();
    };

    $.fn.annotateImage.ajaxLoad = function(image) {
        /// <summary>
        ///   Loads the annotations from the "getUrl" property passed in on the
        ///     options object.
        /// </summary>
        var item_uid = $('.post-body').attr('id');
        item_uid = item_uid.split('-');
        item_uid = item_uid[2];
        $.ajax({
          url: 'http://www.otaku.fm/themes/default/ajax/ajax.annotate.image.php',
          type: 'POST',
          data: 'action=load&ticks=' + $.fn.annotateImage.getTicks()+'&item_id='+item_uid+'&item_type=post&image_id='+image.id,
          beforeSend: function () {
            $.fn.annotateImage.showLoading(image.id);
          },
          error: function(e) {
            $('#image-annotate-canvas-'+image.id+'-notice').hide();
            $.fn.annotateImage.showError(image.id, "An error occured loading the image notes.")
          },
          success: function(data) {
            $('#image-annotate-canvas-'+image.id+'-notice').fadeOut('slow');
            if(data.ok===false) {
              image.notes = new Array();
            } else {
              image.notes = data;
            }
            $.fn.annotateImage.load(image);
          },
          dataType: "json"
        });
    };
    
    $.fn.annotateImage.showError = function(id, msg) {
      $('#image-annotate-canvas-'+id+'-error').hide();
      $('#image-annotate-canvas-'+id+'-error').html(msg);
      $('#image-annotate-canvas-'+id+'-error').fadeIn('slow');
    };
    
    $.fn.annotateImage.showLoading = function(id) {
      $('#image-annotate-canvas-'+id+'-notice').hide();
      $('#image-annotate-canvas-'+id+'-notice').html('<img src="http://www.otaku.fm/themes/default/img/loading-annotations.gif?v=20090424" />&nbsp;Loading image notes...');
      $('#image-annotate-canvas-'+id+'-notice').fadeIn('slow');
    };
    
    $.fn.annotateImage.showNotice = function(id, msg) {
      $('#image-annotate-canvas-'+id+'-notice').hide();
      $('#image-annotate-canvas-'+id+'-notice').html(msg);
      $('#image-annotate-canvas-'+id+'-notice').fadeIn('slow');
    };
    

    $.fn.annotateImage.load = function(image) {
        /// <summary>
        ///   Loads the annotations from the notes property passed in on the
        ///     options object.
        /// </summary>
        for (var i = 0; i < image.notes.length; i++) {
            image.notes[image.notes[i]] = new $.fn.annotateView(image, image.notes[i]);
        }
    };

    $.fn.annotateImage.getTicks = function() {
        /// <summary>
        ///   Gets a count og the ticks for the current date.
        ///     This is used to ensure that URLs are always unique and not cached by the browser.
        /// </summary>        
        var now = new Date();
        return now.getTime();
    };

    $.fn.annotateImage.add = function(image) {
        /// <summary>
        ///   Adds a note to the image.
        /// </summary>        
        if (image.mode == 'view') {
            image.mode = 'edit';
            
            // Create/prepare the editable note elements
            var editable = new $.fn.annotateEdit(image);

            $.fn.annotateImage.createSaveButton(editable, image);
            $.fn.annotateImage.createCancelButton(editable, image);
        }
    };

    $.fn.annotateImage.createSaveButton = function(editable, image, note) {
        /// <summary>
        ///   Creates a Save button on the editable note.
        /// </summary>
        var ok = $('<a class="image-annotate-edit-ok">OK</a>');

        ok.click(function() {
            var form = $('#image-annotate-edit-form form');
            var text = $('#image-annotate-text').val();
            $.fn.annotateImage.appendPosition(form, editable)
            image.mode = 'view';

            // Save via AJAX
            //if (image.useAjax) {
              var item_uid = $('.post-body').attr('id');
              item_uid = item_uid.split('-');
              item_uid = item_uid[2];
                $.ajax({
                    url: 'http://www.otaku.fm/themes/default/ajax/ajax.annotate.image.php',
                    type: 'POST',
                    data: form.serialize() + '&action=add&ticks='+ $.fn.annotateImage.getTicks() + '&item_id='+item_uid+'&item_type=post&language=ja&image_id='+image.id,
                    beforeSend: function () {
                      $.fn.annotateImage.showNotice(image.id, '<img src="http://www.otaku.fm/themes/default/img/loading-annotations.gif?v=20090424" />&nbsp;Saving note...');
                    },
                    error: function(e) {
                      $('#image-annotate-canvas-'+image.id+'-notice').hide();
                      $.fn.annotateImage.showError(image.id, "An error occured loading the image notes.")
                    },
                    success: function(data) {
                      $('#image-annotate-canvas-'+image.id+'-notice').fadeOut('slow');
                      if (data.annotation_id != undefined) {
                        editable.note.id = data.annotation_id;
                      }
                    },
                    dataType: "json"
                });
            //}

            // Add to canvas
            if (note) {
                note.resetPosition(editable, text);
            } else {
                //editable.note.editable = true;
                note = new $.fn.annotateView(image, editable.note)
                note.resetPosition(editable, text);
                image.notes.push(editable.note);
            }

            editable.destroy();
        });
        editable.form.append(ok);
    };

    $.fn.annotateImage.createCancelButton = function(editable, image) {
        /// <summary>
        ///   Creates a Cancel button on the editable note.
        /// </summary>
        var cancel = $('<a class="image-annotate-edit-close">キャンセル</a>');
        cancel.click(function() {
            editable.destroy();
            image.mode = 'view';
        });
        editable.form.append(cancel);
        editable.form.append('<div class="instructions"><small>写真メモはコメント欄にも表示されます</small></div>');
    };

    $.fn.annotateImage.saveAsHtml = function(image, target) {
        var element = $(target);
        var html = "";
        for (var i = 0; i < image.notes.length; i++) {
            html += $.fn.annotateImage.createHiddenField("text_" + i, image.notes[i].text);
            html += $.fn.annotateImage.createHiddenField("top_" + i, image.notes[i].top);
            html += $.fn.annotateImage.createHiddenField("left_" + i, image.notes[i].left);
            html += $.fn.annotateImage.createHiddenField("height_" + i, image.notes[i].height);
            html += $.fn.annotateImage.createHiddenField("width_" + i, image.notes[i].width);
        }
        element.html(html);
    };

    $.fn.annotateImage.createHiddenField = function(name, value) {
        return '&lt;input type="hidden" name="' + name + '" value="' + value + '" /&gt;<br />';
    };

    $.fn.annotateEdit = function(image, note) {
        /// <summary>
        ///   Defines an editable annotation area.
        /// </summary>
        this.image = image;

        if (note) {
            this.note = note;
        } else {
            var newNote = new Object();
            newNote.id = "new";
            newNote.top = 30;
            newNote.left = 30;
            newNote.width = 30;
            newNote.height = 30;
            newNote.text = "";
            this.note = newNote;
        }

        // Set area
        var area = image.canvas.children('.image-annotate-edit').children('.image-annotate-edit-area');
        this.area = area;
        this.area.css('height', this.note.height + 'px');
        this.area.css('width', this.note.width + 'px');
        this.area.css('left', this.note.left + 'px');
        this.area.css('top', this.note.top + 'px');

        // Show the edition canvas and hide the view canvas
        image.canvas.children('.image-annotate-view').hide();
        image.canvas.children('.image-annotate-edit').show();

        // Add the note (which we'll load with the form afterwards)
        var form = $('<div id="image-annotate-edit-form"><form><textarea id="image-annotate-text" name="text" rows="3" cols="30">' + this.note.text + '</textarea></form></div>');
        this.form = form;

        $('body').append(this.form);
        this.form.css('left', this.area.offset().left + 'px');
        this.form.css('top', (parseInt(this.area.offset().top) + parseInt(this.area.height()) + 7) + 'px');

        // Set the area as a draggable/resizable element contained in the image canvas.
        // Would be better to use the containment option for resizable but buggy
        area.resizable({
            handles: 'all',
            resize: function(e, ui) {
                if (parseInt(area.position().top) + parseInt(area.height()) + 2 > parseInt(image.canvas.height())) {
                    area.height(parseInt(image.canvas.height()) - parseInt(area.position().top) - 2);
                }
                if (parseInt(area.position().left) + parseInt(area.width()) + 2 > parseInt(image.canvas.width())) {
                    area.width(parseInt(image.canvas.width()) - parseInt(area.position().left) - 2);
                }
                if (parseInt(area.position().top) < 0) {
                    area.height(parseInt(image.canvas.height())).css('top', 0);
                }
                if (parseInt(area.position().left) < 0) {
                    area.width(parseInt(image.canvas.width())).css('left', 0);
                }
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            },
            stop: function(e, ui) {
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            }
        })
        .draggable({
            containment: image.canvas,
            drag: function(e, ui) {
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            },
            stop: function(e, ui) {
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            }
        });
        return this;
    };

    $.fn.annotateEdit.prototype.destroy = function() {
        /// <summary>
        ///   Destroys an editable annotation area.
        /// </summary>        
        this.image.canvas.children('.image-annotate-edit').hide();
        this.area.resizable('destroy');
        this.area.draggable('destroy');
        this.area.css('height', '');
        this.area.css('width', '');
        this.area.css('left', '');
        this.area.css('top', '');
        this.form.remove();
    }

    $.fn.annotateView = function(image, note) {
        /// <summary>
        ///   Defines a annotation area.
        /// </summary>
        this.image = image.image;

        this.note = note;

        //this.editable = (note.editable && image.editable);
        this.editable = false;

        // Add the area
        this.area = $('<div class="image-annotate-area' + (this.editable ? ' image-annotate-area-editable' : '') + '"><a href="#comment-'+note.id+'"></a></div>');
        image.canvas.children('.image-annotate-view').prepend(this.area);

        // Add the note
        this.form = $('<div class="image-annotate-note">' + note.text + '</div>');
        this.form.hide();
        image.canvas.children('.image-annotate-view').append(this.form);
        this.form.children('span.actions').hide();

        // Set the position and size of the note
        this.setPosition();

        // Add the behavior: hide/display the note when hovering the area
        var annotation = this;
        this.area.hover(function() {
            annotation.show();
        }, function() {
            annotation.hide();
        });

        // Edit a note feature
        if (this.editable) {
            var form = this;
            this.area.click(function() {
                form.edit();
            });
        }
    };

    $.fn.annotateView.prototype.setPosition = function() {
        /// <summary>
        ///   Sets the position of an annotation.
        /// </summary>
        this.area.children('a').height((parseInt(this.note.height) - 2) + 'px');
        this.area.children('a').width((parseInt(this.note.width) - 2) + 'px');
        this.area.css('left', (this.note.left) + 'px');
        this.area.css('top', (this.note.top) + 'px');
        this.form.css('left', (this.note.left) + 'px');
        this.form.css('top', (parseInt(this.note.top) + parseInt(this.note.height) + 7) + 'px');
    };

    $.fn.annotateView.prototype.show = function() {
        /// <summary>
        ///   Highlights the annotation
        /// </summary>
        this.form.fadeIn(250);
        if (!this.editable) {
            this.area.addClass('image-annotate-area-hover');
        } else {
            this.area.addClass('image-annotate-area-editable-hover');
        }
    };

    $.fn.annotateView.prototype.hide = function() {
        /// <summary>
        ///   Removes the highlight from the annotation.
        /// </summary>      
        this.form.fadeOut(250);
        this.area.removeClass('image-annotate-area-hover');
        this.area.removeClass('image-annotate-area-editable-hover');
    };

    $.fn.annotateView.prototype.destroy = function() {
        /// <summary>
        ///   Destroys the annotation.
        /// </summary>      
        this.area.remove();
        this.form.remove();
    }

    $.fn.annotateView.prototype.edit = function() {
        /// <summary>
        ///   Edits the annotation.
        /// </summary>      
        if (this.image.mode == 'view') {
            this.image.mode = 'edit';
            var annotation = this;

            // Create/prepare the editable note elements
            //var editable = new $.fn.annotateEdit(this.image, this.note);

            //$.fn.annotateImage.createSaveButton(editable, this.image, annotation);

            // Add the delete button
            //var del = $('<a class="image-annotate-edit-delete">Delete</a>');
            //del.click(function() {
                //var form = $('#image-annotate-edit-form form');

                //$.fn.annotateImage.appendPosition(form, editable)

                //if (annotation.image.useAjax) {
                //    $.ajax({
                //        url: annotation.image.deleteUrl,
                //        data: form.serialize(),
                //        error: function(e) { alert("An error occured deleting that note.") }
                //    });
                //}

                //annotation.image.mode = 'view';
                //editable.destroy();
                //annotation.destroy();
            //});
            //editable.form.append(del);

            //$.fn.annotateImage.createCancelButton(editable, this.image);
        }
    };

    $.fn.annotateImage.appendPosition = function(form, editable) {
        /// <summary>
        ///   Appends the annotations coordinates to the given form that is posted to the server.
        /// </summary>
        var areaFields = $('<input type="hidden" value="' + editable.area.height() + '" name="height"/>' +
                           '<input type="hidden" value="' + editable.area.width() + '" name="width"/>' +
                           '<input type="hidden" value="' + (editable.area.position().top - 4) + '" name="top"/>' +
                           '<input type="hidden" value="' + (editable.area.position().left - 4) + '" name="left"/>' +
                           '<input type="hidden" value="' + editable.note.id + '" name="id"/>');
        form.append(areaFields);
    }

    $.fn.annotateView.prototype.resetPosition = function(editable, text) {
        /// <summary>
        ///   Sets the position of an annotation.
        /// </summary>
        this.form.html(text);
        this.form.hide();
        
        // Fix for padding
        editable.area.position().left = editable.area.position().left - 4;
        editable.area.position().top = editable.area.position().top - 4;

        // Resize
        this.area.children('a').height(editable.area.height() + 'px');
        this.area.children('a').width((editable.area.width() - 2) + 'px');
        this.area.css('left', (editable.area.position().left) + 'px');
        this.area.css('top', (editable.area.position().top) + 'px');
        this.area.css('z-index','9999')
        this.form.css('left', (editable.area.position().left) + 'px');
        this.form.css('top', (parseInt(editable.area.position().top) + parseInt(editable.area.height()) + 7) + 'px');

        // Save new position to note
        this.note.top = editable.area.position().top;
        this.note.left = editable.area.position().left;
        this.note.height = editable.area.height();
        this.note.width = editable.area.width();
        this.note.text = text;
        this.note.id = editable.note.id;
        this.editable = true;
    };

})(jQuery);function displayMemberFeeds(container) {
  var element = $("#"+container);
  if(element.length > 0) {
    var listing_box = element.find('.featured-feeds-box');
    var listing_box_id = listing_box.attr('id');
    var settings = listing_box_id.split("-");
    var limit = settings[3];
    var trim = settings[4];
    $.ajax({ 
      type: "GET", 
      url: "http://www.otaku.fm/themes/default/ajax/ajax.member.feed.listing.php", 
      data: {limit: limit, container: container, trim: trim}, 
      cache: false,
      dataType: "html", 
      beforeSend: function(){
        listing_box.parent('.gradient-box').hide();
        element.find('.featured-feeds-loading').show();
      },
      error: function(){
        element.find('.featured-feeds-loading').hide();
        listing_box.html('Error loading feeds');
        listing_box.parent('.gradient-box').show();
        
      },
      success: function(data){
        element.find('.featured-feeds-loading').hide();
        listing_box.html(data);
        listing_box.parent('.gradient-box').show();
      }
    });
  }
}

$(document).ready (function () { 
 $('#featured-feeds-refresh').click(function (event) {
   event.preventDefault();
   var listing_id = $('#featured-feeds-refresh').parents('.featured-feeds-list').attr('id');
   var listing_box_id = $('#'+listing_id).find('.featured-feeds-box').attr('id');
   var settings = listing_box_id.split("-");
   var limit = settings[3];
   var trim = settings[4];
   displayMemberFeeds(listing_id, limit, trim);
 });
});function refreshPollValues(poll_id, votes) {
  var votes = votes.split("|");
  var total_votes = 0;
  for (var i = 0; i < votes.length; i++) {
	total_votes += parseInt(votes[i]);
  }
  if(total_votes <= 0) total_votes = 1;
  var answers = new Array();
  for (var i = 0; i < votes.length; i++) {
	answers[i] = (votes[i]/total_votes)*100;
	answers[i] = answers[i].toFixed(0);
  }
  $(".poll").each(function(i) {
	var div_id = $(this).attr('id');
	var div_poll_id = div_id.split("_");
	div_poll_id = div_poll_id[0];
	if(poll_id == div_poll_id) {
	  $(this).find(".votes").each(function(i) {
		if(isNaN(answers[i])) answers[i] = 0;
		$(this).find(".votes_bar").css("width",answers[i]+"%");
		$(this).find(".votes_percent").html(answers[i]+"%");
	  });
	}
  });
}

function setPollVoted(poll_id) {
  $("form[name="+poll_id+"]").each(function(i) {
	$(this).find(".vote").remove();
	//$(this).find(".refresh").show();
	$(this).find(".answers input").each(function() {
	  $(this).remove();
	});
	var label = '';
	$(this).find(".answers label").each(function() {
	  label = $(this).html();
	  $(this).before('<strong>'+label+'</strong>').remove();
	});
  });
}

function loadPolls() {
	$(".poll").each(function(i) {
		var poll_id = $(this).attr('id');
		var div_id = poll_id+'_'+i
		$(this).attr('id',div_id);

		$("#"+div_id+" .loading").show();
		$("#"+div_id+" .vote").hide();

		if($(this).parents('.comment').length > 0){
		  item_type = 'comment';
		  var item_uid = $(this).parents('.comment').attr('id');
		  item_uid = item_uid.split('-');
		  item_uid = item_uid[1]; 
		} else {
		  var item_type = 'post';
		  var item_uid = $('.post-body').attr('id');
		  item_uid = item_uid.split('-');
		  item_uid = item_uid[2];
		}

		$.post (
		  "http://www.otaku.fm/themes/default/ajax/ajax.poll.php",
		  "poll_id="+poll_id+"&item_type="+item_type+"&item_uid="+item_uid,
		  function (data) {
			if (data.status == 'ok') {
			  refreshPollValues(poll_id, data.votes);
			  if($.cookie(item_type+'_'+item_uid+'_poll_'+poll_id)) {
				setPollVoted(poll_id);
			  } else {
				$("#"+div_id+" .vote").show();
				$("#"+div_id+" .answers input").each(function() {
				  $(this).show();
				});
			  }
			} else {
			  $("#"+div_id+" .error").html(data.msg);
			  $("#"+div_id+" .error").fadeIn('slow');
			}
			$("#"+div_id+" .loading").hide();
		  },
		  'json'
		);
	});
}

function loadCommentPolls(id) {
	$("#comment-"+id+" .poll").each(function(i) {
		var poll_id = $(this).attr('id');
		var div_id = poll_id+'_'+i
		$(this).attr('id',div_id);

		$("#"+div_id+" .loading").show();
		$("#"+div_id+" .vote").hide();

		if($(this).parents('.comment').length > 0){
		  item_type = 'comment';
		  var item_uid = $(this).parents('.comment').attr('id');
		  item_uid = item_uid.split('-');
		  item_uid = item_uid[1]; 
		} else {
		  var item_type = 'post';
		  var item_uid = $('.post-body').attr('id');
		  item_uid = item_uid.split('-');
		  item_uid = item_uid[2];
		}

		$.post (
		  "http://www.otaku.fm/themes/default/ajax/ajax.poll.php",
		  "poll_id="+poll_id+"&item_type="+item_type+"&item_uid="+item_uid,
		  function (data) {
			if (data.status == 'ok') {
			  refreshPollValues(poll_id, data.votes);
			  if($.cookie(item_type+'_'+item_uid+'_poll_'+poll_id)) {
				setPollVoted(poll_id);
			  } else {
				$("#"+div_id+" .vote").show();
				$("#"+div_id+" .answers input").each(function() {
				  $(this).show();
				});
			  }
			} else {
			  $("#"+div_id+" .error").html(data.msg);
			  $("#"+div_id+" .error").fadeIn('slow');
			}
			$("#"+div_id+" .loading").hide();
		  },
		  'json'
		);
	});
}

function bindPolls() {
	$("form.poll").each(function() {
	$(this).validate({
	  rules: {
		answer: {
		  required: true
		}
	  },
	  messages: {
		answer: {
		  required: "Please select an answer"
		}
	  },
	  errorElement: "div",
	  errorClass: "input-error",
	  errorPlacement: function(error, element) {
		element.parent().before(error);
	  },
	  submitHandler: function(form) {
		var form = $('#'+form.id);
		var poll_id = form.attr("id").split("_");
		poll_id = poll_id[0];
		if(form.parents('.comment').length > 0){
		  var item_type = 'comment';
		  var item_uid = form.parents('.comment').attr('id');
		  item_uid = item_uid.split('-');
		  item_uid = item_uid[1]; 
		} else {
		  var item_type = 'post';
		  var item_uid = $('.post-body').attr('id');
		  item_uid = item_uid.split('-');
		  item_uid = item_uid[2];
		}

		form.find(".error").hide();
		form.find(".saved").hide();

		form.find(".loading").show();
		form.find(".vote").hide();

		$.post (
		  "http://www.otaku.fm/themes/default/ajax/ajax.poll.php",
		  form.serialize() + "&poll_id="+poll_id+"&item_type="+item_type+"&item_uid="+item_uid,
		  function (data) {
			if (data.status == 'ok') {
			  form.find(".saved").fadeIn('slow');
			  setTimeout (function () { form.find(".saved").fadeOut('slow'); }, 10000);
			  refreshPollValues(poll_id, data.votes);
			  setPollVoted(poll_id);
			} else if(data.status == 'voted') {
			  form.find(".voted").fadeIn('slow');
			  setTimeout (function () { form.find(".voted").fadeOut('slow'); }, 15000);
			} else {
			  form.find(".error").html(data.msg);
			  form.find(".error").fadeIn('slow');
			  setTimeout (function () { form.find(".error").fadeOut('slow'); }, 15000);
			}
			form.find(".loading").hide();
			form.find(".vote").show();
		  },
		  'json'
		);
		return false;
	  }
	});
  });
}

$(document).ready(function() {
	loadPolls();
	bindPolls();
});$(document).ready (function () {
	$('.settings-dropdown').hover(
		function () {
			$(this).children('.dropdown-link').children('img').attr('src', "http://www.otaku.fm/themes/default/img/settings-dropdown-on.png?v=20090424");
		},
		function () {
			$(this).children('.dropdown-link').children('img').attr('src', "http://www.otaku.fm/themes/default/img/settings-dropdown-off.png?v=20090424");
		}
	);
});
$(document).ready (function () {
	$('#mg-user-panel-login-link').click(function (event) {
		event.preventDefault();
		$('#mg-user-panel-login-options').hide();
		$('#mg-user-panel-login-form').slideToggle();
	});
	
	$('#mg-user-panel-login-cancel').click(function (event) {
		event.preventDefault();
		$('#mg-user-panel-login-form').hide();
		$('#mg-user-panel-login-options').slideToggle();
	});
});function bind_minimize(minimize)
{
	var box = minimize.parent('.mg-box');
	var button = minimize.children('.mg-box-minimize-button');
	var title = minimize.children('.mg-box-minimize-title');
	
	button.unbind('click');
	button.click(function (event)
	{
		event.preventDefault();
		box_minimize(minimize);
		$.cookie(box.attr('id'), 0, { expires: 360, path: '/'});
	});
	
	title.unbind('click');
	title.click(function (event)
	{
		event.preventDefault();
		box_minimize(minimize);
		$.cookie(box.attr('id'), 0, { expires: 360, path: '/'});
	});
	
	button.mouseover(function()
	{
		box.addClass('mg-box-highlight');
	}).mouseout(function()
	{
		box.removeClass('mg-box-highlight');
	});
}

function bind_maximize(minimize)
{
	var box = minimize.parent('.mg-box');
	var button = minimize.children('.mg-box-minimize-button');
	var title = minimize.children('.mg-box-minimize-title');
	
	button.unbind('mouseover');
	box.removeClass('mg-box-highlight');
	
	button.unbind('click');
	button.click(function (event)
	{
		event.preventDefault();
		box_maximize(minimize);
		$.cookie(box.attr('id'), 1, { expires: 360, path: '/'});
	});
	
	title.unbind('click');
	title.click(function (event)
	{
		event.preventDefault();
		box_maximize(minimize);
		$.cookie(box.attr('id'), 1, { expires: 360, path: '/'});
	});
}

function box_minimize(minimize)
{
	var box = minimize.parent('.mg-box');
	var button = minimize.children('.mg-box-minimize-button');
	
	bind_maximize(minimize);

	box.children('.mg-box-minimize-content').animate(
	{ 
		height: "hide",
		opacity: "hide"
	}, 600, function() {
		box.children('.mg-box-minimize-content').hide();
	});
	
	minimize.children('.mg-box-minimize-title').fadeIn();
	
	button.children('img').attr('src', 'http://www.otaku.fm/themes/default/img/maximize.png?v=20090424');
	button.children('img').attr('alt', 'Maximize');
	button.attr('title', 'Maximize');
	box.addClass('mg-box-minimized');
}

function box_maximize(minimize)
{
	var box = minimize.parent('.mg-box');
	var button = minimize.children('.mg-box-minimize-button');
	
	bind_minimize(minimize);
	
	minimize.children('.mg-box-minimize-title').fadeOut();
	
	box.children('.mg-box-minimize-content').animate(
	{ 
		height: "show",
		opacity: "show"
	}, 600, function() {
		box.children('.mg-box-minimize-content').show();
	});
	
	button.mouseover(function()
	{
		var box = $(this).parent('.mg-box-minimize').parent('.mg-box');
		box.addClass('mg-box-highlight');
	}).mouseout(function()
	{
		var box = $(this).parent('.mg-box-minimize').parent('.mg-box');
		box.removeClass('mg-box-highlight');
	});
	
	button.children('img').attr('src', 'http://www.otaku.fm/themes/default/img/minimize.png?v=20090424');
	button.children('img').attr('alt', 'Minimize');
	button.attr('title', 'Minimize');
	box.removeClass('mg-box-minimized');
}

$(document).ready (function ()
{
	$('.mg-box-minimize-button').each(function()
	{
		var minimize = $(this).parent('.mg-box-minimize');
		var box = minimize.parent('.mg-box');
		var cookie = box.attr('id');
		
		if( ! $.cookie(cookie))
		{
			if (box.children('.mg-box-minimize-content').is(':visible'))
			{
				bind_minimize(minimize);
			}
			else
			{
				bind_maximize(minimize);
			}
		}
		else
		{
			if($.cookie(cookie) == '1')
			{
				box_maximize(minimize);
			}
			else if($.cookie(cookie) == '0')
			{
				box_minimize(minimize);
			}
		}
	});
	
	
	// TODO: LEGACY
	
	$('.mg-msg-box-close').click(function (event) {
		event.preventDefault();
		var msg_box_id = $(this).parent('.mg-msg-box').attr('id');
		$(this).parent('.mg-msg-box').animate(
		{ 
			height: "hide",
			opacity: "hide"
		}, 600);
		$.cookie(msg_box_id, 1, { expires: 360, path: '/'});
	});
	
	$('.mg-msg-box').each(function() {
		var msg_box_id = $(this).attr('id');
		if( ! $.cookie(msg_box_id)) {
			$(this).show();
		}
	});
});$(document).ready (function ()
{
	$('#mode a').click(function(event) {
		if (navigator.userAgent.match(/(iPhone|iPod|Android)/)) {
			event.preventDefault();
			$.cookie('iphone_mode', null, { path: '/'});
			window.location.href = $('#mode a').attr('href');
		}
	});
});// This module depends on jquery.ui.dialog

function AlertDialog (title/*, text*/)
{
  var text     = (arguments.length >= 2) ? arguments[1] : title;
  var callback = (arguments.length >= 3) ? arguments[2] : null;
  if (arguments.length == 1) { title = 'Alert'; }

  $('<div style="font-size: 10pt;">' + text + '</div>').dialog({
    title : title,
    bgiframe: true,
    modal: true,
    width: "24em",
    overlay: {
      backgroundColor: '#000',
      opacity:         0.5
    },
    buttons: {
      Close: function() {
        $(this).dialog('close');
        if (callback != null)
          callback();
      }
    }
  });
}

function ConfirmDialog (title, text, options)
{
  var options = $.extend ({
    ok        : 'OK',
    cancel    : 'Cancel',
    onConfirm : null,
    onCancel  : null
  }, arguments[2] || {});

  var boptions = {};
  boptions[options.cancel] = function () {
    $(this).dialog('close');
    if (options.onCancel != null) { options.onCancel (); }
  };
  boptions[options.ok] = function() {
    $(this).dialog('close');
    if (options.onConfirm != null) { options.onConfirm (); }
  };
  
  $('<div style="font-size: 10pt;">' + text + '</div>').dialog({
    title : title,
    bgiframe: true,
    width: "auto",
    modal: true,
    overlay: {
      backgroundColor: '#000',
      opacity:         0.5
    },
    buttons: boptions
  });
}

$(document).ready (function () {	
	//displayYUIButtons();
	
	
function ComCount(){
	 var n = 0;
	 $('.comment').each(function(){
		 n++;
	 });
	 return n;
} 
	 
 var m = 0;
	 
 if($.cookie('melissa_display_name') && $.cookie('melissa_user_name') && $.cookie('melissa_avatar')) {
	 $('#comment-header').hide();
	 $('#comment-footer').hide();
	 $('.comment-header-button').show();
	 m = ComCount();
	 if(m>3){
			$('.comment-footer-button').show();
	 }else{
			$('.comment-footer-button').hide();
	 }
	
 } else {
	 $('#comment-header').show();
		m = ComCount();
	 if(m>3){
			 $('#comment-footer').show();
		}else{
			 $('#comment-footer').hide();
		}
	 $('.comment-header-button').hide();
	 $('.comment-footer-button').hide();
 }


$('.comment-button .btn, .comment-reply').live("click", function (event) {
	event.preventDefault();
	var comment_id = $(this).parent('.comment-button').attr('id');
	var settings = comment_id.split("-");
	var item_type = settings[0];
	var item_id = settings[1];
	var parent = settings[2];
	var language = settings[3];
	var parent_author = settings[4];
	var page = location.pathname;
	$('#comment-form-'+parent).show();
	$('#comment-form-'+parent).html('<div class="loading">&nbsp;</div>');
	$('#comment-form-'+parent).load ("http://www.otaku.fm/themes/default/ajax/ajax.comment.form.php", { parent: parent, item_id : item_id, item_type : item_type , page : page, language : language, parent_author : parent_author}, function (response, status) {
		if(status == 'error') {
			$('#comment-form-'+parent).hide();
			var url = encodeURIComponent(window.location.pathname);
			if(response=='revoked') {
				window.location.replace("/melissa/site/ja/signin/?e=8&redirect="+url);
			} else {
				window.location.replace("/melissa/site/ja/signin/?redirect="+url);
			}
		}
	});
	$(this).parent('.comment-button').toggle();
});

$('.comment-cancel-button').live("click", function () {
	var comment_id = this.id;
	var settings = comment_id.split("-");
	var item_type = settings[3];
	var item_id = settings[4];
	var parent = settings[5];
	var language = settings[6];
	var parent_author = settings[7];
	$('#comment-form-'+parent).hide();
	$('#comment-form-'+parent).html('');
	$('#'+item_type+'-'+item_id+'-'+parent+'-'+language+'-'+parent_author).toggle();
});

	
	displayMemberFeeds("featured-feeds-list");
	
	if($.cookie('melissa_display_name') && $.cookie('melissa_user_name') && $.cookie('melissa_avatar') && $.cookie('melissa_login')) {
		$('#mg-user-menu-welcome').html("<img id='mg-user-menu-avatar' src='"+$.cookie('melissa_avatar')+"' /><div id='mg-user-menu-cite'>&nbsp;"+$.cookie('melissa_display_name').replace(/\+/g, ' ')+"</div>");
		$('#mg-user-menu-options .mega-menu-dropdown').prepend("<a href='/profile/ja/"+$.cookie('melissa_user_name')+"/'>プロフィールページ</a><a href='/melissa/site/ja/profile/member-feed/'>個人の特集されるフィード</a><div class='hr-simple'><hr /></div>");
		$('#mg-user-menu-options').show();
		$('#mg-user-menu-login').hide();
		var mg_user_panel = $('#mg-user-panel');
		if(mg_user_panel.length > 0) {
			$.ajax({
				url: "http://www.otaku.fm/themes/default/ajax/ajax.user.panel.php",
				type: 'POST',
				data: {
					language: 'ja',
					login: $.cookie('melissa_login'),
					user_name: $.cookie('melissa_user_name'),
					avatar: $.cookie('melissa_avatar'),
					nickname: $.cookie('melissa_display_name').replace(/\+/g, ' ')
				},
				success: function(data) {
					$('#mg-user-panel-login-form').remove();
					$('#mg-user-panel-login-options').remove();
					$('#mg-user-panel').append(data);
					$('#mg-user-panel').show();
				}
			});
		}
		$('#mg-user-welcome').hide();
	} else {
		$('#mg-user-menu-options').hide();
		$('#mg-user-menu-login').show();
		$('#mg-user-panel').show();
		$('#mg-user-welcome').show();
	}
	
	$("#mg-search-form").validate({
			errorPlacement: function(error, element) {
				// Do nothing
			},
			errorClass: "",
			submitHandler: function(form) {
				if($('#mg-search-form-value').val() == '検索') {
					return false;
				} else {
					form.submit();
				}
			}
	});
});

