/**
 * @class {Object} com.omniacomputing.HCardMapper
 * 
 * @author 		Gordon Oheim 
 * @copyright	Omnia Computing (www.omnia-computing.de)
 * @namespace 	com.omniacomputing
 * @license 	MIT (see file hcardmapper.license.txt)
 * @version		0.96
 */
if(typeof com!='object')com={};if(typeof com.omniacomputing!='object')com.omniacomputing={};com.omniacomputing.HCardMapper=function HCardMapper(config){var config=config||{};if(!config.mappings){if(typeof console=='object'){console.error('You must specify a mappings literal in the config Object.');}return false;}var msg={alreadyInitialized:'HCardMapper is already initialized.',invalidHttpUri:'Param is not a valid HTTP/HTTPS resource:',enterValidUri:'Enter a valid URI',errorReadingUri:'Error while reading URI',missingFn:'The hCard is invalid (missing FN property)',errorOnMapping:'Error during HCard mapping: ',hCardIsNoObject:'HCard property is not an object: ',generalException:'Exception caught in',ajaxRequestFailed:'AJAX Request failed: ',uriSelectorTriggerTitle:'Click to activate the hCard Reader',uriSelectorTriggerLinkText:'Use my hCard',uriSelectorMessage:'Enter the URI where your hCard is located in the field below. Then click the button to fetch the hCard. To learn more about the hCard microformat visit <a href="http://microformats.org" rel="external">Microformats.org</a>',triggerButtonValue:'Fetch hCard',resetButtonValue:'Cancel',fieldsetLegend:'Multiple hCards found. Which hCard listed below do you want to use?',fieldsetButton:'Use selected hCard',indicatorText:'Loading... '};if(typeof config.msg=='object'){for(m in config.msg)msg[m]=config.msg[m];}var initialized=false;var loadIcon=config.loadIcon||'/images/icons/ajax-loader.gif';var triggerButton=config.triggerButton||'hcard-reader';var resetButton=config.resetButton||'hcard-cancel';var hCardUri=config.hCardUri||'hcard-uri';var proxy=config.proxy||'/contact/hcard?uri=';var param=null;var form=config.form||document.forms[0];var mappings=config.mappings;var HCard;var hCards;var insertBelowEl=config.insertBelowEl||form.down('p');var uriSelector=new Template('<div id="hcr">'+'<a href="javascript:hcr.toggle()" title="#{uriSelectorTriggerTitle}">#{uriSelectorTriggerLinkText}</a>'+'<div style="display:none"><p>#{uriSelectorMessage}</p>'+'<label for="#{hCardUri}">URI</label>'+'<input id="#{hCardUri}" name="hcard_uri" value="http://"/>'+'<input id="#{triggerButton}" type="button" value="#{triggerButtonValue}"/>'+'<input id="#{resetButton}" type="button" value="#{resetButtonValue}"/>'+'</div>'+'</div>');var foundCardsTemplate=new Template('<input id="hcr-#{index}" name="hcr-hcard"'+' type="radio"  value="#{index}" style="display:inline"/>'+'<label for="hcr-#{index}">#{name}</label><br/>');var selectionFieldsetTemplate=new Template('<fieldset id="hcr-select-dialogue" style="display:none">'+'<legend>#{fieldsetLegend}</legend>'+'#{html}'+'<input id="hcr-selector" type="button" value="#{fieldsetButton}"/>'+'</fieldset>');var indicator=new Template('<span id="hcr-status">#{indicatorText}<img src="#{loadIcon}" alt="Ajax Loading Indicator"></span>');var hcrToggle=function(){var el=$('hcr').down('div');(el.visible())?new Effect.Fade(el):new Effect.Appear(el);};var register=function(){if(initialized===true){if(typeof console=='object'){console.warn(this,msg.alreadyInitialized);}return false;}else{var tpl=uriSelector.evaluate({hCardUri:hCardUri,uriSelectorTriggerTitle:msg.uriSelectorTriggerTitle,uriSelectorTriggerLinkText:msg.uriSelectorTriggerLinkText,uriSelectorMessage:msg.uriSelectorMessage,triggerButton:triggerButton,triggerButtonValue:msg.triggerButtonValue,resetButton:resetButton,resetButtonValue:msg.resetButtonValue});Element.insert(insertBelowEl,{after:tpl});Event.observe(triggerButton,'click',getHCardFromUri);Event.observe(resetButton,'click',hcrToggle);initialized=true;return true;}};var updateParam=function(){str=$F(hCardUri).strip();if(!isUri(str)){if(typeof console=='object'){console.warn(msg.invalidHttpUri,str);}$(hCardUri).value=msg.enterValidUri;return false;}param=encodeURIComponent(str);return true;};var isUri=function(uri){var regexp=/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;return regexp.test(uri);};var unique=function(a){var contains=function(a,e){for(j=0;j<a.length;j++){if(Object.toJSON(a[j])===Object.toJSON(e))return true;}return false;};var tmp=new Array(0);for(i=0;i<a.length;i++){if(!contains(tmp,a[i])){tmp.length+=1;tmp[tmp.length-1]=a[i];}}return tmp;};var showSelectionDialogue=function(){var index=0;var html='';hCards.each(function(hCard){html+=foundCardsTemplate.evaluate({index:index++,name:buildFnAndOrg(hCard)});});html=selectionFieldsetTemplate.evaluate({html:html,fieldsetLegend:msg.fieldsetLegend,fieldsetButton:msg.fieldsetButton});if($('hcr-select-dialogue'))Element.remove('hcr-select-dialogue');Element.insert(triggerButton,{after:html});Event.observe('hcr-selector','click',function(e){var form=Event.element(e).up('form');var sel=form.getInputs('radio','hcr-hcard').find(function(radio){return radio.checked});HCard=hCards[sel.getValue()];new Effect.Fade($('hcr').down('div'),{afterFinish:function(){Element.remove('hcr-select-dialogue');}});guessNFromFN();mapHCardToFormFields();});new Effect.Appear($('hcr-select-dialogue'));};var buildFnAndOrg=function(hCard){var hCard=hCard||HCard;var fnAndOrg=msg.missingFn;if((hCard.org==hCard.fn)||((!hCard.org)&&(hCard.fn))){return hCard.fn;}if((hCard.org)&&(hCard.fn)){return hCard.fn+((typeof hCard.org=='string')?' ('+hCard.org+')':'');}if((hCard.n.familyName)&&(hCard.givenName)){fnAndOrg=hCard.familyName+', '+hCard.givenName;fnAndOrg+=(typeof hCard.org=='string')?' ('+hCard.org+')':'';}return fnAndOrg.unescapeHTML();};var mapHCardToFormFields=function(currentObject,prop){try{var o=(typeof currentObject=='object')?currentObject:HCard;interceptTypeValueObject(o,prop);for(p in o){if(typeof o[p]==='string'){o[p]=o[p].unescapeHTML();findPropertyInMapping(o,p,mappings);}else if(!Object.isArray(o[p])){convertOpenStructToObject(o,p,prop||false);}else if(Object.isArray(o[p])){o[p]=o[p][0];if(typeof o[p]==='string'){findPropertyInMapping(o,p,mappings);}else{mapHCardToFormFields(o[p],p);}}}}catch(e){if(typeof console=='object'){console.log(msg.errorOnMapping,e,o,HCard);}}};var findPropertyInMapping=function(o,p,ms){Object.keys(ms).find(function(m){if(typeof ms[m]=='object'){findPropertyInMapping(o,p,ms[m]);}var match=p.toLowerCase().replace(/-/g,'_');if((m.toLowerCase()==match)&&($(ms[m]))){$(ms[m]).value=o[p];return true;}});};var convertOpenStructToObject=function(o,p,t){if(p==='table'){var bag={};if(o[p].type&&o[p].value){if(Object.isArray(o[p].type)){var i=0;o[p].type.each(function(t){bag[t]=o[p].value[i];i++;});}else{bag[o[p].type]=o[p].value;}mapHCardToFormFields(bag);}else if(!o[p].type&&o[p].value){bag[t]=o[p].value;mapHCardToFormFields(bag);}}mapHCardToFormFields(o[p],p);};var interceptTypeValueObject=function(o,t){if(o!==null){if(o.type&&o.value){var bag={};bag[o.type]=o.value;mapHCardToFormFields(bag);}if(o.href&&o.value){var bag={};bag[t]=o.value;mapHCardToFormFields(bag);}}};var guessNFromFN=function(){if((HCard.fn!=HCard.org)&&(!HCard.n)){if(HCard.fn.split(' ').length==2){var n=HCard.fn.split(' ');HCard.n={'given_name':n[0],'family_name':n[1]};if(n[0].endsWith(',')){HCard.n={'given_name':n[1],'family_name':n[0].substring(0,n[0].length-1)};}else if((n[1].endsWith('.'))&&(n[1].length==2)){HCard.n={'given_name':n[0],'family_name':n[1]};}}}};var getHCardFromUri=function(){if(!updateParam())return false;form.reset();$(hCardUri).value=decodeURIComponent(param);new Ajax.Request(proxy.concat(param),{method:'get',evalJS:false,onCreate:cbOnCreate,onComplete:cbOnComplete,onException:cbOnException,onFailure:cbOnFailure,onLoaded:cbOnLoaded,onLoading:cbOnLoading,onSuccess:cbOnSuccess});};function assignAjaxResponse(r){if(r.hcard){r=r.hcard;}if(r.vcard){r=r.vcard[0];}if(Object.isArray(r)){hCards=unique(rl);HCard=null;}else{hCards=null;HCard=r;}};var cbOnSuccess=config.cbOnSuccess||function(transport){var retVal=transport.responseText.evalJSON(true);assignAjaxResponse(retVal);};var cbOnCreate=config.cbOnCreate||function(){return true;};var cbOnComplete=config.cbOnComplete||function(){if((Object.isArray(hCards))&&(hCards.length>0)){showSelectionDialogue();}else if(typeof HCard=='object'){guessNFromFN();mapHCardToFormFields();}else{if(typeof console=='object'){console.error(msg.hCardIsNoObject,HCard);}return false;}if($('hcr-status')){Element.remove('hcr-status');}return true;};var cbOnException=config.cbOnException||function(requester,exception){if(typeof console=='object'){console.error(msg.generalException,requester,'with',exception);}if($('hcr-status')){Element.remove('hcr-status');}$(hCardUri).value=msg.errorReadingUri;return false;};var cbOnLoaded=config.cbOnLoaded||function(){return true;};var cbOnLoading=config.cbOnLoading||function(){Element.insert($('hcr'),{top:indicator.evaluate({indicatorText:msg.indicatorText,loadIcon:loadIcon})});};var cbOnFailure=config.cbOnFailure||function(transport){if(typeof console=='object'){console.error(msg.ajaxRequestFailed,transport);}Element.remove('hcr-status');$(hCardUri).value=msg.errorReadingUri;return false;};var publicObject={init:register,toggle:hcrToggle};if(config.register===true)register();if(config.debug===true){publicObject['debug']=function(json){assignAjaxResponse(json);cbOnComplete();}}return publicObject;};