/**
 * global vars [unfortunately :(]
 */


// Enable nederland
function enableNederland(value){
  if(typeof(value) == 'undefined'){
	var element = $("#country_nl");
	if(element.size()){
	  if(element[0].checked){
		enableNederland(true);
	  } else {
		enableNederland(false);
	  }
	}
   } else {
	var nl = $('.netherlands');
	var abroad = $('.abroad');
	if(value) {
	  nl.each(function(i,it) {
		it.style.display = "";
	  });
	  abroad.each(function(i,it) {
		it.style.display = "none";
	  });
	} else {
	  nl.each(function(i,it) {
		it.style.display = "none";
	  });
	  abroad.each(function(i,it) {
		it.style.display = "";
	  });
	}
  }
}


var openTip;
/**
 * sets up the "add tip" form
 */
function setUpAddTipForm(){
  var maxSelectedItems = 3;
  var selectedStatus = {};
  if(!$('#household_tip_form')){
    return;
  }
  $('input.tipcheckbox').each(function(i,checkbox){
    $(checkbox).bind('click', function(e) {
      doClick(checkbox);
    });
    if(checkbox.checked){
      doClick(checkbox);
    }
  });
  function doClick(checkbox){
    var id = $(checkbox).parent().parent().attr('id') || $(checkbox).parent().parent().parent().attr('id');
    var showText = modifyStatus(checkbox, id);
    if(/_rooms$/.test(id)){
      toggleDiv(checkbox);
    }
    toggleTexts(checkbox, id, showText);
  } 
  function toggleDiv(checkbox, force){
    var outerDiv = $(checkbox).parent().next('div');
    var innerDiv = $(checkbox).parent().parent();
    if(force || checkbox.checked){
      outerDiv.addClass('show');
      innerDiv.addClass('show');
    }
    else {
      outerDiv.removeClass('show');
      innerDiv.removeClass('show');
      $('input:checked', innerDiv).each(function(i,el){
          el.checked = false;
          modifyStatus(el, outerDiv[0].id);
        
      });
    }
  }
  function modifyStatus(checkbox, id){
    if(checkbox.checked){
      if(selectedStatus[id] && selectedStatus[id] == maxSelectedItems){
        checkbox.checked = false;
        return true;
      }
      else{
        selectedStatus[id] = selectedStatus[id] ? selectedStatus[id] + 1 : 1;
      } 
    }
    else{
      selectedStatus[id] = selectedStatus[id] - 1;      
    }
    return false;
  }
  function toggleTexts(checkbox, id, force){
    var p = $(checkbox).parent().parent().parent().prev('p.feedforward') || $(checkbox).parent().parent().prev('p.feedforward');
    if(force || selectedStatus[id] === 0){
      p.css({visibility: 'visible'});
    }
    else{
      p.css({visibility:'hidden'});
    }
  }
	
	
  /**
   * Toggle country
   */ 
  var countryNL = $('#country_nl');
  var countryAbroad = $('#country_abr');
  if(countryNL.size()){
    countryNL.bind('focus', function(e) {
      enableNederland(true);
      return false;
    });
  }
  if(countryAbroad.size()){
    countryAbroad.bind('focus', function(e) {
      enableNederland(false);
      return false;
    });
  }
}
/**
 * sets up the popup for the GoudenTip
 * TODO checken en tekst invoeren
 */
function setupGoudenTips(){
  var gt_title = 'De Gouden Tip';
  var gt_text  = 'Gouden tips zijn tips die door zowel bezoekers als de redactie in een bepaalde periode als heel goed worden beoordeeld.';
  $('div.goud').each(function(i,obj){
    obj.bind('click', function(){
      var d = new AHDialog();
      d.addTitle(gt_title);
      d.setText(gt_text);
      d.addDestroyer('Sluiten');
      d.build();
    })
  }); 
}
/** 
 * slides a div
 * @param {Object} obj
 */
function slideDiv(obj) {
  var pps =  200; // pixels per second
  var destHeight, startTime;
  if (obj.open) {
    destHeight = obj.startHeight;
  }
  else {
    obj.startHeight = obj.startHeight || (obj.offsetHeight - 10);  // Subtract 10px to compensate for padding on tip when folded in.
    obj.style.height = 'auto';
    obj.style.height = obj.startHeight;
    destHeight = obj.fullHeight;
  }
  startTime = new Date().getTime();
  step();
  function step() {
    var ms = new Date().getTime() - startTime;
    var dif = Math.round(ms * pps / 1000);
    var newPos = obj.offsetHeight + (destHeight == obj.startHeight  ? -dif : dif);
    if (newPos > obj.fullHeight || newPos < obj.startHeight) {
      obj.style.height = destHeight+'px';
      obj.open = !obj.open;
      if(obj.open){
        $(obj).removeClass('closed');
        openTip = obj;        
      }
      else{
        $(obj).addClass('closed');
        openTip = false;
      }
      return;
    }
    else {
      setTimeout(step, 40);
    }
    obj.style.height = newPos+'px';
  }
}
/**
 * sets up folding of the tips
 * 
 * @author BWI
 */
function setupFoldout(){
  // ellipses
  $('span.tip_body_short').each(function(i,el){
    setupFoldoutEllipses(el);
  });
  // hide rest of text
  $('div.tip.foldout').each(function(i,el){
    setupFoldoutHide(el);
  });
  
  // init handle
  var handles = $('h3.foldoutHandle');
  handles.each(function(i,h3){
    setupFoldoutHandle(h3);
  });
  
  if(handles.length == 1){
    slideDiv(handles[0].parentNode.parentNode);
//    clickFoldoutHandle(handles[0]);
  }
}
// ellipses
function setupFoldoutEllipses(el) {
  var _d = document;
  var ellipsis = _d.createElement('span');
  ellipsis.className = 'ellipsis';
  ellipsis.appendChild(_d.createTextNode('...'));
  el.appendChild(ellipsis);
}
// hide rest of text
function setupFoldoutHide(el) {
  $(el).removeClass('closed');  
  el.fullHeight = $(el).height();
  $(el).addClass('closed');
}
// init handle
function setupFoldoutHandle(el, e) {
  $(el).bind('click', function(e) {
    clickFoldoutHandle(this, e);
    return false;
  });
}
function clickFoldoutHandle(el, e){
  var e = e || {};
  var div = el.parentNode.parentNode;
  if(openTip && openTip != div){
    slideDiv(openTip);
  }
  slideDiv(div);
  return false;
}
/**
 * 
 * @author BWI
 * 
 */
function setupRefinement() {
  var hide_more = 5;
  
  if (!$("#refine")) {
    return;
  }
  
  var uls = $('div#refine div ul');
  var _d = document;
  uls.each(function(i,ul){
    var lis = $('li',ul);
    var ln = lis.length
    if(ln > hide_more){
      for(var i = hide_more; i < lis.length; ++i){
        $(lis[i]).addClass('hidden');
      }
      var p = _d.createElement('p');
      p.className = "more";
      p.appendChild(_d.createTextNode("Meer"));
      p.onclick = function(){
        doDialog(ul);
      }
      var more_li = _d.createElement('li');
      more_li.appendChild(p);
      $(ul).append(more_li);
    }
  });
}
/**
 * popup meer opties
 * TODO columns switch beetje mooier maken
 */
function doDialog(ul){
  var maxPerCol = 32;
  var title = ul.parentNode.firstChild.innerHTML;
  var clone = ul.cloneNode(true);
  clone.removeChild(clone.lastChild);
  // [KN] unsure
  var ls = clone.getElementsByTagName('li'); //$(clone).childElements();
  
  var len = ls.length;
  var numCols = Math.ceil(len / maxPerCol);
  numCols = (numCols == 1) ? 2 : numCols;
  var colLen = Math.ceil(len / numCols);
  var colNum = 1;
  var html = '<ul>';
  
  for(var i = 0; i < len; ++i){
    html += '<li>' + ls[i].innerHTML +'</li>';
    if (i >= colNum * colLen) {
      ++colNum;
      html += '</ul><ul>';
    }
  }
  html += '</ul>';
  var div = document.createElement('div');
  $(div).addClass('refineDiv');
  div.innerHTML = html;
  
  var d = new AHDialog();
  d.addTitle(title);
  d.setText(div);
  d.addDestroyer('Sluiten');
  d.build();
  
  $('ah_dialog').css({
    width: Math.ceil(numCols * 13) + 'em'
  });
  
  if(ua.ie6 && numCols == 2 && $('#ah_dialog').size()) {
    var ahDialogUls = $('#ah_dialog .refineDiv ul');
    ahDialogUls.each(function(i,ahDialogUl) {
      $(ahDialogUl).addClass("ie62cols");
    });
  }
  else {
    var ahDialogUls = $('#ah_dialog .refineDiv ul');
    ahDialogUls.each(function(i,ahDialogUl) {
      $(ahDialogUl).removeClass("ie62cols");
    });
  }
  
  return false;
}
/**
 * Tipsrating  usabilityenhancement
 */
// Default ratedvalues for the tips
var currentRatings = [];
function setupRatings() {
  renderRatings();
  setupRatingsBehaviour();
  defineEnhancedRating();
  setupRatedTips();
}
/**
 * Tipsrating  usabilityenhancement view
 */
function renderRatings() {
  var tipRatings = $('form.rate_tip');
 
  tipRatings.each(function(i,tipRating) {
    // Check whether rating is allowed
	  
    var ratingInputs = tipRating.getElementsByTagName('INPUT');
    var ratingParent = $(tipRating.parentNode);
    var tipId = false;
    var currentRating = false;
    var giveRate = [];
    var tipType = false;
    
    // Define rating in enhancedmode
    ratingParent.addClass('enhanced_rating_container');
    tipType = ratingParent.hasClass('bst') ? 'bst' : 'new';
    
    for(var i = 0; i < ratingInputs.length; i++) {
      if(ratingInputs[i].name == 'tipId')
        tipId = ratingInputs[i].value;
        
      if(ratingInputs[i].name == 'avgRating')
        currentRating = ratingInputs[i].value;
      
      if(ratingInputs[i].name == 'rating')
        giveRate[giveRate.length] = ratingInputs[i].value;
    }
    if(tipId == false)
      return false;
    
    // Register the default ratingvalue
    currentRatings[tipId] = currentRating;
    
    var newRating = document.createElement('div');
    newRating.className = 'enhanced_rating';
    for(var i = 0; i < giveRate.length; i++) {
      var newRatingA = document.createElement('a');
      newRatingA.href = '/huishouden/stem?rating=' + giveRate[i] + '&tipId=' + tipId + '&ajax=true';
      
      newRatingA.ratingvalue = (i+1);
      newRatingA.defaulttext = 'Geef uw beoordeling';
      newRatingA.ratingtext = (i == 0) ? 'Geef uw beoordeling: ' + (i+1) + ' ster' : 'Geef uw beoordeling: ' + (i+1) + ' sterren';
      // Show normal star or rated star
      if (i+1 <= currentRatings[tipId]) {
        newRatingA.className += 'rating';
      }
      // Add either 'bst' or 'new'
      newRatingA.className += ' ' + tipType;
      
      newRatingSpan = document.createElement("span");
      newRatingSpan.appendChild(document.createTextNode(newRatingA.ratingtext));
      newRatingA.appendChild(newRatingSpan);
      newRating.appendChild(newRatingA);
    }
    $('div:first', tipRating).prepend(newRating);
    
  });
}
/**
 * setupRatingsBehaviour
 */
function setupRatingsBehaviour() {
  var ratings = $('div.enhanced_rating a');
  ratings.each(function(i,rating) {
    var tipId = rating.href.match(/tipId=([0-9]*)/)[1];
    //var tipType = rating.hasClassName('bst') ? 'bst_' : 'new_';
    //var tipContainer = $('tip_' + tipType + tip);
    
    $(rating).bind('click', function(e) {
      var tipType = $(rating).hasClass('bst') ? 'bst_' : 'new_';
      var tipContainer = $('#tip_' + tipType + tipId);
    
      if(!tipContainer.hasClass('closed'))
        rate(tipId, rating.href, tipType);
      
      return false;
    });
    $(rating).bind('mouseover', function(e) {
      var tipType = $(rating).hasClass('bst') ? 'bst_' : 'new_';
      var tipContainer = $('#tip_' + tipType + tipId);
      var tipRatingText = getRatingText(tipId, tipType);
      
      previewRate(tipContainer, rating, rating.ratingvalue);
      if (tipRatingText.indexOf("Geef uw beoordeling") > -1)
        setRatingText(tipId, rating.ratingtext, tipType);
      return false;
    });
    $(rating).bind('mouseout', function(e) {
      var tipType = $(rating).hasClass('bst') ? 'bst_' : 'new_';
      var tipContainer = $('#tip_' + tipType + tipId);
      var tipRatingText = getRatingText(tipId, tipType);
      
      previewRate(tipContainer, rating, currentRatings[tipId]);
      if (tipRatingText.indexOf("Geef uw beoordeling") > -1)
        setRatingText(tipId, rating.defaulttext, tipType);
      return false;
    });
  });
}
/**
 * Perform rate and refresh the DOM with new ratingvalue
 * 
 * @param tipId    int     Tip to rate
 * @param url      string  Url to update the rating
 */
function rate(tipId, url, tipType) {
  //var tipContainerId = 'tip_' + tipType + tipId;
  setRatingText(tipId, 'Bezig met verwerken...', tipType);
  $.ajax({
	  'url': url,
	  type: 'get',
	  complete: function(transport) {
		  replaceTip(tipId, tipType, transport);
	  },

	  error: function(){
		  setRatingText(tipId, 'Uw beoordeling is niet aangekomen. Probeer het nogmaals.', tipType);
	  }
    
  });
}
/**
 * Replace tip
 *
 * @param {Object} tipId
 * @param {Object} tipType
 * @param {Object} transport
 */
function replaceTip(tipId, tipType, transport){
  var transportText = transport.responseText;
 
  
  // the clicked tip rating
  var tipContainerId = 'tip_' + tipType + tipId;
  var tip = $('#'+tipContainerId);
  var newRating = $('<div>').html(transportText).find('div.tip_rating');
  
  
  tip.find('div.tip_rating').replaceWith(newRating);
  setRatingText(tipId, 'Bedankt voor uw beoordeling', tipType);
  
  // if there were two identical tips on the page [new and best], 
  // replace the other tip as well
  var otherType = tipType == 'bst_' ? 'new_' : 'bst_';
  var otherTipContainerId = 'tip_' + otherType + tipId;
  var otherTip = $('#'+otherTipContainerId);
 
  otherTip.find('div.tip_rating').replaceWith(newRating);
  
  otherTip.find('div.tip_rating img').each(function(){
	  setupRatedTipsSwitcher(this);  
  });
  
  

}
/**
 * Preview rate
 */
function previewRate(tipContainer, rate, currentRate) {
  if(typeof rate == 'undefined' || rate == '' || $(tipContainer).hasClass('closed'))
    return false;
  
  var rateStars = rate.parentNode.getElementsByTagName('a');
  
  for(var i = 0; i < rateStars.length; i++) {
    rateStars[i].ratingvalue <= currentRate ?
      $(rateStars[i]).addClass('rating') :
      $(rateStars[i]).removeClass('rating');
  }
}
/**
 * Define enhanced rating
 */
function defineEnhancedRating() {
  var tipRatings = $('div.tip_rating');
  tipRatings.each(function(i,tipRating) {
    $(tipRating).addClass('enhanced_rating_container');
  });
}
/**
 * Setup rated stars behaviour
 */
function setupRatedTips() {
  var ratedStars = $('img.tip_rating_stars');
  ratedStars.each(function(i,ratedStar) {
    setupRatedTipsSwitcher(ratedStar)
  });
}
/**
 * Setup rated text swither
 */
function setupRatedTipsSwitcher(ratedStar) {
  // Only works when ratedStar has an id beginning with 'tip_rating_id_'
  var tipId = ratedStar.id.substring(14);
  var tipType = $(ratedStar).hasClass('bst') ? 'bst_' : 'new_';
  var defaultV = getRatingText(tipId, tipType);
  
  $(ratedStar).bind('mouseover', function(e) {
    setRatingText(tipId, 'U hebt al gestemd', tipType);
    return false;
  });
  $(ratedStar).bind('mouseout', function(e) {
    setRatingText(tipId, defaultV, tipType);
    return false;
  });
}
/**
 * Set ratingtext
 */
function setRatingText(tipId, txt, tipType) {
  var tipC = $('#tip_' + tipType + tipId);
  var tipRatingTexts = '';
  if (tipC.size()) {
    tipRatingTexts = tipC[0].getElementsByTagName('p');
  }
  for(var i = 0; i < tipRatingTexts.length; i++) {
    if(tipRatingTexts[i].className.indexOf('tip_rating_text') > -1)
      tipRatingTexts[i].innerHTML = txt;
  }
}
/**
 * Get ratingtext
 */
function getRatingText(tipId, tipType) {
  var tipC = $('#tip_' + tipType + tipId);
  var tipRatingTexts = '';
  if(tipC.size())
    tipRatingTexts = tipC[0].getElementsByTagName('p');
  for(var i = 0; i < tipRatingTexts.length; i++) {
    if(tipRatingTexts[i].className.indexOf('tip_rating_text') > -1)
      return tipRatingTexts[i].innerHTML;
  }
}
/**
 * Enhance image type inputs on household_tip_form with mouseover styling
 */
function setupImageButtons() {
  var imageButtons = $('#household_tip_form .imagebutton input');
  if (!imageButtons.size()) return;
  
  imageButtons.each(function(index, elem){
    $(elem).bind('mouseover', function(e) {
      if (elem.src.indexOf('_hover') == -1)
      {
        elem.src = elem.src.replace('.gif', '_hover.gif');
      }
      return false;
    });
    $(elem).bind('mouseout', function(e) {
      if (elem.src.indexOf('_hover') > -1)
      {
        elem.src = elem.src.replace('_hover.gif', '.gif');
      }
      return false;
    });
    
  });
}
/**
 * init household functionality
 */
function initHuishouden(){
  if(rq = $('#rq')){
    rq.focus();
  }
  // Disabled Gouden Tips in AHDialog for now; interferes with Flash heading.
  // setupGoudenTips();
  setUpAddTipForm();
  setupImageButtons();
}
/**
 * setup the loader
 */
if(loader){
  loader.schedule("initHuishouden", initHuishouden);
  loader.schedule("setupRatings", setupRatings, Loader.priority.HIGH);
  loader.schedule("setupFoldout", setupFoldout, Loader.priority.HIGH);
  loader.schedule("setupRefinement", setupRefinement, Loader.priority.HIGH);
}

