/* page.js|customers */
function initPageJs(){
	accessibleInputs();
	datePickers();
	ticketProgressBar();
	ticketCountdown();
}

function datePickers(){
	$("#mdGlobalSearch").find(".mdFormSelectWrap + .mdFormTextWrap .mdFormText").datepicker({
			showOn: 'button',
			buttonImage: 'templates/billetexpressen/img/icons/calendar_view_month.png',
			buttonImageOnly: true,
			buttonText:	'Vælg dato',
			showOn: 'both'
	});
}

function ticketProgressBar(){
	$(".mdTicketsProgress").each(function(){
		var pWidth = $(this).find(".mdAvailable").html();
		$(this).addClass("mdTicketsProgressJs").append('<div class="mdTicketsBar"><div style="width:'+pWidth+'%"></div></div>');
	})
}

function ticketCountdown(){
	// these lines are only for demo purposes and should be deleted
	
	
	// end demo lines
	var showTime = $(".doCountDown").attr("title");
	var nowTime = new Date;
	var nowTimeUnix = parseInt(nowTime.getTime() / 1000);
	var remainingTime = showTime - nowTimeUnix;
	$(".doCountDown").addClass("countdown");
	$.autocountdown() // loop
}

// runs when dom is loaded
$(document).ready(function(){
  initPageJs();
});

/* Danish initialisation for the jQuery UI date picker plugin. */
/* Written by Jan Christensen ( deletestuff@gmail.com). */
jQuery(function($){
    $.datepicker.regional['da'] = {
		closeText: 'Luk',
        prevText: 'Forrige',
		nextText: 'Næste',
		currentText: 'Idag',
        monthNames: ['Januar','Februar','Marts','April','Maj','Juni',
        'Juli','August','September','Oktober','November','December'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
        'Jul','Aug','Sep','Okt','Nov','Dec'],
		dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
		dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
		dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
		weekHeader: 'Uge',
        dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['da']);
});
/* accessibleInputs.js|global */
//Accessible Inputs (requires jQuery)

// moves labels value to inputs if class 'mdValueToInput' is present & then adds focus/blur to inputs
function accessibleInputs(){
	$("label.mdValueToInput[for]").each(function(i){
		// fill input fields with labeltext - html tags
		var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
		var newVal = this.innerHTML.replace(regexp,"");
		//if el is type=input or textarea
		if($("#"+this.htmlFor).is("input") || $("#"+this.htmlFor).is("textarea")){
			if(($("#"+this.htmlFor).val() == "") || ($("#"+this.htmlFor).val() == newVal)){
				$("#"+this.htmlFor).attr("value",newVal);
			}
			// create onclick/blur functionality
			$("#"+this.htmlFor).focus(function(){if(this.value == newVal) this.value = "";});
			$("#"+this.htmlFor).blur(function(){if(this.value == "") this.value = newVal;});
		// if el is select	
		} else if($("#"+this.htmlFor).is("select")){
			var orgOptions = $("#"+this.htmlFor).html();
			var newOptions = '<option value="">'+newVal+'</option>'+orgOptions;
			// IE special Kung Fu
			if($.browser.msie && $.browser.version < 8){
				var go=0;
				$("#"+this.htmlFor).find("option").each(function(i){
					if($(this).get(0).defaultSelected){
						go=1;
					}
				})
				if(go==0){
					newOptions = newOptions.replace(/selected>/g,">");
				}
			}
			$("#"+this.htmlFor).html(newOptions);
			// IE8 force choose first option
			if($.browser.msie && $.browser.version <= 8){
				$("#"+this.htmlFor + " option:first").attr("selected","selected")
			}
		}
		// hide label
		$(this).hide();
	})
	cleanForms();
}

// makes sure that label values are not submitted to forms
function cleanForms(){
	$("form:has(label.mdValueToInput)").submit(function(){
		$("label.mdValueToInput[for]").each(function(){
			// check if value is same as label
			var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
			var newVal = this.innerHTML.replace(regexp,"");
			if($("#"+this.htmlFor).attr("value") == newVal){
				$("#"+this.htmlFor).attr("value","");
			}
		})
	})
}

/* countdown.js|customers */
/* jQuery countdown plugin
* version 1.0 (03/09/2009)
* originally by by Alessandro Feijó (alef@feijo.pro.br)
* modified by Kim Blim Johannesen for Peytz&Co (www.peytz.dk) for semantic reasons
*/

(function($) { 

var vInt=0; // this variable controls the loop
var refresh=1; // refresh when a time finish
var interval=1000; // the loop interval


// this function autostarts the infinite loop, every second, triggers the countdown fn
jQuery.autocountdown = function () {
	$('.countdown').countdown(); // trigger the fn
	vInt=setInterval("$('.countdown').countdown();", interval); // set the loop
}

// countdown function, update second-by-second the time to finish
jQuery.fn.countdown = function (options) {
	var defaults = {  // set up default options
		refresh:     0,		 // refresh when a time finish
		interval:    1000, // the loop interval
		cdClass:     'countdown', // the class to apply this plugin
		granularity: 4,
		
		label:    ['u ', 'd ', ':', ':', ''],
		units:    [604800, 86400, 3600, 60, 1]
	};
	if (options && options.label) {
		$.extend(defaults.label, options.label);
		delete options.label;
	}
    if (options && options.units) {
      $.extend(defaults.units, options.units);
      delete options.units;
    }
	$.extend(defaults, options);

	// pad fn, add left zeros to the string
	var pad = function (value, length) {
		value = String(value);
		length = parseInt(length) || 2;
		while (value.length < length)
			value = "0" + value;
		if (value<1) value = "00";
		return value;
	};

	var format_interval = function (timestamp) {
		var label = defaults.label;
		var units = defaults.units;
		var granularity = defaults.granularity;

		output = '';
		for (i=1; i<=units.length; i++) {
			value=units[i];
			if (timestamp >= value) {	      				
				if(value == 86400) {
				  var unitlength = 1;
				}
				else {
				  var unitlength = 2;
				}
				var val=pad(Math.floor(timestamp / value), unitlength); 
				val = val>0 ? val : '00';
				output += val + label[i];
				timestamp %= value;
				granularity--;
			}
      else if (value==60 && output.length > 0) output += '00' + label[i]; // we need the final minute if there also are hours left, i.e., 02:00:34
			else if (value==1) output += '00'; // we need the final seconds to allways show 00, i.e., 03:00

			if (granularity == 0)
				break; 
		}
		
		if (output.length<3) output = '00:'+output;
		return output ? output : '00:00';
	}
	
	// the countdown core
	return this.each(function() {
		secs=$(this).attr('title');
		$(this).html(format_interval(secs));
		secs--;
		
		if (secs<0) {
			$(this).attr('title', 'Stream er nu live');
			$(this).text('Vises nu:')
			clearInterval(vInt);
		} else
			$(this).attr('title', secs);
		
	});

}
})(jQuery);

