var modified = new Array();

$(document).ready(function(){
	$("form").not('.no-trigger').children().change(function() { 
		section = $(this).parents('div.ui-content').attr('id');
		var modifiedMsg = 'Tietoja muutettu <span class="ui-icon ui-icon-alert"></span>';
		ajaxLoad(section, modifiedMsg);
		setModified(section); 
	});
	
	$('table.colors tbody tr:not([th]):odd').addClass('odd');
	$('table.colors tbody tr:not([th]):even').addClass('even');
	
	windowWidth();
	makeButtons();
	matchHeights();
	externalLinks();
	imagePreview();
});

// Check the window width also when resizing the window:
$(window).resize(function() {
	windowWidth();
});

function windowWidth()
{
	// Different CSS-positioning for #outerContainer in not-wide-enough-window (e.g. mobile devices):
	var viewportwidth;
	if(window.innerWidth != undefined)
	{
		viewportwidth = window.innerWidth;
	}
	else
	{
		if(document.documentElement)
		{
			viewportwidth = document.documentElement.clientWidth;
		}
	}
	if(viewportwidth < '1120')
	{
		$('#outerContainer').css('position', 'absolute');
	}
	else
	{
		$('#outerContainer').css('position', 'relative');
	}
}

function makeButtons()
{
	$('.button-login').button({
		icons: {
			primary: 'ui-icon-key'
		}
	});
	$('.button-window').button({
		icons: {
			primary: 'ui-icon-newwin'
		}
	});
	$('.button-new').button({
		icons: {
			primary: 'ui-icon-plus'
		}
	});
	$('.button-edit').button({
		icons: {
			primary: 'ui-icon-pencil'
		}
	});
	$('.button-arrange').button({
		icons: {
			primary: 'ui-icon-arrowthick-2-n-s'
		}
	});
	$('.button-archive').button({
		icons: {
			primary: 'ui-icon-calendar'
		}
	});
	$('.button-back').button({
		icons: {
			primary: 'ui-icon-arrowthick-1-w'
		}
	});
	$('.button-check').button({
		icons: {
			primary: 'ui-icon-check'
		}
	});
	$('.button-category').button({
		icons: {
			primary: 'ui-icon-note'
		}
	});
	$('.button-cart').button({
		icons: {
			primary: 'ui-icon-cart'
		}
	});
	$('.button-delete').button({
		icons: {
			primary: 'ui-icon-trash'
		}
	});
	$('.button-search').button({
		icons: {
			primary: 'ui-icon-search'
		}
	});
	$('.button-save').button({
		icons: {
			primary: 'ui-icon-disk'
		}
	});
	$('.button-user').button({
		icons: {
			primary: 'ui-icon-person'
		}
	});
	$('.button').button();
	
	// Pagination custom buttons
	$('.pagination-button-next a').button({
		text: false,
		icons: {
			primary: 'ui-icon-triangle-1-e'
		}
	});
	$('.pagination-button-prev a').button({
		text: false,
		icons: {
			primary: 'ui-icon-triangle-1-w'
		}
	});
	$('.pagination-button-first a').button({
		text: false,
		icons: {
			primary: 'ui-icon-seek-start'
		}
	});
	$('.pagination-button-last a').button({
		text: false,
		icons: {
			primary: 'ui-icon-seek-end'
		}
	});
	
	// Napit ilman tekstiä
	$('.button-no-text').each(function(){
		$(this).button('option', 'text', false)
	});
}

function setHeights(_target, _height)
{
	var height = 0;
	targets = $(_target).children("div.ui-match-height > div:not(.ui-clear)");
	targets.each(function()
	{
		$(this).css('height', '');
		theight = $(this).height();
		if(theight > height)
		{
			height = theight;
		}
	});
	targets.each(function()
	{
		$(this).css('height', height+'px');
		height2 = 0;
		$(this).children("div").each(function()
		{
			height2 = height2 + $(this).outerHeight(true);
		});
		$(this).children("div.ui-footer").each(function()
		{
			$(this).css('bottom', '');
		});
		if(height > height2)
		{
			movement = height - height2;
			$(this).children("div.ui-footer").each(function()
			{
				$(this).css('bottom', '-'+movement+'px')
			});	
		}
	}); 
}

function matchHeights(target)
{
	if(target != undefined) 
	{
		target = $('#'+target);
		height = target.outerHeight();
		setHeights(target, height);
	}
	else
	{
		$('div.ui-match-height').each(function()
		{
			target = $(this);
			height = target.outerHeight();
			setHeights(target, height)
		});
	}
}

function processAjaxResponse ( data )
{
    // 'data' is the json object returned from the server 
	switch (data.type)
	{
		case 'error-multi':
			$('#dialog').html("");
			jQuery.each(data.errors, function(i, val)
			{
				$('#dialog').append("<p>"+val+"</p>");
			});
			$('#dialog').dialog(
			{
				modal: true,
				title: php_lang_virheita,
				resizable: false,
				buttons:
				{
					Ok: function()
					{
						$(this).dialog('destroy');
					}
				},
				close: function()
				{
					$(this).dialog('destroy');
				}
			});
			return false;
		break;
		case 'error':
			// 'data' is the json object returned from the server 
			// alert(data.message); 
			$('#dialog').html(data.message);
			$('#dialog').dialog(
			{
				modal: true,
				title: php_lang_virhe,
				resizable: false,
				buttons:
				{
					Ok: function()
					{
						$(this).dialog('destroy');
					}
				},
				close: function()
				{
					$(this).dialog('destroy');
				}
			});
			return false;
		break;
		case 'error-login':
			$('#dialog').html('Sessiosi on päättynyt.<br />Ole hyvä ja kirjaudu sisään uudelleen<br />ennen kun klikkaat Ok.');
			$('#dialog').dialog(
			{
				modal: true,
				title: 'Sessio päättynyt!',
				resizable: false,
				buttons:
				{
					Ok: function()
					{
						$(this).dialog('destroy');
						window.location.reload();
					}
				},
				close: function()
				{
					$(this).dialog('destroy');
					window.location.reload();
				}
			});
			return false;
		break;
		case 'allok':
			return true;
		break;
	}
}

function errorHandler ( msg )
{ 
    // 'data' is the json object returned from the server 
    //	alert(data.message); 
	$('#dialog').html(msg);
	$('#dialog').dialog(
	{
		modal: true,
		resizable: false,
		title: php_lang_virhe,
		buttons:
		{
			Ok: function()
			{
				$(this).dialog('destroy');
			}
		},
		close: function()
		{
			$(this).dialog('destroy');
		}
	});
}

function ajaxLoad( section, message )
{
	$('#loading_'+section).html(message);
	$('#loading_'+section).show();
}

function ajaxLoadOff( section, message)
{ 
	$('#loading_'+section).html(message);
	$('#loading_'+section).show().delay(5000).fadeOut('fast', function()
	{
		loc = jQuery.inArray(section, modified);
		if(loc != -1)
		{
			var modifiedMsg = 'Tietoja muutettu <span class="ui-icon ui-icon-alert"></span>';
			ajaxLoad(section, modifiedMsg);
		}
	});
}

function setModified(section)
{ 
	loc = jQuery.inArray(section, modified);
	if(loc != -1)
	{
		modified.push(section);
	}
}

function unsetModified(section)
{ 
	loc = jQuery.inArray(section, modified);
	if(loc != -1)
	{
		modified.splice(loc, 1);
	}
}

function confirmExit()
{
	if(modified.length > 0)
	{
		return php_lang_tietoja_muutettu_tarkistus;
	}
	/* else if (swfu.getStats().files_queued > 0)
	{
		return php_lang_kuvalataus_kesken_tarkistus;
	} */
}

function externalLinks()
{
	if (!document.getElementsByTagName)
		return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
			anchor.getAttribute("rel") == "external")
				anchor.target = "_blank";
	}
}

/** 
 *
 * Tooltip Image Preview
 *
 */
this.imagePreview = function()
{
	/* CONFIG */
		// These 2 variable determine popup's distance from the cursor;
		// You might want to adjust to get the right result.
		// Default values: x=10 y=30
		xOffset = 240;
		yOffset = 20;
	/* END OF CONFIG */
	$('a.preview').hover(function(e){
		this.t = this.title;
		this.title = '';
		var c = (this.t != '') ? '<br/>' + this.t : '';
		$('body').append('<p id="preview"><img src="'+ this.href +'" alt="Hetkinen..." />'+ c +'</p>');
		$('#preview')
			.css('top',(e.pageY - xOffset) + 'px')
			.css('left',(e.pageX + yOffset) + 'px')
			.fadeIn('fast');
    },
	function(){
		this.title = this.t;
		$('#preview').remove();
    });
	$('a.preview').mousemove(function(e){
		$('#preview')
			.css('top',(e.pageY - xOffset) + 'px')
			.css('left',(e.pageX + yOffset) + 'px');
	});
};

/**
*
*	IE6 :hover fix for navigation
*
*/
sfHover = function() {
	var sfEls = document.getElementById('navigation').getElementsByTagName('LI');
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=' sfhover';
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(' sfhover\\b'), '');
		}
	}
}
if (window.attachEvent) window.attachEvent('onload', sfHover);
