


$(document).ready(function() {
	
	$dateSeparator        = "-";
	$dateYearPosition     = 0;
	$dateMonthPosition    = 1;
	$dateDayPosition      = 2;
	$datePickerDateFormat = "yy"+$dateSeparator+"mm"+$dateSeparator+"dd";
	$dateMonthNamesShort  = $.datepicker.regional['no']['monthNamesShort'];

	$('#menu li').mouseover(function(){
		if($(this).attr('class') != 'selected')
			$(this).addClass('over');
	});
	$('#menu li').mouseout(function(){
		if($(this).attr('class') != 'selected')
			$(this).removeClass('over');
	});

	$(".frm").submit(function(){
		return checkForm($(this));
	});

	$('#logout').click(function(){
		link = $(this).attr('href');
		if(confirm('Are you sure you want to logout?')){
			self.location.href=link;
		}
		return false;
	});
	
	$('.listing tr').mouseover(function(){
		if($(this).attr('class') == '')
			$(this).addClass('over');
	});
	$('.listing tr').mouseout(function(){
		$(this).removeClass('over');
	});
	
	closeAddedMsg();

	$("img.delRec").click(function(){
		var el = $(this);
		var uri = '/'+el.parent().attr("href");
		if(window.confirm("Are you sure you want to delete the record?")) {
			$.ajax({
				type: "GET",
				url: uri,
				success: function(msg){
					if(msg==1) {
						el.parent().parent().parent().fadeOut("slow");
					}
				}
			});
		}
		return false;
	});

	$('#saved .close img').click(function(){
		$("#saved").fadeOut();
	});

	$('.performers_chk').click(function(){
		elid = $(this).attr('value');
		if($(this).attr('checked'))
			$('#hours_'+elid).attr('disabled', false);
		else
			$('#hours_'+elid).attr('disabled', true);
	});

	$('.date').datepicker({ firstDay: 1, dateFormat: $datePickerDateFormat });

	$('.pickdate').click(function(){
		$('#'+$(this).attr("alt")).trigger('focus');
	});

	var date_i = $('#numdates').attr('value');

	$('#adddate').click(function(){
		thenewdate = '<div class="newdate"><input type="text" name="date[]" id="date_'+date_i+'" autocomplete="off" value="" class="frmField date eventdate" readonly="readonly" /> <img src="img/icn_calendar2.png" width="16" height="16" alt="" border="0" style="margin-right: 5px;" id="pickdate_'+date_i+'" class="pickdate" /> <img src="img/cancel.png" width="16" height="16" alt="" border="0" class="remdate" /></div>';
		$('#dates').append(thenewdate);
		date_i++;
		$('#numdates').attr('value', date_i);
		return false;
	});

	$('.pickdate').livequery('click', function(event){ 
		elid = $(this).attr('id').split('_');
		$('#date_'+elid[1]).trigger('focus');
	});
	$('.date').livequery(function(){ 
		$(this).datepicker({ firstDay: 1, dateFormat: $datePickerDateFormat });
	});
	$('.remdate').livequery('click', function(event){ 
		$(this).parent().remove();
	});

	$('.cal_month .on').mouseover(function(){
		$(this).removeClass('on');
		$(this).addClass('over');
	});
	$('.cal_month .on').mouseout(function(){
		$(this).removeClass('over');
		$(this).addClass('on');
	});

	$('.cal_month .on').click(function(){
		$('#popup_content').html('');
		$('#popup').hide();
		$.getScript("/schedule/getEventData/date/"+$(this).attr('date')+"/", function(){
			$('#popup_content').css({'overflow-y': 'auto', 'height': 'auto'});
			$height = $('#popup').height()/2 * -1;
			$('#popup').css("margin-top", $height);
			$('#popup').fadeIn();
			if($('#popup').height() > ($(window).height()-80)) {
				$('#popup_content').css({'overflow-y': 'scroll', 'height': ($(window).height()-80)});
				$height = $('#popup').height()/2 * -1;
				$('#popup').css("margin-top", $height);
			}
		});
	});
	$('.plannerEvent').click(function(){
		$id_event = $(this).attr('alt');

		$('#popup_content').html('');
		$('#popup').hide();
		$.getScript("/planner/getEventData/id_event/"+$id_event+"/", function(){
			$('#popup_content').css({'overflow-y': 'auto', 'height': 'auto'});
			$height = $('#popup').height()/2 * -1;
			$('#popup').css("margin-top", $height);
			$('#popup').fadeIn();
			if($('#popup').height() > ($(window).height()-80)) {
				$('#popup_content').css({'overflow-y': 'scroll', 'height': ($(window).height()-80)});
				$height = $('#popup').height()/2 * -1;
				$('#popup').css("margin-top", $height);
			}
		});
	});
	$('div.close img').click(function(){
		$('#popup').fadeOut();
	});

	$('#bubble .close').click(function(){
		$('#bubble').fadeOut('fast');
	});

	$('#is_group').change(function(){
		if($(this).attr('value') == 2){
			$('#div_partof').fadeIn();
		} else{
			$('#div_partof').fadeOut();
		}
	});

	$('#addperformer').click(function(){
		$('#lightbox').fadeIn('fast');
		addPerformer();
	});

	$('#lightbox').click(function(){
		$('#window').fadeOut('fast');
		$(this).fadeOut('fast');
	});

	$('.eventdate').livequery('change', function(event){ 
		if($(this).attr('value') != ""){
			dates += ","+$(this).attr('value');
		}
	});
	
	$('input.quarter').change(function(){ 
		if( isNaN($(this).val()) ){
			$(this).val(0);
		}
		assignedhrs();
	});
	
	$('input.kvartal').change(function(){ 
		if( isNaN($(this).val()) ){
			$(this).val(0);
		}
		kassignedhrs();
	});
	
	$('input.production').click(function(){ 
		$('#production').show();
		$('#event_name').hide();
		$('#productiondates').show();
		$('#otherdates').hide();
	});
	
	$('input.other').click(function(){ 
		$('#production').hide();
		$('#event_name').show();
		$('#productiondates').hide();
		$('#otherdates').show();
	});
	
	$('img.delDato').livequery('click', function(event){ 
		if(window.confirm('¿Are you sure you want to remove this date?')) {
			$(this).parent().remove();
		}
	});
	
	$('#adddates').click(function(){
		if($('#date_from').val()!='' && $('#date_to').val()!='') {
			$one_day = 1000*60*60*24;				
			$_datefrom = $('#date_from').val().split($dateSeparator);
			$_dateto = $('#date_to').val().split($dateSeparator);
			$pdcount = parseInt($('#pdcount').val());
			$odcount = parseInt($('#odcount').val());
			$datefrom = new Date($_datefrom[$dateYearPosition], $_datefrom[$dateMonthPosition]-1, $_datefrom[$dateDayPosition]);
			$dateto = new Date($_dateto[$dateYearPosition], $_dateto[$dateMonthPosition]-1, $_dateto[$dateDayPosition]);
			$days = Math.ceil(($dateto.getTime()-$datefrom.getTime())/($one_day));
			$phtml = '';
			$ohtml = '';
			$warning = false;
			$k = new Array();
			if($days<0) {
				alert('Date to must be greater than date from');
			} else {
				for($i=0; $i<=$days; $i++) {
					$date = new Date();
					$date.setTime($datefrom.getTime()+($one_day*$i));
					$_year = $date.getFullYear();
					$_month = ($date.getMonth()>8) ? $date.getMonth()+1 : '0'+($date.getMonth()+1);
					$_day = ($date.getDate()>9) ? $date.getDate() : '0'+$date.getDate();
					$_k = Math.floor(($date.getMonth()+1)/4) + 1;
					if(parseInt($("input[checked][name='id_eventtype']").val()) < 3) {
						$pdcount = $pdcount + 1;
						$phtml = $phtml + '<li><input type="hidden" name="pdate_'+$pdcount+'" value="'+$_year+'-'+$_month+'-'+$_day+'" /><span style="width:80px"><input type="checkbox" name="test_'+$pdcount+'" value="1" class="chkoption" /></span><span style="width:50px"><input type="checkbox" name="tour_'+$pdcount+'" value="1" /></span><span class="dato">'+$_day+'. '+$dateMonthNamesShort[$_month-1]+'. '+$_year+' (K'+$_k+' '+$_year+')</span><img src="img/cancel.png" alt="" border="0" class="delDato" /></li>';
					} else {
						$odcount = $odcount + 1;
						$ohtml = $ohtml + '<li><input type="hidden" name="odate_'+$odcount+'" value="'+$_year+'-'+$_month+'-'+$_day+'" /><span class="dato">'+$_day+'. '+$dateMonthNamesShort[$_month-1]+'. '+$_year+' (K'+$_k+' '+$_year+')</span><input type="text" name="details_'+$odcount+'" value="" class="frmField details" /><img src="img/cancel.png" alt="" border="0" class="delDato" /></li>';

					}
					$k[$i] = $_k;
					if($i>0 && $k[$i-1]!=$k[$i]) {
						$warning = true;
					}
				}
				$('#pdcount').val($pdcount);
				$('#odcount').val($odcount);
				$('#quarter').val($k[0]);
				if(parseInt($("input[checked][name='id_eventtype']").val()) < 3) {
					$('#productiondates').append($phtml);
				} else {
					$('#otherdates').append($ohtml);
				}
				if($warning) {
					alert('Warning! You selected dates from different quarters.\nQuarter of first date will be set as default.');
				}
				set_remaining_hrs();
			}
		} else {
			alert('Please select both dates');
		}
		return false;
	});
	
	$('input.plannedhrs, input.actualhrs').change(function(){ 
		if( isNaN($(this).val()) ){
			$(this).val(0);
		}
		set_remaining_hrs();
	});
	
	$("#changeperf").click(function(){
		self.location.href = '/schedule/'+$(this).attr("title")+'/id/' + $('#selperformer').val();
	});
	
	$("#changeyear").click(function(){
		self.location.href = '/performers/main/year/' + $('#selyear').val();
	});
	
	$("form.frm").submit(function(){
		if($(this).hasClass("add-event")) {
			$.get("/events/check/?"+$(this).serialize(), 
				function(data){
					if(data!="") {
						if(!window.confirm(data+"\nDo you want to continue?")) {
							return false;
						} else {
							$frm = $("form.add-event");
							$frm.removeClass("add-event").trigger("submit");
						}
					} else {
						$frm = $("form.add-event");
						$frm.removeClass("add-event").trigger("submit");
					}
			});
			return false;
		}
	});
	
	$("#updateActualHrs").click(function(){
		$("input[name='update_actual_hrs']").val(1);
	});
	
});

function set_remaining_hrs() {
	$k = parseInt($('#quarter').val());
	$("#pflist tr td[class]").each(function(i){
		$_k = $(this).attr("class").split('|');
		$_planned = parseFloat($("#planned_"+(i+1)).val());
		$_actual = parseFloat($("#actual_"+(i+1)).val());
		$_remaining = $_k[$k-1] - $_planned;
		$("#remaining_"+(i+1)).val($_remaining);
	});
}

function assignedhrs() {
	$sum = 0;
	$('input.quarter').each(function(){ 
		if( !isNaN($(this).val()) && $.trim($(this).val())!= '' ){
			$sum += parseFloat($(this).val());
		}
	});
	$('#totalassignedhrs').val($sum);
}

function kassignedhrs() {
	$sum = 0;
	$('input.kvartal').each(function(){ 
		if( !isNaN($(this).val()) && $.trim($(this).val())!= '' ){
			$sum += parseFloat($(this).val());
		}
	});
	$('#ktotalassignedhrs').val($sum);
}

function closeAddedMsg(){
	var t=setTimeout('$("#saved").fadeOut();',5000);
}

function checkForm(frm) {

		var errors = 0;
		frm.find("input").each(function(i) {
			var el = $(this);
			if(el.attr("required")=="true") {
				if(el.attr("type")=="text" || el.attr("type")=="password" || el.attr("type")=="file") {
					if($.trim(el.val())=="") {
						alert(el.attr("title"));
						el.focus();
						errors = 1;
						return false;
					} else if(el.attr("reqtype")=="email"){
						if(!check_email(el.attr('value'))){
							alert(el.attr("title"));
							el.focus();
							errors = 1;
							return false;
						}
					}
				}
			}
		});
		if(errors==1) {
			return false;
		}
		frm.find("textarea").each(function(i) {
			var el = $(this);
			if(el.attr("required")=="true") {
				if($.trim(el.val())=="") {
					alert(el.attr("title"));
					el.focus();
					errors = 1;
					return false;
				}
			}
		});
		if(errors==1) {
			return false;
		}
		frm.find("select").each(function(i) {
			var el = $(this);
			if(el.attr("required")=="true") {
				if($.trim(el.val())=="0") {
					alert(el.attr("title"));
					el.focus();
					errors = 1;
					return false;
				}
			}
		});
		if(errors==1) {
			return false;
		}
}

function addPerformer(){
	$('#window').fadeIn();
	$.getScript('events/loadPerf/'+dates+'/'+performers);
	alert(dates);
	alert(performers);
}

String.prototype.pad = function(l, s, t){
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
		+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
		+ this + s.substr(0, l - t) : this;
};