function d(str) {
if (window.console && window.console.firebug) {
		console.log(str);
	} 
}
function reloadImg(img){
   var timestamp = new Date().getTime();
   $.ajax({
      type: "GET",
      url: img.attr('src'),
      data: timestamp,
      success: function(msg){
      	   d(img);
      	   d(msg);
           var timestamp = new Date().getTime();
           img.attr('src', img.attr('src') + '?' + timestamp);
        }
   });
}
// Poistaa muut &node_tpl= parametrit ja lisää &node_tpl=blank/blank.tpl
// jos on ankkuri #jotain se siirretään urlin perään
function removeNodeTpl(url) {
	if(!!url) {
		var re = new RegExp('&node_tpl=[a-zA-Z0-9_./]*', 'g');
		return url.replace(re, '');
	}
	return '';
}
function useBlankTpl(url) {
	url = removeNodeTpl(url);
    var re = new RegExp('(#[a-zA-Z0-9_./]+)?$');
    return url.replace(re, '&node_tpl=blank/blank.tpl');
}

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData);
    d(formData);
    d(jqForm);
    d(options);
    //var url = $.param(url);
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    alert('About to submit: \n\n' + options.url + '\n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 
} 

function AjaxSivu (selector1, selector2) {
    this.element1 = $(selector1);
    this.element1.hide();
    this.element2 = $(selector2);
    this.ajaxcontainer = $(selector1 + ' .ajaxcontent');
    this.ajaxcontainer.after('<div class="ajaxpreload"></div>');
    this.preloadcontainer = this.ajaxcontainer.next();
    this.preloadcontainer.hide();
d('ajaxcontainer: ');
d(this.ajaxcontainer);
d('preloadcontainer: ');
d(this.preloadcontainer);
    this.htmlsrc = '';
    this.hidden = true;
    this.show = AjaxSivu_show;
    this.hide = AjaxSivu_hide;
    this.toggle = AjaxSivu_toggle;
    this.update = AjaxSivu_update;
    this.bindcontent = AjaxSivu_bindcontent;
    ajaxloadingy = this.element2.width() / 2 - 20;
    ajaxloadingx = this.element2.width() / 2 - 20;
    this.ajaxloading = this.ajaxcontainer.before('<div style="position: absolute; top: 200px; left: '+ ajaxloadingx +'px; " id="ajaxloading"><img src="images/design/ajaxloading.gif"/></div>').prev().hide();
    d('Ajaxloading:');
    d(this.ajaxloading);

}
function AjaxSivu_show() {
    this.element1.slideDown('slow');
    this.element2.slideUp('slow');
    this.hidden = false;
}
function AjaxSivu_hide() {
    this.element1.slideUp('slow');
    this.element2.slideDown('slow', function() {map.checkResize()});
    this.hidden = true;
}
function AjaxSivu_toggle() {
    if(this.hidden) {
        this.show();
    } else {
        this.hide();
    }
}
function AjaxSivu_bindcontent() {
//, a[class^=do]
	var as = this;
	latusivu.ajaxcontainer.trigger('contentchanged');
	latusivu.ajaxcontainer.find('a.AddNewComment').each(function() {
		// Poista kommentin lisäyslinkistä node_tpl parametri
		$(this).attr('href', removeNodeTpl($(this).attr('href')));
    });
    latusivu.ajaxcontainer.find('a[class^=do]').not('div.newsfile a').not('div.liitetiedosto a').each(function() {
        $(this).bind('click', function(event) {
            // Estä normaali linkin klikkaus
            event.preventDefault();
            latulinkki($(this).attr('href'))
        });
    });
    latusivu.ajaxcontainer.find('form').each(function() {
        $(this).find('img#ccs').each(function() {
        	d("Reloading ccs img");
        	reloadImg($(this));
        });
        $(this).bind('click', {as:as}, function(event) {
            // Lomakkeen lähetys
            //event.preventDefault();
//d("Event Data begin");
//d(event.data);
//d(event.data.as);
//d(event.data.as.ajaxcontainer);
//d(event);
//d(event.data);
//d(this);
//d("Event Data end");
            var formoptions = { 
                target:        event.data.as.ajaxcontainer,   // target element(s) to be updated with server response 
                beforeSubmit:  showRequest,  // pre-submit callback 
                //success:       showResponse  // post-submit callback 
 
                // other available options: 
                //url:       url         // override for form's 'action' attribute 
                //type:      type        // 'get' or 'post', override for form's 'method' attribute 
                //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
                //clearForm: true        // clear all form fields after successful submit 
                //resetForm: true        // reset the form after successful submit 
 
                // $.ajax options can be used here too, for example: 
                //timeout:   3000 
            }; 
 
            // bind form using 'ajaxForm' 
            $(this).ajaxForm(formoptions); 
    
         });
    });
}

function AjaxSivu_update(url) {
    if(this.htmlsrc == url) {
        return false;
    }
    this.ajaxloading.animate({ marginLeft: 0 }, 500).fadeIn('100');
    this.htmlsrc = url;
    d('url: ' + url);
    $.ajax({
        type: "GET",
        url: url,
        as: this,
        success: function(data){
            this.as.ajaxloading.stop().fadeOut('200');
            this.as.preloadcontainer.html(data);
            this.as.preloadcontainer.preload({
                as: this.as,
                onFinish: function() {
                    this.as.ajaxloading.stop().hide();
                    this.as.ajaxcontainer.html(this.as.preloadcontainer.html());
										this.as.bindcontent();
                    this.as.show();
                }
            });
        }
    });
}

// Lisää latuinfo sivulle paikka ja piilota se
	$('#mapcontainer').after('<div id="latusivu" style="position: relative;"><div id="suljelatusivu"><table cellspacing="0" cellpadding="0" width="700"><tr><td id="slsleft"></td><td id="slsmiddle">Takaisin karttaan</td><td id="slsright"></td></tr></table></div><div class="ajaxcontent"></div><div id="formcontent"></div></div>');

// Luo latusivulle AjaxSivu objekti
var latusivu = new AjaxSivu('#latusivu', '#mapcontainer');
d(latusivu);

// Latusivun piilotusnappula
$('#suljelatusivu').click(function() {latusivu.hide()});

//////// Latulinkin avausfunktio..
function latulinkki(url) {	
// Sisältääkö #latusivu jo klikatun sivun?
		url = useBlankTpl(url);
		if (latusivu.htmlsrc != url) {
		    d("latusivu.htmlsrc was different than clicked");
		    latusivu.update(url);
	  } else {
    		d("latusivu.htmlsrc was the same as clicked");
    		latusivu.toggle();
	  }
}
//    if(latusivu.htmlsrc != url + '&node_tpl=blank/blank.tpl') {
//        d("latusivu.htmlsrc was different than clicked");
//        latusivu.update(url + '&node_tpl=blank/blank.tpl')
//    } else {
//        d("latusivu.htmlsrc was the same as clicked");
//        latusivu.toggle();
//    }


//////// Document Ready funktio..
$(document).ready(function() {

$('a.latuinfolinkki').bind('click', function(event) {
    event.preventDefault();
});

	// Muuta latulinkit oikealla niin, että ne tuo sisällön samalle sivulle js:llä
	$('#hiihtopaikat li a, a.latuinfolinkki').each(function() {
d(this);

		// Jokaisen linksin klikkaus aiheuttaa tämän.
		// Piilota vanha sisältö , vaihda latuinfo sisältö uudeksi, preloadaa imaget, näytä uusi sisältö
		$(this).bind('click', {pid:$(this).attr("pid")}, function(event) {
			// Estä normaali linkin klikkaus
			event.preventDefault();
            latulinkki($(this).attr('href'))
		});
	});
});
