////////////////////////////////////////
// Rental creation jQuery functionality.
////////////////////////////////////////
if (typeof jQuery != 'undefined') {
  jQuery(document).ready(function() {
    jQuery("form#createRentalForm").keypress(disableEnter);
  });

  
  /** Function to disable the enter key (submitting the form) in some browsers. */
  function disableEnter(e) {
    if(e.which == 13 && e.target && e.target.type !== 'textarea') {
      return false;
    }
  }
  
  /**
   * CheckboxRequired jQuery plugin.
   * Link a checkbox to an input field when the checkbox choice is required.
   * 
   * Usage: jQuery("#checkbox").checkboxRequired("#targetInput");
   */
  (function($j) {
    
    function CheckboxRequired(root, element) {
      var self = this;
      element = $j(element);
      var value = element.val();
      
      root.change(function() {
        if($j(this).attr('checked')) {
          element.val(value);
        } else {
          value = element.val();
          element.val('');
        }
      });
      
      element.keyup(function() {
        if($j(this).val().length > 0) {
          root.attr("checked", true);
        }
      });
      
      $j.extend(self, {
        // Nothing to see here.
      });
    }
    
    $j.fn.checkboxRequired = function(element) {
      var listener = new CheckboxRequired($j(this), element);
      return listener;
    };
  })(jQuery);

}

////////////////////////////////////////
// Common rental creation functionality.
////////////////////////////////////////
function computeNbChars(ref, limit) {
	if ( !ref ) return;
    if (ref.value.length > limit) {
		ref.value = ref.value.substr(0, limit);
	}
	document.getElementById(ref.name + '.nbChars').innerHTML = ref.value.length;
}

function textAreaWithHintAndCounterFocusGained(ref, limit, hintMessage) {
	if ( !ref ) return;
    var textbox = document.getElementById(ref.id);
    if( textbox != null && textbox != undefined && textbox.value == hintMessage ) {
        textbox.value = ''; //clear the textbox.
    }
    computeNbChars(ref, limit);
}

function textAreaWithHintAndCounterFocusLost(ref, hintMessage) {
	if ( !ref ) return;
    var textbox = document.getElementById(ref.id);
    if( textbox != null && textbox != undefined && textbox.value.length == 0 ) {
        textbox.value = hintMessage;
    }
}

function doSave(formId) {
	if (formId == null || formId == '') {
		document.getElementById('createRentalForm').method.value = "save";
	} else {
		document.getElementById(formId).method.value = "save";	
	}
}

function doPreview() {
	document.getElementById('createRentalForm').method.value = "preview";
}

function doAddFlatMate() {
	document.getElementById('createRentalForm').method.value = "addFlatMate";
}

function doSaveFlatMate(flatMateRef) {
    document.getElementById('createRentalForm')['flatMate.editIdx'].value = flatMateRef;
	document.getElementById('createRentalForm').method.value = "saveFlatMate";
}

function doEditFlatMate(flatMateRef) {
	document.getElementById('createRentalForm')['flatMate.editIdx'].value = flatMateRef;
	document.getElementById('createRentalForm').method.value = "editFlatMate";
}

function doDeleteFlatMate(flatMateRef) {
    document.getElementById('createRentalForm')['flatMate.deleteIdx'].value = flatMateRef;
	document.getElementById('createRentalForm').method.value = "deleteFlatMate";
}

function doDeleteFlatMatePicture(flatMateRef) {
    document.getElementById('createRentalForm')['flatMate.editIdx'].value = flatMateRef;
	document.getElementById('createRentalForm').method.value = "deleteFlatMatePicture";
}

function doDeletePicture(picRef) {
	document.getElementById('createRentalForm')['picture.deletePictureID'].value = picRef;
}

function doArrangePicture(picRef) {
	document.getElementById('createRentalForm')['picture.arrangePictureID'].value = picRef;
}				

function doComputeEndTime(pDate, loc) {
	var d;

	if (loc == 'en' && isEnDate(pDate.value)) {
		d = new Date(pDate.value);
		d.setMonth(d.getMonth() + 1);
		if (d.getFullYear() > 0) {
			document.getElementById('endTime').innerHTML = (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear();
		}
	} else if (loc == 'fi' && isFiDate(pDate.value)) {
		var dString = "";
		var dateArray = pDate.value.split(".");
		d = new Date(dateArray[1] + "/" + dateArray[0] + "/" + dateArray[2]);
		if (d.getFullYear() > 0) {
			d.setMonth(d.getMonth() + 1);
			document.getElementById('endTime').innerHTML = d.getDate() + "." + (d.getMonth()+1) + "." + d.getFullYear();
		}
	} else {
	  document.getElementById('endTime').innerHTML = "";
	}
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var enDateSeparator = "/";
var fiDateSeparator = ".";
var minYear=1900;
var maxYear=3000;

function isInteger(s){
  var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
  var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
  // February has 29 days in any year evenly divisible by four,
  // EXCEPT for centurial years which are not also divisible by 400.
  return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
  for (var i = 1; i <= n; i++) {
    this[i] = 31
    if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
    if (i==2) {this[i] = 29}
   } 
   return this;
}

function isEnDate(dtStr){
  var daysInMonth = DaysArray(12)
  var pos1=dtStr.indexOf(enDateSeparator)
  var pos2=dtStr.indexOf(enDateSeparator,pos1+1)
  var strMonth=dtStr.substring(0,pos1)
  var strDay=dtStr.substring(pos1+1,pos2)
  var strYear=dtStr.substring(pos2+1)
  strYr=strYear
  if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
  if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
  for (var i = 1; i <= 3; i++) {
    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
  }
  month=parseInt(strMonth)
  day=parseInt(strDay)
  year=parseInt(strYr)
  if (pos1==-1 || pos2==-1){
    return false;
  }
  if (strMonth.length<1 || month<1 || month>12){
    return false;
  }
  if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
    return false;
  }
  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
    return false;
  }
  if (dtStr.indexOf(enDateSeparator,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, enDateSeparator))==false){
    return false;
  }
  
  return true;
}

function isFiDate(dtStr){
  var daysInMonth = DaysArray(12)
  var pos1=dtStr.indexOf(fiDateSeparator)
  var pos2=dtStr.indexOf(fiDateSeparator,pos1+1)
  var strDay=dtStr.substring(0,pos1)
  var strMonth=dtStr.substring(pos1+1,pos2)
  var strYear=dtStr.substring(pos2+1)
  strYr=strYear
  if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
  if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
  for (var i = 1; i <= 3; i++) {
    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
  }
  month=parseInt(strMonth)
  day=parseInt(strDay)
  year=parseInt(strYr)
  if (pos1==-1 || pos2==-1){
    return false;
  }
  if (strMonth.length<1 || month<1 || month>12){
    return false;
  }
  if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
    return false;
  }
  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
    return false;
  }
  if (dtStr.indexOf(fiDateSeparator,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, fiDateSeparator))==false){
    return false;
  }
  
  return true;
}


function introOnEnter(e) {
  var keycode;
  if(window.event) {
    keycode = window.event.keyCode;
  } else if(e) {
    keycode = e.which;
  } else {
    return true;
  }
  
  if (keycode == 13) {
    document.getElementById('introsubmit').click();
    return false;
  } else {
    return true;
  }
}

