/**
 * Navigation dropdown support
 */
jQuery(document).ready( function(){
	jQuery('#mainMenuSlideDownAbout').click(function() {
		jQuery('div#subnav').slideDown();
	});
	jQuery('#mainMenuSlideDownArrow').click(function() {
		jQuery('div#subnav').slideDown();
	});
	jQuery('#mainMenuSlideUp').click(function() {
		jQuery('div#subnav').slideUp();
	});

	// Sphinx search
	jQuery(".sphinx").each(
		function(index, value)
		{
			jQuery(value).autocomplete(
			{
				serviceUrl: "/java/ajax_search_campings.php",
				minChars: 2,
				width: 180,
				highlightFirstChild: true,
				onSelect:
					function(value, data)
					{
						if( data != "" )
						{
							window.location = data;
							return false;
						}
					}
			});
		}
	);

	// Message notice
	if( jQuery('.logged-in-user').length > 0 ) {
		jQuery.ajax( {
			url: "/java/ajax/ajax_check_messages.php",
			dataType: "json",
			success: function( data )
			{
				if( data.messages ) {
					var countText = "1 oläst meddelande";
					if( data.count > 1 ) {
						countText = data.count + ' olästa meddelanden';
					}
					jQuery('.logged-in-user').after('<li class="notice right"><a href="'+data.link+'"><span class="mini_icons envelope" title="'+countText+'"></span></a></li>');
				}
			}
		});
	}
});

// Extension of prototype to be able to use delegate.
// It captures the events that bubble up in this element and you can assign behavior to a selector. 
Element.addMethods({
	delegate: function(element, eventName, delegates){
		return Event.observe(element, eventName, Event.delegate(delegates));
	}
});
Event.delegate = function(delegates){
	return function(e){
		var element = Event.element(e), elements = [element].concat(element.ancestors());
		for(var selector in delegates){
			if (element = Selector.matchElements(elements, selector)[0]){
				delegates[selector].call(element, e);
			}
		}
	}
};

jQuery(document).ready( function(){
	if( jQuery.datepicker )
	{
		jQuery.datepicker.setDefaults({
			firstDay : 1,
			dateFormat : "yy-mm-dd",
			dayNamesMin : ["Sön","Mån","Tis","Ons","Tors","Fre","Lör"],
			monthNames : ["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"]
		});
	}
});


/**
 * Event.simulate(@element, eventName[, options]) -> Element
 *
 * - @element: element to fire event on
 * - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
 * - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
 *
 *    $('foo').simulate('click'); // => fires "click" event on an element with id=foo
 *
 **/
(function(){

  var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  };
  var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
  };

  Event.simulate = function(element, eventName) {
    var options = Object.extend(defaultOptions, arguments[2] || { });
    var oEvent, eventType = null;

    element = $(element);

    for (var name in eventMatchers) {
      if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
      throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent) {
      oEvent = document.createEvent(eventType);
      if (eventType == 'HTMLEvents') {
        oEvent.initEvent(eventName, options.bubbles, options.cancelable);
      }
      else {
        oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
      }
      element.dispatchEvent(oEvent);
    }
    else {
      options.clientX = options.pointerX;
      options.clientY = options.pointerY;
      oEvent = Object.extend(document.createEventObject(), options);
      element.fireEvent('on' + eventName, oEvent);
    }
    return element;
  };

  Element.addMethods({ simulate: Event.simulate });
})()

var CG = Class.create();
CG.prototype = {
	initialize: function(){
		this.activateArticleList();
		if (!Modernizr.input.placeholder){
      		this.activatePlaceholder();
    	}
		this.activateSubmit();
		this.activateTableHide();

	},
	activateArticleList: function(){
		$$("ul.tabs.article").each(function(item){
			item.childElements().each(function(item){
				item.observe("click",function(){
					new Ajax.Updater($$("ul.list.article").first(), '../artiklar/ajax_article_list.php', {
  						parameters: { type: this.innerHTML }
					});
					item.siblings().each(function(item){
						item.removeClassName("current");
					});
					item.addClassName("current");
				});
			});
		});		
	},
	/*activateScrollTo:function(){
		var as = $$('a');
		$A(as).each(function(item){
			href = item.href;
			if(href.indexOf('#') > -1){
				$(item).observe('click', function(event){
					event.stop();
					Effect.ScrollTo(this.href.split('#')[1]);
				});
			}
		});
	},*/
	activatePlaceholder:function(){
		$$('input[placeholder]').each(function(input){
			input.addClassName("placeholder");
			input.value=input.getAttribute("placeholder");
			input.observe("focus",function(e){
				e.element().removeClassName("placeholder");				
				if(e.element().value == e.element().getAttribute("placeholder")){
					e.element().value="";
				}
			});
			input.observe("blur",function(e){
				if(e.element().value == ""){
					e.element().addClassName("placeholder");
					e.element().value=e.element().getAttribute("placeholder");
				}
			});
		});
	},
	activateSubmit:function(){
		$$("#submit").each(function(input){
			var form = [];
			input.ancestors().each(function(parent){
				if(parent.tagName.toLocaleLowerCase() == "form")
					form = parent;
			});
			input.observe("click",function(e){
				form.submit();
			})
		});
	},
	activateTableHide:function(){
			$$('table .hideList').each(function(obj){
			$(obj).observe('click', function(e){
				var elm = e.element();
				var parent = elm.up();
				while(parent.tagName.toLocaleLowerCase() != "tr")
					parent = parent.up();
				var sibling = parent.next();
				while(sibling && !sibling.hasClassName("header")){
					sibling.toggle();
					sibling = sibling.next();
				}
				elm.update((elm.innerHTML == "Göm")?"Visa":"Göm")
			});
		});
	}
};

Event.observe(window,'load',function(){
	var cg = new CG();
});	

    //this is a global variable to have only one instance of the calendar
    var calendar = null;
    function showCalendar(element, input, container)
    {
        if (!calendar)
        {
            container = $(container);
            //the Draggable handle is hard coded to "rtop" to avoid other parameter.
            new Draggable(container, {handle: "rtop", starteffect: Prototype.emptyFunction, endeffect: Prototype.emptyFunction});

            //The singleton calendar is created.
            calendar = new scal(element, $(input),
            {
                updateformat: 'yyyy-mm-dd',
                closebutton: '&nbsp;',
                wrapper: container
            });
        }
        else
        {
            calendar.updateelement = $(input);
        }

        var date = new Date($F(input));
        calendar.setCurrentDate(isNaN(date) ? new Date() : date);

        //Locates the calendar over the calling control  (in this example the "img").
		var offset = input.cumulativeOffset();
		$(container).setStyle({left:offset.left+input.getWidth() + 2+'px', top:offset.top+'px'})
        //finally show the calendar =)
        calendar.openCalendar();
    }


// This is jQuery scripting so I have to check if this is implemented...
if(typeof jQuery == "function"){
 // Custom sorting plugin
(function($jQ) {
  $jQ.fn.sorted = function(customOptions) {
    var options = {
      reversed: false,
      by: function(a) { return a.text(); }
    };
    $jQ.extend(options, customOptions);
    $data = jQuery(this);
    arr = $data.get();
    arr.sort(function(a, b) {
      var valA = options.by(jQuery(a));
      var valB = options.by(jQuery(b));
      if (options.reversed) {
        return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
      } else {
        return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
      }
    });
    return jQuery(arr);
  };
})(jQuery);

// DOMContentLoaded

jQuery(function() {

  // bind radiobuttons in the form
  var $filterType = jQuery('#filter input[name="type"]');
  var $filterSort = jQuery('#filter input[name="sort"]');

  // get the first collection
  var $result = jQuery('#result');
  // clone applications to get a second collection
  var $data = $result.clone();
  // attempt to call Quicksand on every form change
  $filterType.add($filterSort).change(function(e) {
	if(updatedList){
	  	// clone applications to get a second collection
  		$data = jQuery('#result').clone();
		updatedList = false;
	}

	var checked = jQuery($filterType+':checked');
	var filter="";
	jQuery.each(checked, function(i,v){
		if(jQuery(v).val() != "name" && jQuery(v).val() != "county"){
			if(jQuery(v).val() != "on")
				filter +='[data-type*=' + jQuery(v).val() + ']';
		}
	});
      var $filteredData = $data.find('li'+filter);
    // if sorted by county
    if (jQuery('#filter input[name="sort"]:checked').val() == "county") {
      var $sortedData = $filteredData.sorted({
        by: function(v) {
          return jQuery(v).find('div[data-type=county]').text().toLowerCase();
        }
      });
    } else {
      // if sorted by name
      var $sortedData = $filteredData.sorted({
        by: function(v) {
          return jQuery(v).find('div[data-type=name]').text().toLowerCase();
        }
      });
    }
    // finally, call quicksand
    $result.quicksand($sortedData, {
      duration: 500,
      easing: 'easeInOutQuad'
    });
  });
});
	function manuallySort(){
		jQuery('#filter input[name="sort"]').trigger('change');
	}
}


var wikiLayer ;
var showWikiOnMap = function(){
	if( wikiLayer == null){
		wikiLayer = new GLayer('org.wikipedia.en');
		wikiLayer.hide();
		map.addOverlay(wikiLayer);
	}
	if(this.checked)
		wikiLayer.show();
	else
		wikiLayer.hide();
};
var panoramioLayer ;
function showPanoramioOnMap(){
	if( panoramioLayer == null){
		panoramioLayer = new GLayer('com.panoramio.all');
		panoramioLayer.hide();
		map.addOverlay(panoramioLayer);
	}
	if(this.checked)
		panoramioLayer.show();
	else
		panoramioLayer.hide();
}


var customMarkerWindow = function(){
		var giw = map.getInfoWindow();
		var myInfowindow = new MarkerWindow(mapCanvas);
		var markWinDiv = new Element("div").addClassName('wikiWindow').insert(new Element("div").addClassName('markerWindow-top'));
			var markWinDivMain = new Element("div").addClassName('markerWindow-main').insert(giw.getContentContainers()[0].firstChild.innerHTML);
   		markWinDiv.insert(markWinDivMain);
		markWinDiv.insert(new Element("div").addClassName('markerWindow-bottom'));
		markWinDiv.insert(new Element("img",{src:'../gfx/googlemap-box-close.png',id:"mc:"}).addClassName('boxClose').observe('click',function(event){
				myInfowindow.fadeOut(0.5);
		}));
		myInfowindow.addContent(markWinDiv);
	    myInfowindow.fadeIn(0.5);
		myInfowindow.moveTo(-200,0);
		myInfowindow.activateDrag();
		giw.hide();
		map.setCenter(giw.getPoint())
};

// Slide up and slide down
function slideThisDown( sel ) {
		jQuery( sel ).slideDown();
	};
function slideThisUp( sel ) {
		jQuery( sel ).slideUp();
	};

/*
function displayArticleBoxList( e )
{
	$$( "ul[class*=articleBoxList]" ).each(
		function( item ){
			item.hide();
		}
	);

	$( e ).show();
}

//Set menu-button active in any UL-list
function setActiveButton( e )
{
	e.up( "ul" ).childElements().each(
		function( obj ){
			obj.removeClassName( "current" );
		}
	);

	e.up( "li" ).addClassName( "current" );
}
*/
