/**
 * Common execution js
 * @author AK
 * 
 * dependancies: jQuery 1.2.x
 * 
 */

if (typeof console == 'undefined') {
	console = {
		log: function(){},
		debug: function(){}
	};
}

// isEmpty (twitter et al.)
function isEmpty(str) { if (typeof str == 'undefined' || str === null || str === '' || str == 0) { return true; } return false; }


var p = {}; // container for Peppered scripts

function emailObfuscate () {
   var uri = this.href ;
   var aParams = [] ;
   var aAddressCode = [] ;

   // split uri, identify adress, subject and body
   arrUri = uri.split('/');
   for ( var u = 0; u < arrUri.length; u ++ ) {
   	if ( arrUri[u] == 'mailto' ) {
   	  address = arrUri[u+1] + '@' + arrUri[u+2];
          for ( var i = 0 ; i < address.length ; i++ )
		aAddressCode.push( address.charCodeAt( i ) ) ;

          if ( arrUri[u+3].length > 0 )
	   	aParams.push( 'subject='+ encodeURIComponent( arrUri[u+3] ) ) ;
          if ( arrUri[u+4].length > 0 )
	     	aParams.push( 'body=' + encodeURIComponent( arrUri[u+4] ) ) ;
   	}
   }

   this.href = 'javascript:location.href=\'mailto:\'+String.fromCharCode(' + aAddressCode.join( ',' ) + ')+\'?' + aParams.join( '&' ) + '\'' ;
}


/**
 * Peppered object scripts
 * 
 * called from within tpl 
 * 
 */

p._funcs = {};

p._funcs.createInputHintFromLabel = function($input, labelTxt) {
	
	$input.data('initVal', labelTxt);
	
	if ($input.val() == '') {
		$input.val(labelTxt).addClass('dummyText');
	}
	
	$input
		.focus(function(){
			var $this = $(this);
			if ($this.val() == $this.data('initVal')) {
				$this.val('').removeClass('dummyText');;
			}			
		})
		.blur(function(){
			var $this = $(this);
			if ($this.val() == '') {
				$this.val($this.data('initVal')).addClass('dummyText');
			}
			
		})
	;
	
};


/**
 * p.searchBox
 * 
 * zoekCalendar.stpl
 */
p.searchBox = {

	init: function() {
		
		// label as input hint
		var $form = $('#zoekForm'),
			$input = $('#zoekForm-value'),
			$label = $input.prev().hide(),
			labelTxt = $label.text();		

		p._funcs.createInputHintFromLabel($input, labelTxt);

	}

};

/**
 * p.NLSubscribe
 * 
 * nieuwsbrief.stpl
 */
p.NLSubscribe = {
	
	init: function() {
		
		// label as input hint
		var $form = $('#formNLSubscribe'),
			$input = $('#formNLSubscribe-email'),
			$label = $input.prev().hide(),
			labelTxt = $label.text();

		p._funcs.createInputHintFromLabel($input, labelTxt);
		
		$form.submit(function(e) {			
			if (!$input.val().match(/^([\w-]+\.?)+@([\w-]+\.{1})+[A-Za-z]+$/)) {
				e.preventDefault();
				alert('Aanmelden nieuwsbrief mislukt:\n\nGeen geldig e-mail adres opgegeven.')
				$input.focus().select();
			}
		});
		
	}

};


/**
 * p.enhanceSelect
 * 
 * for now only geared towards the header dropdowns
 */
p.enhanceSelect = function(selectId, opts) {
	var $select = $('#'+selectId),
		$form = $select.parents('form').first(),
		opts = opts || {},
		changeFn = selectFn = null
	;
	
	if (opts.dummyText !== undefined) {
		$select.prepend('<option value="" class="dummyText">' + opts.dummyText + '</option>');
		changeFn = function(){
			$form.submit();
		};
	}
	else {
		selectFn = function(){
			$form.submit();
		};
	}
	
	//$(function(){
	opts.width = (opts.width === undefined) ? 127 : opts.width;	
	opts.menuWidth = (opts.menuWidth === undefined) ? 147 : opts.menuWidth;	
	
	$select.selectmenu({
		width: opts.width,
		menuWidth: opts.menuWidth,
		change: changeFn,
		select: selectFn
	});
	if (opts.dummyText !== undefined) {
		$select.selectmenu('index', 0);
	}
	//});
	$form.find('input.toonBtn').hide();
	//$form.find('.ui-selectmenu-status').text('test');
	
};



/**
 * hover imput
 */

$(function() {
// MouseOver effect op submit buttons
 $('input.submit').hover(function() {
    $(this).addClass('btnHover');
  }, function() {
    $(this).removeClass('btnHover');
  });
});


/**
 * DOMReady scripts
 */

$(function(){
	/**
	 * anchors (external/popup)
	 * 
	 */
	var oPopWin = null;
	
//	$("a[href^='/mailto']").each(emailObfuscate);
	$("a[rel='external']").click(function(){window.open(this.href); return false});
	$("a[rel='popup']").click(function(){
		popWin = new PopupWindow();
		popWin.anchor = $(this);
		popWin.width = 500;
		popWin.height = 500;
		if (popWin.spawn())
			return false;
	});
	
	/**
	 * rel=modal
	 * Requires id attribute for anchor, format: btnXXX
	 */
	$("a[rel='modal']").click(function(e) {
		
		var $this = $(this),
			target = $this.attr('href'),
			title = $this.attr('title')
		;
		
		if (target.indexOf('?') > 0) {
			target += "&rt=pageContentOnly";
		} else {
			target += "?rt=pageContentOnly";
		}
		
		//console.log($this.attr('id').substr(3));
		$.pDialog({
			id: $this.attr('id').substr(3),
			type: 'page',
			title: title,
			hideTitleBar: true,
			load: target,
			width: 500,
			buttons: {
				'sluiten': {
					action: 'cancel'
				}
			}
		});
		
		e.preventDefault();
	});
	
	$('#calendarForm input[type="submit"]').hide();
	$('#calendarForm select').change(function() {
		$(this).get(0).form.submit();
	});

	// shipping address (MT)
	$('.formPaymentMethods #otherAddressContainer').not(".jsForceVisible").hide();
	$('.formPaymentMethods .radio[name=shippingAddress]').change(function() {
        $('.formPaymentMethods #otherAddressContainer').toggle('fast');
	});
	
	$('#buttonEmailMatchReminder').click(function() {
		$(this).effect("transfer", {to: '#vergetenForm', className: 'red', complete:function(){$("#vergetenForm").effect("transfer", {to: '#vergetenForm-email', className: 'red', complete:function(){$("#vergetenForm-email").focus()}})}});
		return false;
	});
	
	// iframe z-index (YT embed)
	$('.richtext iframe').each(function(){
		var $this = $(this),
			url = $this.attr('src');
		if (url.indexOf('youtube') > -1) {
			$(this).attr("src", url + ((url.indexOf('?') > -1) ? "&" : "?") + "wmode=transparent");
		}
	});

});
