$(document).ready(function() {
	// focus on accountname
	$('#AccountName').focus();
	
  // Click handlers
  $('a.confirm, button.confirm').click(function() { 
		sText = $(this).attr('title');
		sHref = $(this).attr('href');
	  sHref = confirm(sText,sHref) ? $(this).attr('href') : false;
	  if(sHref) window.location = sHref;
	  return false;
	});
	
	$('a.edit').click(function() {
		sText = $(this).attr('title');
	});
	
	// handle non-submit buttons (except confirms)
	$('button[type="button"]:not(.confirm)').click(function() {
		// don't do anything with modals
		if($(this).attr('name') == 'modal') return;
		var sHref = $(this).attr('href');
		if(sHref != undefined)	window.location = sHref;
	});
	
	// Clear if browser has prefilled field
	$('.clearthisfield').val('');
	
	// Message!
	flashMessage();
	
	$('button[type="reset"]').click(function(event) {
		event.preventDefault();
		$(this).parent().clearForm();
	});
	
	// handle tooltips
	$('abbr, a[title], img[alt]').qtip({ style: { name: 'green', tip: true, delay: 0 } });
	
	// handling minimal length of search queries
	$('form.searchform').submit(function() {
		var valid = false;
		$(this).find('input').each(function() {
			if(this.type == 'text') {
				if($(this).val().length >= 2) {
					valid = true;
				}
			}
		});
		if(!valid) {
			$('#message').html('<img src="artwork/exclamation.png" alt="!" /> Om te zoeken minimaal twee tekens invullen in een van de velden.');
			flashMessage();
		}
		return valid;
	});
	
	// handle dates
	$('form#contributorform').submit(function() {
		var valid = true;
		$(this).find('input.dateentry').each(function() {
			if($(this).val().length != 10) {
				valid = false;
			}
			if ($(this).val().length == 0) {
				valid = true;
			}
		});
		if(!valid) {
			$('#message').html('<img src="artwork/exclamation.png" alt="!" /> Data dienen in de vorm DD-MM-JJJJ ingevoerd te worden.');
			flashMessage();
		}
		return valid;
	});
	
});


function flashMessage() {
	var text = $('#message').text();
	text = $.trim(text);

	if(text.length > 0) {
		$('#message').hide().fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300);
		setTimeout(function() {
			$('#message').slideUp(300);
		}, 3000);
	}
}
$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $('input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			$(this).val('');	
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
  });
};

/*-------------------------
			   Othertext
  -------------------------*/ 
$(document).ready(function() {
	// Handle certain texttypecodes
	var val = $('#othertextform #texttypecode').val();
	if(val != '05' && val != '06' && val != '07' && val != '08') {
		$('#othertextform #extended').hide();
	}
	
	$('#othertextform #texttypecode').change(function() {
		var val = $(this).val();
		if(val == '05' || val == '06' || val == '07' || val == '08') {
			$('#othertextform #extended').slideDown();
		} else {
			$('#othertextform #extended').slideUp();
		}
	});
});


/*-------------------------
			   WYMeditor
  -------------------------*/ 

$(document).ready(function() {
    jQuery('.wymeditor').wymeditor({
    	lang: 'nl',
    	logoHtml: '',
		  toolsItems: [
		    {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}, 
		    {'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
        {'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
        {'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
				{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'}, 
				{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'}, 
				{'name': 'Indent', 'title':  'Indent', 'css': 'wym_tools_indent'}, 
				{'name': 'Outdent', 'title':  'Outdent', 'css': 'wym_tools_outdent'}, 
		    {'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
		    {'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
		    {'name': 'Preview', 'title': 'Preview', 'css': 'wym_tools_preview'}
		  ],
		  containersHtml: '',
		  classesHtml: '',
 			postInitDialog: function(wym,wdw) {
            var body = wdw.document.body;
            var LinkText = "<div class='row row-indent'>"
            + "Geef url op (inclusief http://)"
            + "<\/div>";
            var TitleText = "<div class='row row-indent'>"
            + "Titel (verschijnt bij mouseover) is optioneel"
            + "<\/div>";

            //add to the dialog
            jQuery(body)
                .filter('.wym_dialog_link').find('.wym_href').eq(0)
                .parent().before(wym.replaceStrings(LinkText));
            jQuery(body)
                .filter('.wym_dialog_link').find('.wym_title').eq(0)
                .parent().before(wym.replaceStrings(TitleText));
        }
    });
});
 
/*-------------------------
			   MODALS
  -------------------------*/ 

$(document).ready(function() {
	// setup modals
	$.jqm.params.modal = true;
	
	// changeContributor modal hitlist
	$("button[name='changeContributor']").click(function(event) {
		// stop automatic event
		event.preventDefault();
		
		// we need a reference to the trigger
		var trigger = $(this);
		
		// check the contributors
		var sText = '';
		var ContributorID = 0;
		$("input[type='checkbox']:checked").each(function(){
			var RawData = $(this).val().split("+");
			if (ContributorID != 0 && ContributorID != RawData[1]) {
				alert('U mag alleen contributors met dezelfde naam selecteren!');
				ContributorID = 0;
				//return false;
				exit();
			}
	
			ContributorID = RawData[1];
		
			if (sText != '')
				sText += ',';
				sText = sText + RawData[0];
		});
		
		if (ContributorID != 0) {
			if (sText != '') {
				// all is well, open the modal
				
				// set src & title
				var sUrl = 'changecontributorform.php?contributorid='+ContributorID+'&productids='+sText.replace(/product/g,'');
				var sTitle = 'Contributors';

				$('#modalWindow').jqm({
					trigger: trigger,
					target: '#jqmContent',
					onShow:  function(hash) {
						var $modal = $(hash.w);
						var iframe = $("iframe", $modal).clone();
						$("iframe", $modal).replaceWith(iframe);
						
						var $modalContent = $("iframe", $modal);
						$modalContent.html('').attr('src', sUrl);
						$('#jqmTitleText').text(sTitle);
						
						$modal.show();					
					}
				}).jqmShow();
			}
		} else {
			alert('Selecteer een of meer (dezelfde) contributors door in de rechterkolom een vinkje te zetten.');
			return false;
		}
	});
	
	// Other modal windows that us
	// name=modal attribute/value pair as trigger	
	
	// Loading Iframes in the Modal
	var loadInIframeModal = function(hash){
		var $trigger = $(hash.t);
		var sUrl = $trigger.attr('href');
		var $modal = $(hash.w);
		var iframe = $("iframe", $modal).clone();
		$("iframe", $modal).replaceWith(iframe);
		
		var $modalContent = $("iframe", $modal);
		$modalContent.html('').attr('src', sUrl);
				
		var sTitle= $trigger.attr('title');
		$('#jqmTitleText').text(sTitle);

		$modal.jqmShow();
		$modal.show();
	}

	// initialise jqModal
	$('#modalWindow').jqm({
		trigger: "button[name='modal']",
		target: '#jqmContent',
		onShow:  loadInIframeModal
	});

});

/*-------------------------
			DATE FUNCTIONS
  -------------------------*/  

$(document).ready(function() {
  // Setup date entry
  var oldlength = 0;
  
  // keyup doesn't always fire, so we'll use keydown 
  // with a timeout  
  var keyspressed = 0;
  $('input.dateentry').keypress(function(event) {
  	keyspressed++;
  });
  
  $('input.dateentry').keyup(function(event) {
  	var t = $(this);
  	var pressed = keyspressed;
  	keyspressed = 0;
  	
  	code = event.keyCode;

  	// compensate keypad
  	if(code > 95) {
  		code = code-48;
  	} 
  	
  	// make sure it's a numerical key
		var char = String.fromCharCode(code);
		var int = parseInt(char, 10);
		if(!isNaN(int)) {
  		// get current length to find position of current key
  		var val = t.val();
  		var length = val.length;

			if(length > oldlength + pressed) {
				t.val(val.substring(0,oldlength));	
			} else {
			
				if(length == 2) {
					// check value
					if(parseInt(val, 10) > 31) {
						val = '31';
					}
					if(parseInt(val, 10) < 1) {
						val = '01';
					}
					t.val(val+'-');
				}
				
				if(length == 5) {
					// check value
					var month = (t.val().substr(3,2));
					if(parseInt(month, 10) > 12) {
						val = val.substr(0,3)+'12';
					}
					if(parseInt(month, 10) < 1) {
						val = val.substr(0,3)+'01';
					}
					t.val(val+'-');
				}	
			}
			oldlength = t.val().length;
  	} else {
  		var val = t.val();
  		var length = val.length;

			// check if length has changed
  		if(length > oldlength) {
				// remove incorrect key
  			t.val(val.substring(0,oldlength));
  		}
  		
  		oldlength = t.val().length;
  	}
  });

});

function forceInt(s) {
    s = '' + s;
    while (s.substr(0, 1) == '0') { s = s.substr(1); }
    return parseInt(s * 1, 10);
}

function DaysInMonth(month, year) {
    if (month == 2) {
    	// February has 29 days in any year evenly divisible by four,
        // EXCEPT for centurial years which are not also divisible by 400.
        d = (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
    }
    else
    if (month == 4 || month == 6 || month == 9 || month == 11)
        d = 30
    else
        d = 31;
    return d;
}

function IsValidDate(D){
	D = ""+D;
	if (D.length != 10)
		return false;

    day = forceInt(D.substr(0,2));
    month = forceInt(D.substr(3,2));
    year = forceInt(D.substr(6,4));
    if (year < 1900)
        return false;
    if (month < 0 || month > 12)
        return false;
    if (day < 1 || day > DaysInMonth(month,year))
        return false;
    return true;
}

function formatDate(D) {
	if (D.length != 8)
		return '';
	return D.substr(6,2)+'-'+D.substr(4,2)+'-'+D.substr(0,4);
}
