//SWFADDRESS
/**
 * SWFAddress 2.4: Deep linking for Flash and Ajax <http://www.asual.com/swfaddress/>
 *
 * SWFAddress is (c) 2006-2009 Rostislav Hristov and contributors
 * This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
 *
 */
if(typeof asual=="undefined"){var asual={}}if(typeof asual.util=="undefined"){asual.util={}}asual.util.Browser=new function(){var b=navigator.userAgent.toLowerCase(),a=/webkit/.test(b),e=/opera/.test(b),c=/msie/.test(b)&&!/opera/.test(b),d=/mozilla/.test(b)&&!/(compatible|webkit)/.test(b),f=parseFloat(c?b.substr(b.indexOf("msie")+4):(b.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1]);this.toString=function(){return"[class Browser]"};this.getVersion=function(){return f};this.isMSIE=function(){return c};this.isSafari=function(){return a};this.isOpera=function(){return e};this.isMozilla=function(){return d}};asual.util.Events=new function(){var c="DOMContentLoaded",j="onstop",k=window,h=document,b=[],a=asual.util,e=a.Browser,d=e.isMSIE(),g=e.isSafari();this.toString=function(){return"[class Events]"};this.addListener=function(n,l,m){b.push({o:n,t:l,l:m});if(!(l==c&&(d||g))){if(n.addEventListener){n.addEventListener(l,m,false)}else{if(n.attachEvent){n.attachEvent("on"+l,m)}}}};this.removeListener=function(p,m,n){for(var l=0,o;o=b[l];l++){if(o.o==p&&o.t==m&&o.l==n){b.splice(l,1);break}}if(!(m==c&&(d||g))){if(p.removeEventListener){p.removeEventListener(m,n,false)}else{if(p.detachEvent){p.detachEvent("on"+m,n)}}}};var i=function(){for(var m=0,l;l=b[m];m++){if(l.t!=c){a.Events.removeListener(l.o,l.t,l.l)}}};var f=function(){if(h.readyState=="interactive"){function l(){h.detachEvent(j,l);i()}h.attachEvent(j,l);k.setTimeout(function(){h.detachEvent(j,l)},0)}};if(d||g){(function(){try{if((d&&h.body)||!/loaded|complete/.test(h.readyState)){h.documentElement.doScroll("left")}}catch(m){return setTimeout(arguments.callee,0)}for(var l=0,m;m=b[l];l++){if(m.t==c){m.l.call(null)}}})()}if(d){k.attachEvent("onbeforeunload",f)}this.addListener(k,"unload",i)};asual.util.Functions=new function(){this.toString=function(){return"[class Functions]"};this.bind=function(f,b,e){for(var c=2,d,a=[];d=arguments[c];c++){a.push(d)}return function(){return f.apply(b,a)}}};var SWFAddressEvent=function(d){this.toString=function(){return"[object SWFAddressEvent]"};this.type=d;this.target=[SWFAddress][0];this.value=SWFAddress.getValue();this.path=SWFAddress.getPath();this.pathNames=SWFAddress.getPathNames();this.parameters={};var c=SWFAddress.getParameterNames();for(var b=0,a=c.length;b<a;b++){this.parameters[c[b]]=SWFAddress.getParameter(c[b])}this.parameterNames=c};SWFAddressEvent.INIT="init";SWFAddressEvent.CHANGE="change";SWFAddressEvent.INTERNAL_CHANGE="internalChange";SWFAddressEvent.EXTERNAL_CHANGE="externalChange";var SWFAddress=new function(){var _getHash=function(){var index=_l.href.indexOf("#");return index!=-1?_ec(_dc(_l.href.substr(index+1))):""};var _getWindow=function(){try{top.document;return top}catch(e){return window}};var _strictCheck=function(value,force){if(_opts.strict){value=force?(value.substr(0,1)!="/"?"/"+value:value):(value==""?"/":value)}return value};var _ieLocal=function(value,direction){return(_msie&&_l.protocol=="file:")?(direction?_value.replace(/\?/,"%3F"):_value.replace(/%253F/,"?")):value};var _searchScript=function(el){if(el.childNodes){for(var i=0,l=el.childNodes.length,s;i<l;i++){if(el.childNodes[i].src){_url=String(el.childNodes[i].src)}if(s=_searchScript(el.childNodes[i])){return s}}}};var _titleCheck=function(){if(_d.title!=_title&&_d.title.indexOf("#")!=-1){_d.title=_title}};var _listen=function(){if(!_silent){var hash=_getHash();var diff=!(_value==hash);if(_safari&&_version<523){if(_length!=_h.length){_length=_h.length;if(typeof _stack[_length-1]!=UNDEFINED){_value=_stack[_length-1]}_update.call(this,false)}}else{if(_msie&&diff){if(_version<7){_l.reload()}else{this.setValue(hash)}}else{if(diff){_value=hash;_update.call(this,false)}}}if(_msie){_titleCheck.call(this)}}};var _bodyClick=function(e){if(_popup.length>0){var popup=window.open(_popup[0],_popup[1],eval(_popup[2]));if(typeof _popup[3]!=UNDEFINED){eval(_popup[3])}}_popup=[]};var _swfChange=function(){for(var i=0,id,obj,value=SWFAddress.getValue(),setter="setSWFAddressValue";id=_ids[i];i++){obj=document.getElementById(id);if(obj){if(obj.parentNode&&typeof obj.parentNode.so!=UNDEFINED){obj.parentNode.so.call(setter,value)}else{if(!(obj&&typeof obj[setter]!=UNDEFINED)){var objects=obj.getElementsByTagName("object");var embeds=obj.getElementsByTagName("embed");obj=((objects[0]&&typeof objects[0][setter]!=UNDEFINED)?objects[0]:((embeds[0]&&typeof embeds[0][setter]!=UNDEFINED)?embeds[0]:null))}if(obj){obj[setter](value)}}}else{if(obj=document[id]){if(typeof obj[setter]!=UNDEFINED){obj[setter](value)}}}}};var _jsDispatch=function(type){this.dispatchEvent(new SWFAddressEvent(type));type=type.substr(0,1).toUpperCase()+type.substr(1);if(typeof this["on"+type]==FUNCTION){this["on"+type]()}};var _jsInit=function(){if(_util.Browser.isSafari()){_d.body.addEventListener("click",_bodyClick)}_jsDispatch.call(this,"init")};var _jsChange=function(){_swfChange();_jsDispatch.call(this,"change")};var _update=function(internal){_jsChange.call(this);if(internal){_jsDispatch.call(this,"internalChange")}else{_jsDispatch.call(this,"externalChange")}_st(_functions.bind(_track,this),10)};var _track=function(){var value=(_l.pathname+(/\/$/.test(_l.pathname)?"":"/")+this.getValue()).replace(/\/\//,"/").replace(/^\/$/,"");var fn=_t[_opts.tracker];if(typeof fn==FUNCTION){fn(value)}else{if(typeof _t.pageTracker!=UNDEFINED&&typeof _t.pageTracker._trackPageview==FUNCTION){_t.pageTracker._trackPageview(value)}else{if(typeof _t.urchinTracker==FUNCTION){_t.urchinTracker(value)}}}};var _htmlWrite=function(){var doc=_frame.contentWindow.document;doc.open();doc.write("<html><head><title>"+_d.title+"</title><script>var "+ID+' = "'+_getHash()+'";<\/script></head></html>');doc.close()};var _htmlLoad=function(){var win=_frame.contentWindow;var src=win.location.href;_value=(typeof win[ID]!=UNDEFINED?win[ID]:"");if(_value!=_getHash()){_update.call(SWFAddress,false);_l.hash=_ieLocal(_value,TRUE)}};var _load=function(){if(!_loaded){_loaded=TRUE;if(_msie&&_version<8){var frameset=_d.getElementsByTagName("frameset")[0];_frame=_d.createElement((frameset?"":"i")+"frame");if(frameset){frameset.insertAdjacentElement("beforeEnd",_frame);frameset[frameset.cols?"cols":"rows"]+=",0";_frame.src="javascript:false";_frame.noResize=true;_frame.frameBorder=_frame.frameSpacing=0}else{_frame.src="javascript:false";_frame.style.display="none";_d.body.insertAdjacentElement("afterBegin",_frame)}_st(function(){_events.addListener(_frame,"load",_htmlLoad);if(typeof _frame.contentWindow[ID]==UNDEFINED){_htmlWrite()}},50)}else{if(_safari){if(_version<418){_d.body.innerHTML+='<form id="'+ID+'" style="position:absolute;top:-9999px;" method="get"></form>';_form=_d.getElementById(ID)}if(typeof _l[ID]==UNDEFINED){_l[ID]={}}if(typeof _l[ID][_l.pathname]!=UNDEFINED){_stack=_l[ID][_l.pathname].split(",")}}}_st(_functions.bind(function(){_jsInit.call(this);_jsChange.call(this);_track.call(this)},this),1);if(_msie&&_version>=8){_d.body.onhashchange=_functions.bind(_listen,this);_si(_functions.bind(_titleCheck,this),50)}else{_si(_functions.bind(_listen,this),50)}}};var ID="swfaddress",FUNCTION="function",UNDEFINED="undefined",TRUE=true,FALSE=false,_util=asual.util,_browser=_util.Browser,_events=_util.Events,_functions=_util.Functions,_version=_browser.getVersion(),_msie=_browser.isMSIE(),_mozilla=_browser.isMozilla(),_opera=_browser.isOpera(),_safari=_browser.isSafari(),_supported=FALSE,_t=_getWindow(),_d=_t.document,_h=_t.history,_l=_t.location,_si=setInterval,_st=setTimeout,_dc=decodeURI,_ec=encodeURI,_frame,_form,_url,_title=_d.title,_length=_h.length,_silent=FALSE,_loaded=FALSE,_justset=TRUE,_juststart=TRUE,_ref=this,_stack=[],_ids=[],_popup=[],_listeners={},_value=_getHash(),_opts={history:TRUE,strict:TRUE};if(_msie&&_d.documentMode&&_d.documentMode!=_version){_version=_d.documentMode!=8?7:8}_supported=(_mozilla&&_version>=1)||(_msie&&_version>=6)||(_opera&&_version>=9.5)||(_safari&&_version>=312);if(_supported){if(_opera){history.navigationMode="compatible"}for(var i=1;i<_length;i++){_stack.push("")}_stack.push(_getHash());if(_msie&&_l.hash!=_getHash()){_l.hash="#"+_ieLocal(_getHash(),TRUE)}_searchScript(document);var _qi=_url?_url.indexOf("?"):-1;if(_qi!=-1){var param,params=_url.substr(_qi+1).split("&");for(var i=0,p;p=params[i];i++){param=p.split("=");if(/^(history|strict)$/.test(param[0])){_opts[param[0]]=(isNaN(param[1])?/^(true|yes)$/i.test(param[1]):(parseInt(param[1])!=0))}if(/^tracker$/.test(param[0])){_opts[param[0]]=param[1]}}}if(_msie){_titleCheck.call(this)}if(window==_t){_events.addListener(document,"DOMContentLoaded",_functions.bind(_load,this))}_events.addListener(_t,"load",_functions.bind(_load,this))}else{if((!_supported&&_l.href.indexOf("#")!=-1)||(_safari&&_version<418&&_l.href.indexOf("#")!=-1&&_l.search!="")){_d.open();_d.write('<html><head><meta http-equiv="refresh" content="0;url='+_l.href.substr(0,_l.href.indexOf("#"))+'" /></head></html>');_d.close()}else{_track()}}this.toString=function(){return"[class SWFAddress]"};this.back=function(){_h.back()};this.forward=function(){_h.forward()};this.up=function(){var path=this.getPath();this.setValue(path.substr(0,path.lastIndexOf("/",path.length-2)+(path.substr(path.length-1)=="/"?1:0)))};this.go=function(delta){_h.go(delta)};this.href=function(url,target){target=typeof target!=UNDEFINED?target:"_self";if(target=="_self"){self.location.href=url}else{if(target=="_top"){_l.href=url}else{if(target=="_blank"){window.open(url)}else{_t.frames[target].location.href=url}}}};this.popup=function(url,name,options,handler){try{var popup=window.open(url,name,eval(options));if(typeof handler!=UNDEFINED){eval(handler)}}catch(ex){}_popup=arguments};this.getIds=function(){return _ids};this.getId=function(index){return _ids[0]};this.setId=function(id){_ids[0]=id};this.addId=function(id){this.removeId(id);_ids.push(id)};this.removeId=function(id){for(var i=0;i<_ids.length;i++){if(id==_ids[i]){_ids.splice(i,1);break}}};this.addEventListener=function(type,listener){if(typeof _listeners[type]==UNDEFINED){_listeners[type]=[]}_listeners[type].push(listener)};this.removeEventListener=function(type,listener){if(typeof _listeners[type]!=UNDEFINED){for(var i=0,l;l=_listeners[type][i];i++){if(l==listener){break}}_listeners[type].splice(i,1)}};this.dispatchEvent=function(event){if(this.hasEventListener(event.type)){event.target=this;for(var i=0,l;l=_listeners[event.type][i];i++){l(event)}return TRUE}return FALSE};this.hasEventListener=function(type){return(typeof _listeners[type]!=UNDEFINED&&_listeners[type].length>0)};this.getBaseURL=function(){var url=_l.href;if(url.indexOf("#")!=-1){url=url.substr(0,url.indexOf("#"))}if(url.substr(url.length-1)=="/"){url=url.substr(0,url.length-1)}return url};this.getStrict=function(){return _opts.strict};this.setStrict=function(strict){_opts.strict=strict};this.getHistory=function(){return _opts.history};this.setHistory=function(history){_opts.history=history};this.getTracker=function(){return _opts.tracker};this.setTracker=function(tracker){_opts.tracker=tracker};this.getTitle=function(){return _d.title};this.setTitle=function(title){if(!_supported){return null}if(typeof title==UNDEFINED){return}if(title=="null"){title=""}title=_dc(title);_st(function(){_title=_d.title=title;if(_juststart&&_frame&&_frame.contentWindow&&_frame.contentWindow.document){_frame.contentWindow.document.title=title;_juststart=FALSE}if(!_justset&&_mozilla){_l.replace(_l.href.indexOf("#")!=-1?_l.href:_l.href+"#")}_justset=FALSE},10)};this.getStatus=function(){return _t.status};this.setStatus=function(status){if(!_supported){return null}if(typeof status==UNDEFINED){return}if(status=="null"){status=""}status=_dc(status);if(!_safari){status=_strictCheck((status!="null")?status:"",TRUE);if(status=="/"){status=""}if(!(/http(s)?:\/\//.test(status))){var index=_l.href.indexOf("#");status=(index==-1?_l.href:_l.href.substr(0,index))+"#"+status}_t.status=status}};this.resetStatus=function(){_t.status=""};this.getValue=function(){if(!_supported){return null}return _dc(_strictCheck(_ieLocal(_value,FALSE),FALSE))};this.setValue=function(value){if(!_supported){return null}if(typeof value==UNDEFINED){return}if(value=="null"){value=""}value=_ec(_dc(_strictCheck(value,TRUE)));if(value=="/"){value=""}if(_value==value){return}_justset=TRUE;_value=value;_silent=TRUE;_update.call(SWFAddress,true);_stack[_h.length]=_value;if(_safari){if(_opts.history){_l[ID][_l.pathname]=_stack.toString();_length=_h.length+1;if(_version<418){if(_l.search==""){_form.action="#"+_value;_form.submit()}}else{if(_version<523||_value==""){var evt=_d.createEvent("MouseEvents");evt.initEvent("click",TRUE,TRUE);var anchor=_d.createElement("a");anchor.href="#"+_value;anchor.dispatchEvent(evt)}else{_l.hash="#"+_value}}}else{_l.replace("#"+_value)}}else{if(_value!=_getHash()){if(_opts.history){_l.hash="#"+_dc(_ieLocal(_value,TRUE))}else{_l.replace("#"+_dc(_value))}}}if((_msie&&_version<8)&&_opts.history){_st(_htmlWrite,50)}if(_safari){_st(function(){_silent=FALSE},1)}else{_silent=FALSE}};this.getPath=function(){var value=this.getValue();if(value.indexOf("?")!=-1){return value.split("?")[0]}else{if(value.indexOf("#")!=-1){return value.split("#")[0]}else{return value}}};this.getPathNames=function(){var path=this.getPath(),names=path.split("/");if(path.substr(0,1)=="/"||path.length==0){names.splice(0,1)}if(path.substr(path.length-1,1)=="/"){names.splice(names.length-1,1)}return names};this.getQueryString=function(){var value=this.getValue(),index=value.indexOf("?");if(index!=-1&&index<value.length){return value.substr(index+1)}};this.getParameter=function(param){var value=this.getValue();var index=value.indexOf("?");if(index!=-1){value=value.substr(index+1);var p,params=value.split("&"),i=params.length,r=[];while(i--){p=params[i].split("=");if(p[0]==param){r.push(p[1])}}if(r.length!=0){return r.length!=1?r:r[0]}}};this.getParameterNames=function(){var value=this.getValue();var index=value.indexOf("?");var names=[];if(index!=-1){value=value.substr(index+1);if(value!=""&&value.indexOf("=")!=-1){var params=value.split("&"),i=0;while(i<params.length){names.push(params[i].split("=")[0]);i++}}}return names};this.onInit=null;this.onChange=null;this.onInternalChange=null;this.onExternalChange=null;(function(){var _args;if(typeof FlashObject!=UNDEFINED){SWFObject=FlashObject}if(typeof SWFObject!=UNDEFINED&&SWFObject.prototype&&SWFObject.prototype.write){var _s1=SWFObject.prototype.write;SWFObject.prototype.write=function(){_args=arguments;if(this.getAttribute("version").major<8){this.addVariable("$swfaddress",SWFAddress.getValue());((typeof _args[0]=="string")?document.getElementById(_args[0]):_args[0]).so=this}var success;if(success=_s1.apply(this,_args)){_ref.addId(this.getAttribute("id"))}return success}}if(typeof swfobject!=UNDEFINED){var _s2r=swfobject.registerObject;swfobject.registerObject=function(){_args=arguments;_s2r.apply(this,_args);_ref.addId(_args[0])};var _s2c=swfobject.createSWF;swfobject.createSWF=function(){_args=arguments;var swf=_s2c.apply(this,_args);if(swf){_ref.addId(_args[0].id)}return swf};var _s2e=swfobject.embedSWF;swfobject.embedSWF=function(){_args=arguments;if(typeof _args[8]==UNDEFINED){_args[8]={}}if(typeof _args[8].id==UNDEFINED){_args[8].id=_args[1]}_s2e.apply(this,_args);_ref.addId(_args[8].id)}}if(typeof UFO!=UNDEFINED){var _u=UFO.create;UFO.create=function(){_args=arguments;_u.apply(this,_args);_ref.addId(_args[0].id)}}if(typeof AC_FL_RunContent!=UNDEFINED){var _a=AC_FL_RunContent;AC_FL_RunContent=function(){_args=arguments;_a.apply(this,_args);for(var i=0,l=_args.length;i<l;i++){if(_args[i]=="id"){_ref.addId(_args[i+1])}}}}})()};


//JSON2
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);
/**
 * 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
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            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
        }
        // CAUTION: 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;
    }
};
/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = 0;
  this.offsetHorizontal_ = -25;
  this.height_ = 115;
  this.width_ = 276;
  this.content_ = opts.content;
  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}

/* InfoBox extends GOverlay class from the Google Maps API
 */
InfoBox.prototype = new google.maps.OverlayView();

/* Creates the DIV representing this InfoBox
 */
InfoBox.prototype.remove = function() {
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};

/* Redraw the Bar based on the current projection and zoom level
 */
InfoBox.prototype.draw = function() {
  // Creates the element if it doesn't exist already.
  this.createElement();
  if (!this.div_) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our Bar
  var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
  if (!pixPosition) {
    return;
  }
  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = this.width_ + "px";
  this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
  this.div_.style.height = this.height_ + "px";
  this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
  this.div_.style.display = 'block';
};

/* Creates the DIV representing this InfoBox in the floatPane.  If the panes
 * object, retrieved by calling getPanes, is null, remove the element from the
 * DOM.  If the div exists, but its parent is not the floatPane, move the div
 * to the new pane.
 * Called from within draw.  Alternatively, this can be called specifically on
 * a panes_changed event.
 */
InfoBox.prototype.createElement = function() {
  var panes = this.getPanes();
  var div = this.div_;
  if (!div) {
    // This does not handle changing panes.  You can set the map to be null and
    // then reset the map to move the div.
    div = this.div_ = document.createElement("div");
    div.id = "infowindow";
    var contentDiv = document.createElement("div");
    contentDiv.innerHTML = this.content_;
    contentDiv.id = "innerWrapper";

    var topDiv = document.createElement("div");
    topDiv.id = "infowindowcloser";
    var closeImg = document.createElement("img");
    closeImg.src = ips.system.urlroot + "filestore/closebigger.gif";
    topDiv.appendChild(closeImg);

    function removeInfoBox(ib) {
      return function() {
        ib.setMap(null);
      };
    }

    google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this));

    div.appendChild(topDiv);
    div.appendChild(contentDiv);
    div.style.display = 'none';
    panes.floatPane.appendChild(div);
    this.panMap();
  } else if (div.parentNode != panes.floatPane) {
    // The panes have changed.  Move the div.
    if (div.parentNode !== null) {
      div.parentNode.removeChild(div);
    }
    panes.floatPane.appendChild(div);
  } else {
    // The panes have not changed, so no need to create or move the div.
  }
};

/* Pan the map to fit the InfoBox.
 */
InfoBox.prototype.panMap = function() {
  // if we go beyond map, pan map
  var map = this.map_;
  var bounds = map.getBounds();
  if (!bounds) {
    return;
  }
  // The position of the infowindow
  var position = this.latlng_;

  // The dimension of the infowindow
  var iwWidth = this.width_;
  var iwHeight = this.height_;

  // The offset position of the infowindow
  var iwOffsetX = this.offsetHorizontal_;
  var iwOffsetY = this.offsetVertical_;

  // Padding on the infowindow
  var padX = 40;
  var padY = 40;

  // The degrees per pixel
  var mapDiv = map.getDiv();
  var mapWidth = mapDiv.offsetWidth;
  var mapHeight = mapDiv.offsetHeight;
  var boundsSpan = bounds.toSpan();
  var longSpan = boundsSpan.lng();
  var latSpan = boundsSpan.lat();
  var degPixelX = longSpan / mapWidth;
  var degPixelY = latSpan / mapHeight;

  // The bounds of the map
  var mapWestLng = bounds.getSouthWest().lng();
  var mapEastLng = bounds.getNorthEast().lng();
  var mapNorthLat = bounds.getNorthEast().lat();
  var mapSouthLat = bounds.getSouthWest().lat();

  // The bounds of the infowindow
  var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
  var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
  var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
  var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;

  // calculate center shift
  var shiftLng =
      (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
      (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
  var shiftLat =
      (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
      (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

  // The center of the map
  var center = map.getCenter();

  // The new map center
  var centerX = center.lng() - shiftLng;
  var centerY = center.lat() - shiftLat;

  // center the map to the new shifted center
  map.setCenter(new google.maps.LatLng(centerY, centerX));

  // Remove the listener after panning is complete.
  google.maps.event.removeListener(this.boundsChangedListener_);
  this.boundsChangedListener_ = null;
};

//google analytics
var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1166823-1']);
  _gaq.push(['_trackPageview']);

//byggmakker master.js
(function(){
    var emailpattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
        urlroot = ips.system.urlroot, // cache as local variable
	    store = ips.data, //cache
	    $nostore = $("div.nostore"),
	    $butikkInfo = $("#butikkInfo"), // cache 
	    $name = $butikkInfo.find(".name"), // cache  
		$url = $butikkInfo.find("a.url"), // cache 
		$phone = $butikkInfo.find(".shopphone"), // cache 
		$email = $butikkInfo.find("a.shopemail"),  // cache
	    $app = $("#mapApp"),
	    $map = $(".map"),
	    $gmap = $map.find(".gmap"),
	    geocoder,
	    thegmap,
	    $searchResult = $("#searchResult"),
	    $postal = $("#postalSearch"),
	    $postalResponse = $postal.find("p.response"),
	    $searchWrapper = $app.find(".searchWrapper"),
	    $searchResponse = $searchWrapper.find("p.response");
	var $body = $("body")
	   .bind("updateFlashFiles", function(e, trigger){
	      for( var i = 0; i < ips.queue.length; i++ ) {
		    if(ips.queue[i].update) {
			  document.getElementById(ips.queue[i].element).update();
			}
		  }
	   }).bind("loadMapData", function(e, trigger){
		  // Load data, then callback / trigger
		  if (!store.butikker) {
				var theUrl = urlroot + '?template=jsonfolders';
				jQuery.getJSON(theUrl, function(data){
					store.butikker = data.butikker;
					if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}	
			   });
		  } else {
			   if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}	
	      }
	  }).bind("setMinbutikkFromUrlParam",function(e, trigger) {
		if (store.params.settminbutikk) {
            $(this).trigger("loadMapData", function(){
			  updateWithId(store.params.settminbutikk);
			  if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}
			});
		}
	  })
	.bind("loadCookie", function(e, trigger){
          if (!store.minbutikk.name) {
			 var cookie = $.cookie('minbutikk');
			 if (cookie !== null) {
			   store.minbutikk = $.secureEvalJSON(cookie); // insert cookie obj into ips object
			 }
		  }

		  if (store.minbutikk.name) {
            var _minbutikk = store.minbutikk; // shortcut var
		    $name.text(_minbutikk.name);
            var shopurlroot = _minbutikk.folderpath.indexOf("http:") == -1 ? urlroot : "";
            var shopclass = shopurlroot === "" ? 'externalLink' : '';
			$url.add("a.minbutikk").attr("href", shopurlroot + _minbutikk.folderpath).addClass("loaded").addClass(shopclass);
			$phone.text(_minbutikk.phone);
		    $email.attr("href", "mailto:" + _minbutikk.email);
		    $nostore.hide(); // hide placeholder
		    $butikkInfo.show(); // show populated store
            $("a.setMinButikk").removeClass("current").each(function(){
				if (this.id.substring(8,20) === _minbutikk.id ) {
					$(this).addClass("current");
				}
	        });
			if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}
		  }  else {
			if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}
		  }
	  })
	.bind("clearCookie", function(e,trigger){
		$.cookie('minbutikk',null,{ path: '/', expires: -1 });
		$nostore.show();
		$butikkInfo.hide();
		$("a.setMinButikk").removeClass("current");
		ips.data.minbutikk = {};
		$body.trigger("updateFlashFiles");
		if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}
	})
	  .one("mapBindings",function(){
			$app.find(".dropdown").live("click", function(e){
				e.preventDefault();
				var $this = $(this);
				if (!$this.hasClass("loaded")) {
					return loadFromDatabase(function(){
						var results = "";
						var objs = store.butikker;
						var objsLength = objs.length;
						var currId = store.minbutikk.id;
						for (var k = 0;k<objsLength;k++) {
							var obj = objs[k];
							var currentclass = obj.id === currId ? ' current': '';
							var objname = "BM " + obj.name.substring(10,50);
							results += "<li><a href='#' class='setMinButikk visMinButikk" + currentclass + "' id='butikkid" + obj.id +"'>" + objname + "</a></li>";
						}
						$this.html(results);
						$this.addClass("loaded").addClass("expanded");
					});
				} else {
					$this.toggleClass("expanded");
				}
			});
			$map.find(".pluss").live("click",function(e){
				e.preventDefault();
				var currZoom = thegmap.getZoom();
				if (currZoom < 20) {
				   thegmap.setZoom(currZoom+1);
                }
			});
			$map.find(".minus").live("click",function(e){
				e.preventDefault();
				var currZoom = thegmap.getZoom();
				if (currZoom > 1) {
				   thegmap.setZoom(currZoom-1);
                }
			});
			$map.find(".zoom").live("click",function(e){
				e.preventDefault();
				var currZoom = thegmap.getZoom();
				if (currZoom < 12) {
				   thegmap.setZoom(15);
                } else {
                   thegmap.setZoom(6);
                }
                thegmap.setCenter(store.infobox.latlng_);
			});
			$map.find(".mapMode").live("click",function(e){
				var $target  = $(e.target);
				if ($target.is("a")) {
					$(this).find(".current").removeClass("current");
					$target.addClass("current");
				}
			});
			$map.find(".hybrid").live("click",function(e){
				e.preventDefault();
				thegmap.setMapTypeId("hybrid");
			});
			$map.find(".normal").live("click",function(e){
				e.preventDefault();
				thegmap.setMapTypeId("roadmap");
			});
			$map.find(".satelite").live("click",function(e){
				e.preventDefault();
				thegmap.setMapTypeId("satellite");
			});
			$map.find(".terrain").live("click",function(e){
				e.preventDefault();
				thegmap.setMapTypeId("terrain");
			});
			$postal.submit(function(e){
	                        e.preventDefault();
				$postalResponse.text("S\u00F8ker...");
				if ($postal.find(".query").val() !== '') {
                  getMapViewBounds($postal.find(".query").val() );
				} else {
					$postalResponse.text("Vennligst fyll inn en by eller et postnummer.");
				}
			});
	  })
	  .bind("initMap", function(e, trigger){ // Init map
			if (!$gmap.hasClass("loaded")) {
				var myLatlng = new google.maps.LatLng(65.566338192033194,13.271484375); //fallback loc
				geocoder = new google.maps.Geocoder(); // init geocoder, var i in top scope
				var zoomInt = 4;
				if (store.minbutikk.latitude) { // get location from cookie
					myLatlng = new google.maps.LatLng(store.minbutikk.latitude,store.minbutikk.longitude);
					zoomInt = 10;
				} else if (google.loader.ClientLocation !== null && google.loader.ClientLocation.address.country_code.toString() == "NO") { // or get loc from google loader
					myLatlng = new google.maps.LatLng(google.loader.ClientLocation.latitude,google.loader.ClientLocation.longitude);
					zoomInt = 9;
				}
				var myOptions = { // Gmap options
					zoom: zoomInt,
					center: myLatlng,
					diableDefaultUI: true,
					navigationControl: false,
					mapTypeControl: false,
					scaleControl: false,
					backgroundColor: "#99b3cc",
					mapTypeId: google.maps.MapTypeId.ROADMAP,  
					navigationControlOptions: {  
						style: google.maps.NavigationControlStyle.SMALL  
					}  
			  };
			  var gmapref = $gmap.addClass("loaded").get()[0];
			  thegmap = new google.maps.Map(gmapref, myOptions);
			  $body.trigger("loadMapData", "insertPoints").trigger("mapBindings");
			}
		  if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}	
	  })  
	  .bind("insertPoints", function(e, trigger){
			var points = store.butikker;
			var len = points.length;
			for(var g = 0;g < len;g++){
				var thisg = points[g];
				if (thisg.latitude) {
					thisg.position = new google.maps.LatLng(thisg.latitude,thisg.longitude);
					setPoint(thisg);
				} else {
					getAddress(thisg);
				}
			}
			if (typeof trigger === "string") {$body.trigger(trigger);} else if (typeof trigger === "function") {trigger();}
	  }); 
	    // just sugar - deprecated
		var loadFromDatabase = function(callback){
			return $body.trigger("loadMapData", callback);
		};
		//utility function for locating the correct store from ID
		var findObjInArray = function(id,callback){
			return loadFromDatabase(function(){
				var butikker = store.butikker;
				var l = butikker.length;
				for (var i = 0; i < l;i++) {
					if (butikker[i].id === id) {
						return callback(i);
					}	
				}
			});
		};
		//update cookie and current map store
		var updateWithId = function(butikkid){
			findObjInArray(butikkid,function(returnval){
				store.minbutikk = store.butikker[returnval];
				delete store.minbutikk.position;
				delete store.minbutikk.marker;
				$.cookie('minbutikk', $.toJSON(store.minbutikk), { expires: 100, path: '/'}); 
				$body.trigger("loadCookie").trigger("updateFlashFiles").trigger("loadForm");
				if (!$app.is(":hidden")) {
					$showmaplink.click();
				}
				//Google analytics
				_gaq.push(['_trackEvent', 'setMinButikk', store.minbutikk.name]);
          });
		};
		
		var findObjWithPostalcode = function(postalcode,callback){
			loadFromDatabase(function(){
				var butikker = store.butikker;
				var l = butikker.length;
				var onr = 1*postalcode;
				for (var i = 0; i < l;i++) {
					var nr = 1*butikker[i].postalcode;
					if (nr === onr ) {
						thegmap.setCenter(butikker[i].position);		
						updateSearch();						
						return;
					} else if (nr >  onr-50 && nr < onr+50) {
						thegmap.setCenter(butikker[i].position);
						updateSearch();
						return;
					}					
				}
				$postalResponse.text("");
				$searchResponse.text("Ingen treff");
				$searchResult.html("<li></li>");
			});
		};	
			
		var getAddress = function (that) {
			if(!that.city) { // special case for customer, tho should not be used. Use latlng.
			  if (that.name.toLowerCase().indexOf("byggmakker") !== -1) {
				var _str = that.name.substr(11,50);
				that.city = _str;
			  } else {
				that.city = that.name;
			  }
			}
			geocoder.geocode( { 'address': that.city,'country':'no'}, function(results, status) {
			   if (status == google.maps.GeocoderStatus.OK) {
				   that.position = results[0].geometry.location;
				   setPoint(that);
			   } else {
			   }
			});
		};
		
		var updateSearch = function(notcenter) {
			if (!notcenter) {
				thegmap.setZoom(9); // TODO : do more logic
			}
			store.search = [];
			store.search.length = 0;
			var butikker = store.butikker;
			var l = butikker.length;
			var bounds =  thegmap.getBounds();
			for (var i = 0; i < l;i++) {
				if (butikker[i].position && bounds.contains(butikker[i].position)) {
					store.search.push(butikker[i]);
				}	
			}
			if (store.search.length === 0) {
				var currZoom = thegmap.getZoom();
				if (currZoom > 1) {
					thegmap.setZoom(currZoom-2);
					updateSearch(true);
				} 
			} else {
				if (!notcenter) {
					thegmap.setCenter(store.search[0].position);
				}
				var page = 1;
				var searchLength = store.search.length < 10 ? store.search.length : 9;
				var currId = store.minbutikk.id;
				var results = "";
				var j = page === 1 ? 0 : page * 9 -1; //pagination not inuse
				for (j;j < searchLength; j++) {
					var obj = store.search[j];
					var currentclass = obj.id === currId ? ' current': '';
					results += "<li class='result" + j + "'><a href='#' class='setMinButikk visMinButikk" + currentclass + "' id='butikkid" + obj.id +"'><span class='checkbox'></span>" + obj.name + "<span class='city'>" + obj.city + "</span></a></li>";
				}
				/*$searchResponse.text("Viser " + searchLength + " av " + store.search.length + " treff.");*/
				$searchResponse.html("Her er v\u00E5re butikker n\u00E6rmest ditt s\u00F8k (<span>" + $postal.find(".query").val() + "</span>):");
				$postalResponse.text("");
				$searchResult.hide().html(results).fadeIn(1000, function(){
					if (store.search.length === 1) { 
					  google.maps.event.trigger(store.search[0].marker, "click"); // TODO produces a = null
					}
				});
			}	
		};
		
		var getMapViewBounds = function(query) {
			geocoder.geocode( {'address':query,'country':'NO'}, function(results, status) {
			  if (status == google.maps.GeocoderStatus.OK) {
				  if (results[0].formatted_address.indexOf("Norge") !== -1) {
					  thegmap.setCenter(results[0].geometry.location);
					  updateSearch();
				  }  else {
				    findObjWithPostalcode(query);
				  }
			   } else {
                  findObjWithPostalcode(query);
			   }
			});
		};
		// load points from ips object. store.butikker should be on place
		var setPoint =  function(that){
		   var marker = new google.maps.Marker({
				  position: that.position, 
				  map: thegmap, 
				  icon: urlroot + 'filestore/bmicon.png',
				  title: that.name
		   }); 
           var shopurlroot = that.folderpath.indexOf("http:") == -1 ? urlroot : "";
           var shopclass = shopurlroot === "" ? 'externalLink' : ''
		   var currentclass = store.minbutikk.id === that.id ? 'current' : '';
		   var content = "<h4>" + that.name + "</h4><p class='city'>" + that.city + "</p><span class='zoom'>Zoom</span>";
		   var innercontent = "<ul class='nav'><li class='shopname'><a class='"+shopclass+"' href='"+ shopurlroot + that.folderpath;
		       innercontent += "'>Butikkside</a></li><li class='shopemail'><a href='mailto:" + that.email 
		       innercontent += "'>E-post</a></li><li class='shopphone'>" + that.phone + "</li><li class='last'><a id='butikkid" 
		       innercontent += that.id + "' href='#' class='setMinButikk " + currentclass + "'><span class='checkbox'></span>"
		       innercontent += "<span class='istrue'>Dette er din BM</span><span class='isfalse'>Sett som min BM</span></a></li></ul>";
		   
		   google.maps.event.addListener(marker, "click", function(e) {
				if (store.infobox && store.infobox !== null) {
					store.infobox.remove();
					store.infobox.setMap(null);
					store.infobox = null;
				}
				var infoBox = new InfoBox({"latlng": marker.getPosition(), "map": thegmap, "content": content + innercontent});
				store.infobox = infoBox;
		   });
		   that.marker = marker;
		};
		/*###  INIT  ###*/
		// update fn for flash/actionscript - reload flash from inside
        ips.system.update = function(queue_pos){ ips.queue[queue_pos].update = true };
        // Utility function for flash-files from JR
        ips.system.resizeFlash = function (pos,width,height) {
          var size = {"width":width,"height":height},
          $elem = $("#"+ips.queue[pos].element).css(size),
          $parent = $elem.parent();
          if ($elem.parent().is(".flashWrapper")){
            $parent.css(size)
          }
        }
        // Trigger init setup, check if param is here. then check for cookie
		$body.trigger("setMinbutikkFromUrlParam").trigger("loadCookie", function(){
			// after cookie check, load flash-files in queue
			var queue = ips.queue;
            var _minbutikk = ips.data.minbutikk.name || "ingen";
            var _minbutikk_id = ips.data.minbutikk.id || 0;
            $(queue).each(function(i){
                if (!this.loaded) {
                    this.flashvars.minbutikk = _minbutikk;
                    this.flashvars.minbutikk_id = _minbutikk_id;
                    this.flashvars.queue_pos = i;
                    swfobject.embedSWF(this.url, this.element, this.width, this.height, this.version, this.expressInstall, this.flashvars, this.params, this.attributes);
                    this.loaded = "true";
                }
            });
		});	
		
		// EVENT DELEGATION - Not touching dom until click
		$(".externalLink").live("click", function(){
		  $(this).attr("target", "_blank");
		});
		// FORMS
		/*$("input:not(.radiobutton),textarea").focus(function(){
			 $(this).addClass("focus");
		  }).blur(function(){
			 $(this).removeClass("focus");
		});*/
	
		$("a.setMinButikk").live('click', function(e) { 
		  e.preventDefault(); 
		  var $this = $(this),
              butikkid = this.id.substring(8,20);
		  if ($this.hasClass("visMinButikk")) {
			findObjInArray(butikkid,function(returnval){
				google.maps.event.trigger(store.butikker[returnval].marker, "click");
            });  
		  } else if ($this.hasClass("current")) {
				$body.trigger("clearCookie");
		} else {
            $("a.setMinButikk").removeClass("current");
            $this.addClass("current");
            updateWithId(butikkid);
		  }
		});
		$("a.remove").live("click",function(e){
			e.preventDefault();
			$body.trigger("clearCookie");
		});
	    // Map app button;
		var $showmaplink = $(".showMap a").live("click",function(e){
			e.preventDefault();
			$app.slideToggle();
			var $this = $(this);
			$body.trigger("initMap",function(){
				$(".minButikkWrapper").toggleClass("expanded");
				if ($this.text() === 'Vis kart') {
					$this.text("Lukk kart");
				} else {
					$this.text("Vis kart");
				}
				if(store.params.big === 'true') {
					var newMapSize = ($(window).height() - $(".searchMap").height() - $("#minButikk").height() - 80 ) + "px";
					$(".minButikkWrapper").css({"position":"absolute","z-index":"1000","height":$(document).height()});
					$(".map").css({"height":newMapSize});
				}
		   });
		});
	   $("a.minbutikk, div.nostore").live("click",function(e){
		 if (!$(this).hasClass("loaded")) {
		   e.preventDefault();
		   $showmaplink.click();
		 }
	  
	   });
           $(".staticGoogleMap").live("click",function(){
              $showmaplink.click();
          });
	    //INIT - Initiate click on map if parameter is present
		if (store.params.showmap === 'true') {
			$showmaplink.click();
		}
	   // MENY SUPPORT
	   var $flere = $("li.flere");
	   if ($flere.length) {
		 var $flereul = $flere.find("ul.extra");
		 var menuTimer;
		 $flere.hover(function(){
			 $(this).find("a.flere").addClass("expanded");
			 $flereul.slideDown();
			 clearTimeout(menuTimer); 
		   },function(){
			 menuTimer = setTimeout(function(){
				  $flereul.slideUp();
				  $flere.find("a.flere").removeClass("expanded");
			   },5000);
		   }).find("a.flere").live("click",function(e){
			 e.preventDefault();   
			 $flereul.slideToggle();
		  });
	   }
	 $("#searchForm").submit(function(){
		var $this = $(this),
			$query = $this.find(".query");
		if ($query.val() === "") {
			return false;
		} else if ($query.val().indexOf("*") === -1){
			$query.val($query.val() + "*");
		}
	});
	//pricecheck for product view
	var $product = $(".produkt");
	if ($product.length) {
		$body.bind("loadForm",function(){
			var $content = $product.find(".article-content");
			var storeEmail = ips.data.minbutikk.email !== undefined ? ";ipsfm_toAddr=" + ips.data.minbutikk.email : "";
			$.get(ips.system.urlroot + "?template=pricecheck" + storeEmail + ";",function(data){
				if( $("#formPriceCheck").length === 0){
				  $(data).prependTo($content);
				} else {
				  $("#formPriceCheck").replaceWith(data);
				  $("#formPriceCheck").find("input.block").eq(0).focus();
				}
				if(!ips.data.minbutikk.email){
				  $("#formPriceCheck input").one("focus", function(){
					$showmaplink.click();
					$postal.find(".query").focus();
					$searchResponse.text("For \u00E5 sende sp\u00F8rsm\u00E5l om produkter, vennligst velg din Byggmakker-butikk og sett denne som din butikk.");
					$postalResponse.text("Skriv inn navnet p\u00E5 stedet du bor og trykk p\u00E5 s\u00F8k.")
				  });
				}
			  $("#formPriceCheck").live("submit",function(e){
				e.preventDefault();
				$("#fillURL").val(window.location.toString());
				$("#fillTITLE").val(document.title);
				$("<input type='hidden' name='ipsfm_subject' value='Sp\u00F8rsm\u00E5l fra kunde på Byggmakker.no' />").appendTo("#formPriceCheck fieldset");
				var $this = $(this);
				$.ajax({
					url:$this.attr("action"),
					type:"POST",
					data:$this.serialize(),
					success: function(data2){
					  $this.replaceWith(data2);
					}
					});
				});
			});
	}).trigger("loadForm");

	}
//contact form for local store
    if (store.params.contact) {
       var $content = $("#content");
       if ($content.length) {
         $.get(urlroot + "?template=contactform;ipsfm_toAddr=" + store.params.contact + ";",function(data){
           $(data).appendTo($content);
           $("<a href='mailto:"+store.params.contact+"' class='mailto'>...eller trykk her for vanlig e-post.</a>").appendTo("#formContactForm div.submit");
           $("#formContactForm").live("submit",function(e){
            e.preventDefault();
	    var $this = $(this);
			$.ajax({
			  url:$this.attr("action"),
			  type:"POST",
			  data:$this.serialize(),
			  success: function(data2){
			    $this.replaceWith(data2);
			  }
			});
           });
         });
       }

    }
    // TIPS FORM
    var $tipsform = $("#tipsForm").submit(function(event){
        var $this = $(this), 
                $senderName = $("#senderName"), 
                $senderEmail = $("#senderEmail"), 
                $recipientEmail = $("#recipientEmail"), 
                $response = $this.find("h3");
        $this.find(".error").removeClass("error");
        if($senderName.val() === "") {
            $senderName.addClass("error").focus().parent().addClass("error");
            return false;
        }
        if(!emailpattern.test($senderEmail.val())) {
            $senderEmail.addClass("error").focus().parent().addClass("error");
            return false;
        }
        if(!emailpattern.test($recipientEmail.val())) {
            $recipientEmail.addClass("error").focus().parent().addClass("error");
            return false;
        }
        $.ajax({
          url: urlroot,
          data: $tipsform.serialize(),
          error: function() {
            $response.text("Det har skjedd en feil. Send en gang til.");
          },
          success: function() {
            $response.text("Tipset ble sendt!");
            $tipsform.toggle("slow");
          }
        });
        return false;
    });
	$(".email").click(function(e){
		e.preventDefault();
		$tipsform.toggle();
	});
})();

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();