$(function(){
	var params = getQueryParams(document.location.search);

	$.each(params, function(index, value){
			if(index=="reload" && value=="true"){
				window.location = window.location.pathname;
			}
		});

});

function getQueryParams(qs) {
	qs = qs.split("+").join(" ");
	var params = {},
		tokens,
		re = /[?&]?([^=]+)=([^&]*)/g;

	while (tokens = re.exec(qs)) {
		params[decodeURIComponent(tokens[1])]
			= decodeURIComponent(tokens[2]);
	}

	return params;
}

function isObject(test) {
	return ((typeof test == 'object') && (test != null ));
}

function getObject(test) {
	if(isObject(test)) {
		return test;
	} else {
		return document.getElementById(test);
	}
}

function hideObject(obj) {
	getObject(obj).style.display = "none";
}

function showObject(obj) {
	getObject(obj).style.display = "block";
}

function isVisible(obj) {
	return (getObject(obj).style.display != 'none');
}

function switchVisibility(obj) {
	if(isVisible(obj)) {
		hideObject(obj);
	} else {
		showObject(obj);
	}
}

function alternateDisplay(show, hide) {
	hideObject(hide);
	showObject(show);
}

function addPriceModelRow(priceModelSelect, priceModelTd) {
	var sel = getObject(priceModelSelect);
	var selection = sel.options[sel.selectedIndex].value;
	
	var priceModelObj = getObject(priceModelTd);
	
	if(selection == 'fixedprice') {
		priceModelObj.innerHTML = getObject("FixedFeeLabel").value + ' <input type="text" name="FixedPriceValue" id="FixedPriceValue" />';
	} else if(selection == 'hourprice') {
		priceModelObj.innerHTML = getObject("NormalFeeLabel").value + ' <input type="text" name="HourPriceValueNormalRate" id="HourPriceValueNormalRate" />' + 
									getObject("IncreasedFeeLabel").value + ' <input type="text" name="HourPriceValueIncreasedRate" id="HourPriceValueIncreasedRate" />' + 
									getObject("HighFeeLabel").value + ' <input type="text" name="HourPriceValueHighRate" id="HourPriceValueHighRate" />';
	} else if(selection == 'specialprice') {
		priceModelObj.innerHTML = getObject("SpecialFeeLabel").value + ': <textarea name="SpecialPriceValue" style="width: 100%;" rows="5"></textarea>';
	} else {
		priceModelObj.innerHTML = '&nbsp;';
	}
}

function getTickets(formDivId, projectId, userId){
	$.ajax({
		type: "POST",
		url: "../Ajax/ticketsystem.php",
		data: {
			functionName: "GetTickets",
			projectId: projectId,
			userId: userId,
			day: formDivId
			},
		dataType: "json", 
		success: function(data){
			if(data.html == "") {
				$("#timeReportTicketsDiv"+formDivId+projectId).css("display", "none");
				return;
			} else {
				$("#timeReportTicketsDiv"+formDivId+projectId).css("display", "block");
				$("#timeReportTickets"+formDivId+projectId).html(data.html);
				$("#trTicketStatus"+formDivId+projectId).attr("disabled", "true");
				$("#showTicket"+formDivId+projectId).attr("disabled", "true");
				$("#ticket_select"+formDivId+projectId).change(function(val){
					var disabled = false;
					if(this.value == -1){
						disabled = true;
					}
					$.ajax({
						type: "POST",
						url: "../Ajax/ticketsystem.php",
						data: {
							functionName: "GetStatusSelectForTicket",
							ticketId: $("#ticket_select"+formDivId+projectId).val()
							},
						dataType: "json", 
						success: function(data){
							$("#ticketStatus"+formDivId+projectId).html(data.html);
							if(disabled) {
								$("#trTicketStatus"+formDivId+projectId).attr("disabled", disabled);
								$("#showTicket"+formDivId+projectId).attr("disabled", disabled);
							} else {
								$("#trTicketStatus"+formDivId+projectId).removeAttr("disabled");
								$("#showTicket"+formDivId+projectId).removeAttr("disabled");
							}
						}
					});		
				});
			}
			
			
		}
	});		
}

function showProjectTickets(projectId, request_uri, sort, where) {
//	alert(projectId);
	//$("#projectTickets").html("TEST");
	$.ajax({
		type: "POST",
		url: "../Ajax/ticketsystem.php",
		async: false,
		data: {
			functionName: "ShowProjectTickets",
			projectId: projectId,
			request_uri: request_uri,
			sort: sort,
			where: where
			},
		dataType: "json", 
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		success: function(data){
			if(data.html == "") {
				$("#projectTickets").html("No html!");
				return;
			} else {
				$("#projectTickets").html(data.html);
				Process_chosen();
			}
		}
	});
}

function hideTicket(){
	$("#ticketContainer").hide();
}

function showEditTicketForm(formDivId, projectId){
	var select = $("#ticket_select"+formDivId+projectId);
	var ticketId = select.val();
	$("#ticketContainer").show();
	$.ajax({
		type: "POST",
		url: "../Ajax/ticketsystem.php",
		data: {
			functionName: "viewTicket",
			ticketId: ticketId
			},
		dataType: "json", 
		success: function(data){
			$("#ticketContainer").html(data.html);
		}
	});
}

function RefreshTicketComments() {
	$.ajax({
		type: "POST",
		url: "../Ajax/ticketsystem.php",
		data: {
			functionName: "GetComments",
			ticketid: $("#ticketId").val()
			},
		dataType: "json", 
		success: function(data){
			$("#ticketCommentHistory").html(data.html);
		}
	});
}

function SubmitTicketComment() {
	$.ajax({
		type: "POST",
		url: "../Ajax/ticketsystem.php",
		data: {
			functionName: "SaveComment",
			ticketid: $("#ticketId").val(),
			content: $("#newCommentContent").val()
			},
		dataType: "json", 
		success: function(data){
			RefreshTicketComments();
		}
	});
	var e = document.getElementById("newCommentContent");
	e.value = "";
}

function RemoveTicketComment(commentId){
	if(!confirm("Vill du verkligen ta bort denna kommentar?"))
		return;
	
	$.ajax({
		type: "POST",
		url: "../Ajax/ticketsystem.php",
		data: {
			functionName: "RemoveComment",
			commentid: commentId
			},
		dataType: "json", 
		success: function(data){
			RefreshTicketComments();
		}
	});
}

function limitText(limitField, limitNum, limitCount) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else if(limitCount){
		limitCount.value = limitNum - limitField.value.length;
	}
}

$(document).ready(function() {
 
    //Select all anchor tag with rel set to tooltip
    $('.tooltip').mouseover(function(e) {
         
        //Grab the title attribute's value and assign it to a variable
        var tip = $(this).attr('title');    
         
        //Remove the title attribute's to avoid the native tooltip from the browser
        $(this).attr('title','');
         
        //Append the tooltip template and its value
        $(this).append('<div id="tooltip"><div class="tipBody">' + tip + '</div></div>');     
         
        //Set the X and Y axis of the tooltip
        //$('#tooltip').css('top', e.pageY - 110 );
        //$('#tooltip').css('left', e.pageX - 165 );
        var docheight = $(document).height();
        var tipheight = $('#tooltip').height();
        var posY = e.pageY + 14;
        var posX = e.pageX + 14;
        
        if (posY + tipheight > docheight) {
			posY -= tipheight;
		}
        
        $('#tooltip').css('top', posY );
        $('#tooltip').css('left', posX );
         
        //Show the tooltip with faceIn effect
        $('#tooltip').fadeIn('500');
        $('#tooltip').fadeTo('10',1);
         
    }).mousemove(function(e) {
     
        //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
        //$('#tooltip').css('top', e.pageY - 110 );
        //$('#tooltip').css('left', e.pageX - 165 );
        
        var docheight = $(document).height();
        var tipheight = $('#tooltip').height();
        var posY = e.pageY + 14;
        var posX = e.pageX + 14;
        
        if (posY + tipheight > docheight) {
			posY -= tipheight;
		}
        
        $('#tooltip').css('top', posY );
        $('#tooltip').css('left', posX );
         
    }).mouseout(function() {
     
        //Put back the title attribute's value
		if($('.tipBody').html() !== null) {
			$(this).attr('title',$('.tipBody').html());
		}
        //Remove the appended tooltip template
        $(this).children('div#tooltip').remove();
         
    });
 
});


//calendar widget in consultview
$(function() {
	//$.datepicker.setDefaults($.datepicker.regional['']);
	$("#datepicker").datepicker({
			dateFormat: 'yy-mm-dd',
			showWeek: true,
			selectWeek:true
		},
		$.datepicker.regional['sv']
	);
	

	$("#datepicker").change(function() {
			
			var getDate = $("#datepicker").datepicker("getDate");
			var pickedDate = $.datepicker.formatDate('yy-mm-dd', getDate );
			
			var week = $.datepicker.iso8601Week( getDate );
			var month = $.datepicker.formatDate('mm', getDate );
			var year = $.datepicker.formatDate('yy', getDate );
			
			if (month == '01' && week > '51')
				year -= 1;
			
			var link = $("#datepicker_post_action").val() + '&function=week&week=' + week + '&year=' + year + '&pickedDate=' + pickedDate;
			//alert(link);
			location.href = link;
	});
});

function ShowCalendar(id, day, month, year){
	
		$("#"+id).datepicker("setDate", year+"-"+month+"-"+day);
	
		$("#"+id).focus();	
}

