var loaderPath = '/extension/kkverkko/design/kkverkko/images/';
var t = '';

$(document).ready(function () {

  $('#noticeStart').datepicker(
    { dateFormat: 'd.m.yy',
      minDate: new Date(),
      maxDate: new Date().getDay() + 365
      }
  );
  
  $('#noticeEnd').datepicker(
    { dateFormat: 'd.m.yy',
      minDate: new Date().getDay() + 1,
      maxDate: new Date().getDay() + 366
     }
  );
  
  $('#noticeStart').change(function (e) {
    e.preventDefault();
    var today = new Date();
    var starts = $(this).attr("value").split('.');
    var nextyear = parseInt(starts[2])+1;
    var nextday = parseInt(starts[0])+1;
    
    if (nextyear) {   
      $("#noticeEnd").datepicker( "option", "minDate", nextday+"."+starts[1]+"."+starts[2] );
      $("#noticeEnd").datepicker( "option", "maxDate", starts[0]+"."+starts[1]+"."+nextyear );
    }
  });
  
  $('#searchForm .textInput').keydown(function (e) {
  
    if (e.keyCode == 13) {
    
      $('#searchForm').submit();
    }
  
  });
  
  $('#loginForm input.halfbox').keydown(function (e) {
  
    if (e.keyCode == 13) {
    
      $('#loginForm').submit();
    }
  
  });
  

 	$('input#SearchText').keyup( function(e) { 

    if ($('#branchWindow').length != 0) {
      $('#branchWindow').remove();
    }
    
    if ($('#chamberWindow').length != 0) {
      $('#chamberWindow').remove();
    }
    
    if ($('#wheelContent').length == 0) {
      $('body').append('<div id="wheelContent"></div>');
    }
      
    searchWordwheel.modified(this,"what"); 
   });
   
 	$('input#SearchLocation').keyup( function(e) { 

    if ($('#branchWindow').length != 0) {
      $('#branchWindow').remove();
    }
    
    if ($('#wheelContent').length == 0) {
      $('body').append('<div id="wheelContent"></div>');
    }
      
    searchWordwheel.modified(this,"where"); 
   });

  $('#getBranch').click(function (e) {
    e.preventDefault();
    
    if ($('#wheelContent').length != 0) {
      $('#wheelContent').remove();
    }
    
    if ($('#chamberWindow').length != 0) {
      $('#chamberWindow').remove();
    }
    
    if ($('#branchWindow').length != 0) {
      $('#branchWindow').remove();
    }
    else {
      openBranches(this);
    }
  });
  $('#getChamber').click(function (e) {
    e.preventDefault();
    
    if ($('#wheelContent').length != 0) {
      $('#wheelContent').remove();
    }
    
    if ($('#branchWindow').length != 0) {
      $('#branchWindow').remove();
    }

    if ($('#chamberWindow').length != 0) {
      $('#chamberWindow').remove();
    }
    else {
      openChambers(this);
    }
  });

  $('.contentTab').css('display','none');
  $('.contentTab.tab_1').css('display','block');

  $('#searchContent .textInput').focus(function () {
  
    var defVal = this.defaultValue;
    
    if ($(this).attr('value') == defVal) {
      $(this).attr('value','');
    }
  });
  
  $('#searchContent .textInput').blur(function () {
  
    /*var defVal = this.defaultValue;      
    if ($(this).attr('value')=='') {
      $(this).attr('value',defVal);
    }*/
        
  });
  
  $('.frontTabs li a').click(function (e) {
  
    var ec = $(this).attr('rel');
    
    if (ec == 'notab') {
      return;
    }
  
    e.preventDefault();
    
    

    $(this).parents('ul').children('li').removeClass('active');    
    $(this).parent().addClass('active');
    
    $(this).parents('div').children('div.contentTab').css('display','none');
    $(this).parents('div').children('.contentTab.'+ec).css('display','block');
  
  });
  
  $('#rightLiftMapImage .locationDot').click(function (e) {
    e.preventDefault();
    
    var lid = $(this).attr('id');
    var iid = "";
    
    if (t != "") {
      clearTimeout(t);
    }
    
    if ($('.locationInfo').length>0) {
      iid = $('.locationInfo').attr('id').split('_')[1]
    }
    
    $('.locationInfo').remove();
    $('.locationBottom').remove();
    $('.locationTip').remove();
    $('.locationTop').remove();
        
    if (iid != lid) {
  
      var lid = $(this).attr('id');      
      var text = $(this).attr('rel');
	  var name = $(this).attr('name');
      var ypos = parseFloat($(this).css('top').split('px')[0]);
      var xpos = parseFloat($(this).css('left').split('px')[0]);
      //$(this).parent().prepend('<div class="locationInfo" id="info_'+lid+'"><p><a class="infoLink" name="'+name+'" id="location_'+lid+'" href="#">'+text+'</a></p></div>')
      $(this).parent().prepend('<div class="locationTop"></div><div class="locationInfo" id="info_'+lid+'"><p><a class="infoLink" name="'+name+'" href="#">'+text+'</a></p></div><div class="locationBottom"></div><div class="locationTip"></div>')
      
      $('.locationTip').css('left',xpos+4+'px');      
      $('.locationTip').css('top',ypos-16+'px');
      
      $('.locationBottom').css('left',xpos-47+'px');      
      $('.locationBottom').css('top',ypos-28+'px');
      
      var bottomPosition = $('.locationBottom').position();     
      var infoHeight = $('.locationInfo').height();
      
      $('.locationInfo').css('top',bottomPosition.top-infoHeight+1+'px');
      $('.locationInfo').css('left',xpos-47+'px');
      
      var infoPosition = $('.locationInfo').position();
      
      $('.locationTop').css('left',xpos-47+'px');
      $('.locationTop').css('top',infoPosition.top-6+'px');
      
      
      t = setTimeout(function(){
          $('.locationInfo').hide(1000);
          $('.locationBottom').hide(1000);
          $('.locationTop').hide(1000);
          $('.locationTip').hide(1000);
          $('.locationInfo').remove();
          $('.locationBottom').remove();
          $('.locationTop').remove();
          $('.locationTip').remove();                                            
      }, 4000);
      
      
	  $('.infoLink').click(function (e) {
		e.preventDefault();
		//var user_location = $(this).attr('name').split('_')[1];             
		//alert(location.href);
		xajax_setKKVerkkoLocation($(this).attr('name'), location.href);
	  })
	  
    } 
  });

  $('#headerTabs a').click(function (e) {
  
    e.preventDefault();
    $('#headerTabs a').removeClass('active');
    $(this).addClass('active');
    var sid = $(this).attr("id").split('_')[1];
    $('#SearchWhere').attr("value",sid);
  
  });
  
  $('#saveWatch').change(function (e) {
  
    var offset = $(this).position();

		var top = offset.top+25 
		var left = offset.left;

		$('#watchData').css('top', top);
		$('#watchData').css('left', left);
  
    if ($('#watchData').css("display") == "none") {
     $('#watchData').show('fast');
    }
    /*else {
     $('#watchData').hide('fast');
    }*/
  });
  
  $('#disabledWatch').click(function (e) {
  
    var offset = $('#saveWatch').position();

		var top = offset.top+25 
		var left = offset.left;

		$('#watchData').css('top', top);
		$('#watchData').css('left', left);
  
    if ($('#watchData').css("display") == "none") {
     $('#watchData').show('fast');
    }
    /*else {
     $('#watchData').hide('fast');
    }*/
  });
  
  $('#closeWatchData').click(function (e) {
    $('#watchData').hide('fast');
  });

  $('.edit_search_listener').click(function (e) {
    e.preventDefault();
    editWatch(this);
  });


});

var searchWordwheel = {
	bufferText: false,
	bufferTime: 500,
	object: false,  
	type: false,
	
	modified : function(obj,type){
		this.object = obj;
		this.type = type;
		
		/*
		if ( $(this.object).attr('id') == 'searchByWordField' ){
			if ( $(this.object).attr('value') != $("#searchByWordFieldHidden").attr('value') ){
				$("#searchByWordFieldHidden").attr('value', '');
			}
		}
		*/
		setTimeout('searchWordwheel.compareBuffer();', this.bufferTime);
	},
	
	compareBuffer : function(){
		strText = $(this.object).attr('value');
		if ( strText != this.bufferText && strText.length > 2){
			this.bufferText = strText;
			searchWordwheel.makeRequest();
		}
	},
	
	makeRequest : function(){

		xajax_getKKVerkkoWordwheel(this.type,$(this.object).attr('value'));
	},
	
	showResults : function(){

      if ($('.wheelItem').length != 0) {

        if (this.type == 'where') {
         var offset = $('#SearchLocation').position();
        }
        else {
  			 var offset = $("#SearchText").position();
  			}
  			var top = offset.top+30 //offset.top + $("#searchByWordField").height() + 2;
  			var left = offset.left;
  
    		if ( $('#wheelContent').css('display') == 'none' ){
    			$('#wheelContent').css('top', top);
    			$('#wheelContent').css('left', left);
    			$('#wheelContent').toggle();
    			  			    			
    			$('body').click(function(){searchWordwheel.hideResults()});
    		}
  		}
  		else {
        searchWordwheel.hideResults();
      }
	},
	
	hideResults : function(){
		$('body').unbind('click', searchWordwheel.hideResults);
		$('#wheelContent').html('');
		//$('#cpvSearchResults').toggle();
		$('#wheelContent').css('display','none');
	},
	
	select : function(e, obj){
		e.preventDefault();
		//alert($(this.object).attr('id'));
    if (this.type == 'where') {
      $("#SearchLocation").attr('value', $(obj).html());
    }
    else {
  	 $("#SearchText").attr('value', $(obj).html());
  	}
	
		searchWordwheel.hideResults();
	}
	
}

function editWatch(e) {
  
  var wid = $(e).attr('id').split('_')[1];  
  var pos = $(e).offset(); 
  
  $('#watchEditor').remove();
  
  $('body').append('<div id="watchEditor"></div>');
  
  $('#watchEditor').css('left',pos.left+'px');
  $('#watchEditor').css('top',pos.top+30.5+'px');
  $('#watchEditor').css('position','absolute');
  $('#watchEditor').css('background','#fff');

  xajax_getKKVerkkoWatchEditForm(wid);

  
}

function openChambers(e) {

  $('#chamberWindow').remove();

  var pos = $(e).position();
  /*alert(pos.top);*/
  $('body').append('<div id="chamberWindow"></div>');
  
  $('#chamberWindow').css('left',pos.left+'px');
  $('#chamberWindow').css('top',pos.top+30.5+'px');
  
  $('#chamberWindow').append('<div id="chamberTop"><h3 id="chamberTopHeader"></h3><a href="#" id="closeChambers" title="Sulje/Close">X</a></div><div class="clear"></div>');
  
  $('#chamberWindow').append('<div id="chamberContent"></div>');
  
  $('#chamberContent').css('display','block');
  
  $('#chamberContent').append('<img src="'+loaderPath+'ajax_loader2_trans.gif" class="loadingImage" alt="Loading..." />')
  
  xajax_getKKVerkkoLocations();
  
  //$('#branchWindow').append('<a href="#" class="setBranch">autot</a><br/>');
  //$('#branchWindow').append('<a href="#" class="setBranch">veneet</a>');

  $('#chamberWindow').append('<div id="chamberBottom"></div>');

  $('#chamberMap .locationDot').hover(function (e) {
    showChamber(this);
  });
  
  $('#chamberMap .locationDot').click(function (e) {
    setChamber(this);
  });
  
  $('#closeChambers').click(function (e) {
    $('#chamberWindow').remove();
  });

}

function openBranches(e) {
  
  $('#branchWindow').remove();

  var pos = $(e).position();
  /*alert(pos.top);*/
  $('body').append('<div id="branchWindow"></div>');
  
  $('#branchWindow').css('left',pos.left+'px');
  $('#branchWindow').css('top',pos.top+30.5+'px');
  
  $('#branchWindow').append('<div id="branchTop"><h3 id="branchTopHeader"></h3><a href="#" id="closeBranch" title="Sulje/Close">X</a></div><div class="clear"></div>');
  
  $('#branchWindow').append('<div id="branchContainer"></div>');
  
  $('#branchContainer').append('<div id="branchHeaders"></div><div class="clear"></div>');
  
  $('#branchContainer').append('<div id="branchContent"></div>');
  
  $('#branchHeaders').append('<img src="'+loaderPath+'ajax_loader2_trans.gif" class="loadingImage" alt="Loading..." />')
  
  xajax_getKKVerkkoBranchHeaders($(this).html());
  
  $('#branchWindow').append('<div id="branchBottom"></div>');
  
  $(".setBranch").click(function (e) {
    setBranch(this);  
  });
  
  $('#closeBranch').click(function (e) {
    $('#branchWindow').remove();
  });
  
}

function showChamber(e) {
    var chVal = $(e).attr('rel');    
    $('#chamberInfo').html('');
    $('#chamberInfo').append('<h3><a class="setChamberInfo" href="#" rel="'+chVal+'">'+chVal+'</a></h3>');
    $('.setChamberInfo').click(function(e){e.preventDefault();setChamber(this)});
}


function setChamber(e) {
    var chVal = $(e).attr('rel');    
    $('#SearchLocation').attr('value',chVal);
    $('#chamberWindow').remove();
}

function setBranch(e) {
    
    var branchVal = $(e).html();    
    $('#SearchText').attr('value',branchVal);
    $('#branchWindow').remove();
}

function validateComment(form) {
    var error = "Seuraavat tiedot puuttuivat:\n";
    var hasErrors = false;
    
    if (form.powercontent_writer_ContentObjectAttribute_ezstring_data_text_pcattributeid.value.length == 0) {
        hasErrors = true;
        error += "  - Nimi on pakollinen\n";
    }
    if (form.powercontent_comment_ContentObjectAttribute_data_text_pcattributeid.value.length == 0) {
        hasErrors = true;
        error += "  - Kommentti on pakollinen\n";
    }
    if (form.chkEncOP.value != md5(form.powercontent_captcha_ContentObjectAttribute_data_text_pcattributeid.value)) {
        hasErrors = true;
        error += "  - Kuvavarmennus ei täsmää\n";
    }

    if (hasErrors) {
        alert(error);
        return false;
    }
    document.postComment.submit();
    return false;
}
jQuery.fn.limitMaxlength = function(options){

	var settings = jQuery.extend({
		attribute: "maxlength",
		onLimit: function(){},
		onEdit: function(){}
	}, options);

	// Event handler to limit the textarea
	var onEdit = function(){
		var textarea = jQuery(this);
		var maxlength = parseInt(textarea.attr(settings.attribute));

		if(textarea.val().length > maxlength){
			textarea.val(textarea.val().substr(0, maxlength));

			// Call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}

		// Call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}

	this.each(onEdit);

	return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}


// *** ***************************** helpers
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
// Returns true if the passed value is found in the
// array. Returns false if it is not.
Array.prototype.inArray = function (value){
	var i;
	for (i=0; i < this.length; i++) {
		// Matches identical (===), not just similar (==).
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};
