﻿/**
 * General triggered behaviour on document load
 */
var general_rules = {
    '.no_javascript' : function() {
        this.addClassName('hide');
    },
    '.show_no_javascript' : function() {
        this.show();
    },
    '.javascript_only' : function() {
        this.removeClassName('javascript_only');
    },
  	'#analytics_placeholder':function(){
		var sid=this.getClassParameter('sid');
		pageTracker = _gat._getTracker(sid);
		pageTracker._trackPageview();
	}
};
Event.addBehavior(general_rules);

/**
 * Rules for hyperlink behaviour
 */
var hyperlink_rules = {
    'a.void:click' : function(e) {
      return false;
    },

    'a.popup:click' : function(e) {

        /**
         * Event:  click
         * Action: open a popup window
         */
        var params = Element.getClassParameters(this);
        var width = params.width || 684;
        var height = params.height || 350;
        var top = params.top || 200;
        var left = params.left || '50%';
        window.open(this.href,
            'PopUp',
            'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + ',scrollbars=0,status=no,resizable=0,toolbar=0,titlebar=0,menubar=0,location=0');
        return false;
    },

    'a.external:click' : function(e) {

        /**
         * Event:  click
         * Action: open a new window
         */
        if (!e.ctrlKey && !e.altKey && !e.shiftKey) {
          window.open(this.href);
          return false;
        }
    },

    'a.status:mouseover' : function(e) {

        /**
         * Event:  mouseover
         * Action: display the hyperlinks title in the status bar
         */
        window.status=this.title;
        return true;
    },
    'a.status:mouseout' : function(e) {

        /**
         * Event:  mouseout
         * Action: clear the status bar
         */
        window.status='';
        return true;
    },

    'a.switch:click': function(e) {
        /**
         * Event:  click
         * Action: show / hide the tab with the same ID minus "_switch"
         */
        var c = $(this.id.replace('_switch',''));
        var content = $(c.id + '_content');
        if (c) {
          c.toggle();
        }
        return false;
    },

    'a.tabswitch:click' : function(e) {
        /**
        * Event: click
        * Action: hide related div, show related div's related element
        */
        var container = $(this.getAttribute('rel'));
        if(container) {
          var other = $(container.getAttribute('rel'));
          if (other) {
            container.addClassName('hide');
            other.removeClassName('hide');
          }
        }
        return false;
    },

    'a.submit' : function(e) {
        /**
        * Event: click
        * Action: submit the form given as a param. (used by captcha)
        */
        var params = Element.getClassParameters(this);
        var form = $(params.form);
        if (form){
          form.submit();
        }
        return false;
    }
};
Event.addBehavior(hyperlink_rules);

/**
 * Behaviour rules for form elements
 */

var form_rules = {
    'form.overlabel' : function(e) {
		el = this;
		
        Element.addClassName(el,'overlabel-apply');
        Element.removeClassName(el,'overlabel');

        var labels = el.getElementsByTagName('label');

        if (labels) {
            for (i=0;i<labels.length;i++) {

                Event.observe(labels[i],'click', function(e) {
                    var me = Event.findElement(e,'LABEL');
                    var field;
                    if (me.htmlFor) {
                        field = $(me.htmlFor);
                    } else {
                        field = $(me.getAttribute('for'));
                    }
                    if (field) {
                        field.focus();
                    }
                }, false);

                var field;

                if (labels[i].htmlFor) {
                    field = $(labels[i].htmlFor);
                } else {
                    field = $(labels[i].getAttribute('for'));
                }
                if (field.value != '') {
                    labels[i].style.textIndent = '-10000px';
                }
                Event.observe(field,'focus', function(e) {
                    var me = Event.element(e);
                    var label = $(me.id + '_label');
                    if (label) {
                        label.style.textIndent = '-10000px';
                    }
                }, false);
                Event.observe(field,'blur', function(e) {
                    var me = Event.element(e);
                    var label = $(me.id + '_label');
                    if (label) {
                        if (me.value == '') {
                            label.style.textIndent = '0px';
                        }
                    }
                }, false);
            }
        }
    },
    'form.auto_submit' : function(e) {
      this.submit();
    },
    'select.auto_submit:change' : function(e) {
      this.form.submit();
    },
    'input.auto_submit:click' : function(e) {
      this.form.submit();
    },
    /**
     * Event:  blur
     * Action: convert field value to upper case
     */
    'input.auto_upper:blur' : function(e) {
      this.value = this.value.toUpperCase();
    },

    /**
     * Event:  change
     * Action: convert field value to upper case
     */
    'input.auto_upper:change' : function(e) {
      this.value = this.value.toUpperCase();
    },

    'input.auto_blur:focus' : function(e) {

      /**
       * Event:  focus
       * Action:
       *   - replace field's classname from "_off" to "_on"
       *   - if labeled, replace label's classname from "_off" to "_on"
       *   - if label is image, replace image with "_hover" version
       */
        this.className = this.className.replace('_off','_on');
        var fieldLabel = $(this.id + '_label');
        if (fieldLabel) {
            fieldLabel.className = fieldLabel.className.replace('_off','_on');
            var image = fieldLabel.getElementsByTagName('img')[0];
            if (image) {
                image.src = image.src.replace('_normal','_hover');
            }
        }
    },
    'input.auto_blur:blur' : function(e) {

        /**
         * Event:  blur
         * Action:
         *   - replace field's classname from "_on" to "_off"
         *   - if labeled, replace label's classname from "_on" to "_off"
         *   - if label is image, replace image with "_normal" version
         */
        this.className = this.className.replace('_on','_off');
        var fieldLabel = $(this.id + '_label');
        if (fieldLabel) {
              fieldLabel.className = fieldLabel.className.replace('_on','_off');
            var image = fieldLabel.getElementsByTagName('img')[0];
            if (image) {
                image.src = image.src.replace('_hover','_normal');
            }
        }
    },
    'input.auto_clear:focus' : function(e) {

        /**
         * Event:  focus
         * Action:
         *   - clear value
         *   - remove auto_clear class
         */
        if (Element.hasClassName(this,'auto_clear')) {
            this.value='';
        }
        Element.removeClassName(this,'auto_clear');
    },
    '.auto_blur_multiple:focus' : function(el) {

      /**
       * This is the multiple variant of auto_blur. It will highlight the
       * label of replace the image. The id of the label must be the same
       * as the id of the field, minus the last underscore and digits.
       * Now you can do those fancy multiple fields with one label :)
       */
        this.className = this.className.replace('_off','_on');
        var fieldLabel = $(this.id.sub(/_\d+$/, '') + '_label');
        if (fieldLabel) {
            fieldLabel.className = fieldLabel.className.replace('_off','_on');
            var image = fieldLabel.getElementsByTagName('img')[0];
            if (image) {
                image.src = image.src.replace('_normal','_hover');
            }
        }
    },
    '.auto_blur_multiple:blur' : function(el) {
        this.className = this.className.replace('_on','_off');
        var fieldLabel = $(this.id.sub(/_\d+$/, '') + '_label');
        if (fieldLabel) {
            fieldLabel.className = fieldLabel.className.replace('_on','_off');
            var image = fieldLabel.getElementsByTagName('img')[0];
            if (image) {
                image.src = image.src.replace('_hover','_normal');
            }
        }
    },
    'input.rollover:mouseover' : function(el) {

        /**
         * Event:  mouseover
         * Action:
         *   - if not "active", replace classname by "_hover" classname
         *   - if type is "image", replace image by "_hover" version
         */
        if (!Element.hasClassName(this,'active')) {
            this.className = this.className.replace('_normal','_hover');
            if (this.type == 'image') {
                this.src = this.src.replace('_normal','_hover');
            }
        }
    },
    'input.rollover:mouseout' : function(e) {
        /**
         * Event:  mouseout
         * Action:
         *   - replace classname by "_hover" classname
         *   - if type is "image", replace image by "_hover" version
         */
        if (!Element.hasClassName(this,'active')) {
            this.className = this.className.replace('_hover','_normal');
            if (this.type == 'image') {
                this.src = this.src.replace('_hover','_normal');
            }
        }
    },
    'input.ajax:click' : function(e) {
      /**
       * Event: submit
       * Action: set form elements value
       */
      this.value = 1;
    },
    'input.ajax_auto_submit:click' : function(e) {
      /**
       * Event: click
       * Action: parse form elements and POST to AJAX handler
       */
      var container = Element.getClassParameter(this.form,'container');
      var myAjax = new Ajax.Updater(container, 'ajax.php', {
          method: 'post',
          parameters: this.form.serialize(true)
      });
      return false;
    },
    'form.ajax:submit' : function(e) {
      /**
       * Event: submit
       * Action: parse form elements and POST to AJAX handler
       */
      var container = Element.getClassParameter(this,'container');
      var myAjax = new Ajax.Updater(container, 'ajax.php', {
          method: 'post',
          parameters: this.serialize(true)
      });
      return false;
    },
    'form#form_quickbooking_step2:submit' : function() {
      /**
       * Event: submit
       * Action: show loading screen while we wait for ASSD data
       */
			$('quick_loading').style.display = 'block';
    },
    'form#form_booking .js_submit_radio:click, form#form_booking .js_submit:change' : function() {
      /**
       * Event: change
       * Action: submit form when field is changed
       */
      // submit here
        var loaderDiv = $('loading');
        var loader = new MUIL.Dialog.Loader(loaderDiv);
    		return this.up('form').submit();
    },
    'form#form_booking:submit' : function() {
        /**
         * Event: submit
         * Action: show loading screen when submit
         */
        var loaderDiv = $('loading');
        var loader = new MUIL.Dialog.Loader(loaderDiv);
	}
};
Event.addBehavior(form_rules);

var rollover_rules = {
    'img.rollover:mouseover' : function(el) {
      /**
       * Event:  mouseover
       * Action: show hover version
       */
    this.src = this.src.replace('_normal','_hover');
    return false;

  },
    'img.rollover:mouseout' : function(el) {
      /**
       * Event:  mouseout
       * Action: show normal version
       */
    this.src = this.src.replace('_hover','_normal');
    return false;
  }
};
Event.addBehavior(rollover_rules);

var contact_rules = {
    '.contact_extra:change' : function(el) {
    if (this.value == 'sales'){
    	console.log('showing extra fields');        
        $('contact_extra_fields').removeClassName('no_javascript');
        $('contact_extra_fields').removeClassName('hide');
        $('contact_extra_fields').show();
    } else {
        $('contact_extra_fields').hide();    	
    }
    return false;
  }
};
Event.addBehavior(contact_rules);

var gallery_rules = {
	'img.gallery_image:mouseover' : function(el) {
       /**
        * Event:  mouseover
        * Action: show hover version
        */
	    var img = $('picture');
	    img.src = img.src.replace(img.src, this.src);
	    
	    return false;
	},
  'img.gallery_image:mouseout' : function(el) {
       /**
        * Event:  mouseout
        * Action: show selected version
        */
      var li = this.parentNode.parentNode;
      li.addClassName('selected');
      li.siblings().each(function(e){
        e.className = '';
      });
      
      return false;
  },
	'img.gallery_image:click' : function(el) {
       /**
        * Event:  click
        * Action: return false
        */
	    return false;
	}
};
Event.addBehavior(gallery_rules);

var map_rules = {
  'ol#map' : function(el) {
    var points = this.getElementsByTagName('li');
    var mapParams = Element.getClassParameters(this);
    $A(points).each(function(point) {
      var pointParams = Element.getClassParameters($(point));
      var dimensions = point.getDimensions();
      if (pointParams.latitude > 0 && pointParams.longitude > 0) {
        point.style.left = Math.round((pointParams.longitude - mapParams.left) / (mapParams.right - mapParams.left) * this.getWidth() - (point.getWidth() / 2)) + 'px';
        point.style.top = Math.round((mapParams.top - pointParams.latitude) / (mapParams.top - mapParams.bottom) * this.getHeight() - (point.getHeight() / 2)) + 'px';
      } else {
        point.addClassName('hide');
      }
    }.bind(this));
  }
};
Event.addBehavior(map_rules);

var stayokaycard_rules = {
    'input.addrow:click' : function(el) {
        var params = Element.getClassParameters(this);
        var key = params.key;
        var new_key = ((key*1) + 1);
        var row ="<tr>" + $(params.source).innerHTML + "</tr>";
     	row = row.gsub(new RegExp(params.sub), new_key);
        new Insertion.Before( $(params.point),row); 
        this.removeClassName('param-key='+key);
        this.addClassName('param-key='+new_key);    
        $(params.counter).value=new_key;
        Event.addBehavior.unload(); 
        Event.addBehavior.load(Event.addBehavior.rules);
        return false;
    }
};
Event.addBehavior(stayokaycard_rules);
var price_updater_rules = {
    'select.change_price:change' : function(el){
        var today = new Date();
        var sixteen = new Date();
        var birthDay = new Date();
        // Sixteen years ago....
        sixteen.setFullYear(today.getFullYear()-16);
        
        // Which birthdate are we working on?
        var iterator = this.id.replace('birthdate_d_','');
        iterator = iterator.replace('birthdate_m_','');
        iterator = iterator.replace('birthdate_y_','');
        
        // Calculate the right birthdate
        birthDay.setFullYear($('birthdate_y_' + iterator).value);
        birthDay.setMonth(($('birthdate_m_' + iterator).value - 1));
        birthDay.setDate($('birthdate_d_' + iterator).value);
        if(sixteen>=birthDay){    
            // Sixteen or older, pay the price
            $('cardform_display_price_'+ iterator).value="€17,50";
            $('cardform_price_'+ iterator).value='17.5';
        } else{
            // Younger than sixteen, no charge
            $('cardform_display_price_'+ iterator).value="€0,00";
            $('cardform_price_'+ iterator).value='0';
        }
        // Calculate Total
        var totals = $('cardform').getElementsByClassName('sum').pluck('value');
        $('cardform_totalprice').value = "€" + totals.inject(0, function(acc, n) { return (acc*1 + n*1); }) + ",00";
    }
};
Event.addBehavior(price_updater_rules);

var flash_rules = {
  '#home_intro' : function(event) {
    var params = Element.getClassParameters(this);
      var FO = {
        data: "/flash/header.swf",  
        width: "687px",  
        height: "309px",
        xi: "false",
        flashvars: {
    	  headerTitle: this.getElementsByTagName('H2')[0].innerHTML.replace('strong','b','g'),
    	  headerContent: this.getElementsByTagName('P')[0].innerHTML
        },
        version: "8.0.0",
        params: {
      	  menu: "false"
        },
        attributes: {
          id: this.identify()
        }
      };
      swfobject.embedSWF(FO.data, this.identify(), FO.width, FO.height, FO.version, FO.xi, FO.flashvars, FO.params, FO.attributes);
  },
  '.hostel-video' : function(el) {
    var classParams = Element.getClassParameters(this);     
    var FO= {
      data: classParams.video,
      width: "250px",
      height: "209px",
      xi: "false", 
      version:"8.0.0",
      flashvars: {},
      params: {
    	menu: "false",
    	wmode: "transparent"
      },
      attributes: {
        id: this.identify()
      }
    };
    swfobject.embedSWF(FO.data, this.identify(), FO.width, FO.height, FO.version, FO.xi, FO.flashvars, FO.params, FO.attributes);
  },
  '#banner' : function(el) {
    var FO = {
      data: "/flash/banner.swf?clickTag=http://www.cjp.nl/reizen/redactioneel/item2011/CJP_en_Stayokay_presenteren_Cultarrangementen.html",
      width: "185px",
      height: "153px",
      xi: "false", 
      version:"8.0.0",
      flashvars: {},
      params: {
        menu:"false",
        wmode:"opaque"
      },
      attributes: {
          id: this.identify()
      }
    };
    swfobject.embedSWF(FO.data, this.identify(), FO.width, FO.height, FO.version, FO.xi, FO.flashvars, FO.params, FO.attributes);
  },
  '.giro555' : function(el) {
    var FO = {
      data: "/flash/banner_giro555_haiti_234x60.swf",
      width: "234px",
      height: "60px",
      xi: "false", 
      version:"8.0.0",
      flashvars: {},
      params: {
        menu:"false",
        wmode:"opaque"
      },
      attributes: {
          id: this.identify()
      }
    };
    swfobject.embedSWF(FO.data, this.identify(), FO.width, FO.height, FO.version, FO.xi, FO.flashvars, FO.params, FO.attributes);
  }
};
Event.addBehavior(flash_rules);

var print_rules = {
    'a.print:click' : function() {
            window.print();
            return false;
    }
};
Event.addBehavior(print_rules);

/*
 * Rules for googlemaps
 */
var google_maps_rules = {
    '.google-map': function(){
      if (GBrowserIsCompatible()) {
    	var params = this.getClassParameters();
        var map = new MarkerListMap(this, {
          language: params.language,
          dataUrl: '/api/hostel',
          infoWindowTemplateUrl: '/js/templates/infowindow.tpl',
          locationParam: 'hostelID',
          startPoint: new GLatLng(params.latitude, params.longitude),
          startLocationId: params.hostelID,
          showDialog: true,
          markerListDOMElement: $('google-map-list'),
          markerInfoDOMElement: this.previous(),
          markerListActiveClass: 'active'
        });
      }
    }
};
Event.addBehavior(google_maps_rules);

/*
 * Rules for form action manipulation in booking module for Google Analytics
 */
var booking_step_rules = {
	'input.btn-booking-continue:click' : function(el) {
		var params = this.getClassParameters();
		if (params.bookingStep) {
			var baseurl = window.location.href;
			if (baseurl.indexOf('&step=') >= 0) {
				baseurl = baseurl.replace(/&step=[a-z]+/,'');
			}
			this.up('form').action = baseurl+'&step='+params.bookingStep;
		}
	}
}
Event.addBehavior(booking_step_rules);

var feedburner_awareness_rules = {
	'.fb-aware' : function(el) {
		var params = this.getClassParameters();
		
		if (params.fbUri) {
			new Ajax.Request(
				'/jsProxy.php?url='+encodeURIComponent('https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='+params.fbUri),
				{
					method: 'get',
					onComplete: function(transport) {
						if (transport.responseXML && transport.responseXML.documentElement) {
							var fbXML = $(transport.responseXML);
							var rsp = $(fbXML.getElementsByTagName('rsp')[0]);
							if (rsp && rsp.hasAttribute('stat') && rsp.getAttribute('stat') === 'ok') {
								var feed = rsp.getElementsByTagName('feed')[0];
								if (feed) {
									var entry = feed.getElementsByTagName('entry')[0];
									if (entry && entry.hasAttribute('circulation')) {
										var linkContainer = $(this.getElementsByTagName('span')[0]);
										linkContainer.addClassName('loaded');
										linkContainer.insert({top: parseInt(entry.getAttribute('circulation'))});
									}
								}
							}
						}
					}.bind(this)
				}
			);
		}
	}
}
Event.addBehavior(feedburner_awareness_rules);
