/**
 * ISSN ajax request
 */
issn = {
		
		/**
		 * Retrieves open access journal information
		 * 
		 * @param  string	issn_number		issn number of journal
		 * 
		 * @return void
		 */
		get: function ( issn_number )
		{
			$.ajax(
			{
				url: "/export/de/json/journal/issn/" + issn_number,
				dataType: "json",
				success: function( data ) 
				{
					var node = $("input#journal_title").parent();
					
					if ( node.length == 0 )
					{
						node = $("input#publisher_of_proceedings").parent();
					}
					
					var content = $("#formcontent");
					
					if ( typeof content != 'undefined' )
					{
						for ( i=0 ;i<=4 ;i++) $("#formcontent").remove();
					}
					
					if ( typeof node != 'undefined' && node.length &&
					     typeof data != 'undefined' && 
					     typeof data.publishers != 'undefined' && 
					     typeof data.publishers.publisher != 'undefined' )
					{
						
						node.append('<div id ="formcontent">Open Access Pre-Print: ' + 
								     data.publishers.publisher.preprints.prearchiving +  
							        '</div>');
						
						node.append('<div id ="formcontent">Open Access Post-Print: ' + 
							         data.publishers.publisher.postprints.postarchiving +  
						            '</div>');
						
						//node.append('<div id ="formcontent">Open Access Color: ' + 
						//		     data.publishers.publisher.romeocolour +  
					    //            '</div>');
						
						node.append('<div id ="formcontent">' +
								    'Mehr Informationen auf <a target="_blank" href="http://www.sherpa.ac.uk/romeo/search34.php?issn=' + issn_number + 
									'">http://www.sherpa.ac.uk'  +  
					                '</a></div>');
					}
				}
			});
		}
};

/**
 * Journal autocompletion object
 */
journal = {
		
		
		/**
		 * Minimum length of the input string to enable auto completion
		 * 
		 * @param  integer
		 */
		minLength: 2,
		
		/**
		 * Retrieves autocompletion results
		 * 
		 * @param  object	request			request object
		 * @param  object	response		response object
		 * 
		 * @return response items
		 */
		source: function( request, response ) 
		{
			$.ajax(
			{
				url: "/export/de/json/journal/title/" + request.term,
				dataType: "json",
				success: function( data ) 
				{
					response( $.map( data, function( item ) 
					{
						return {
							label: item.journal_title.length < 50 ?  item.journal_title : item.journal_title.substr(0,50) + '...',
							value: item.journal_title,
							publisher: item.publisher,
							issn: item.ISSN_number,
						    issn_online: item.ISSN_number_online,
						    location: item.location_of_publisher
						}
					}));
				}
			});
		},
		
		/**
		 * Select handler function
		 * 
		 * @param  object	event			event happening on element
		 * @param  object	ui				ui element properties
		 * 
		 * @return void
		 */
		select: function( event, ui ) 
		{
			if ( ui.item )
			{
				if ( ui.item.issn )
				{
					issn.get(ui.item.issn);
				}
				
				if ( $("input#publisher").length )
				{
					$("input#publisher")[0].value = ui.item.publisher;
				}
				
				if ( $("input#location_of_publisher").length )
				{
					$("input#location_of_publisher")[0].value = ui.item.location;
				}
				
				if ( $("input#ISSN_number").length )
				{
					$("input#ISSN_number")[0].value = ui.item.issn;
				}
				
				if ( $("input#ISSN_number_online").length )
				{
					$("input#ISSN_number_online")[0].value = ui.item.issn_online;
				}
			}
		}
};


/**
 * Enables autocomplete
 */
function autocomplete ()
{	
	$(document).ready(function() 
			{
				$("input#journal_title").autocomplete(journal);
			});
	
	$(document).ready(function() 
			{
				$("input#publisher_of_proceedings").autocomplete(journal);
			});
}


/**
 * Write Alert Message
 * 
 * @param str		alert message
 * @return void
 */
function alert( text )
{
	if ( typeof text != 'undefined' && text.length)
	{
		text = text.replace(/-/g, "<BR/>-");
		$.prompt(text);
	}
}

/**
 * Confirmation box for removing document
 * 
 * @param text		confirmation box text
 * @param url		url to delete document
 * 
 * @return void
 */
function document_remove ( text, url )
{
	if ( text.length )
	{
		text = text.replace(/-/g, "<BR/>-");
		
		$.prompt(text, {
			focus  : 1,
			buttons: {  Ok: true, Cancel: false },
		     submit: function(v,m,f){ if (v) window.location = url }
		});
	}
}

/**
 * Confirmation box for removing document within a form
 * 
 * @param text		confirmation box text
 * @param url		url to delete document
 * 
 * @return void
 */
function document_remove_submit ( text, url )
{
	if ( text.length )
	{
		text = text.replace(/-/g, "<BR/>-");
		
		$.prompt(text, {
			 focus  : 1,
			 buttons: { Ok: true, Cancel: false },
		     submit : function(v,m,f)
		     { 
				 if (v) 
					 {
					 	document.form.action=url;
					 	document.form.submit();
					 }
		     }
		});
	}
}

/**
 * Submit Document
 * 
 * @param action	target url
 * 
 * @return void
 */
function document_submit( action )
{
	if ( typeof validate_form == 'function')
	{
		try 
		{
			var myValidator = validate_form; 
		} 
		catch(e) {}; 
		
		if (myValidator)
		{
			var result = myValidator(document.form);
			
			if ( result )
			{
				if ( action )
				{
					document.form.action = action;
				}
				
				document.form.submit();
			}
		}
	}
	else 
	{
		if ( action )
		{
			document.form.action = action;
		}
		
		document.form.submit();
	}
}

/**
 * Project Start Date Object
 */
var start = Array();

/**
 * Returns the number of days in February
 * @param year
 * @return	number of days for the given year
 */
function days_february ( year )
{
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );7
}

/**
 * Returns the number of days for each month
 * 
 * @return	array of days
 */
function days_month () 
{
	for (var i = 1; i <= 12; i++) 
	{
		this[i] = 31;
		
		if (i==4 || i==6 || i==9 || i==11) 
		{
			this[i] = 30;
		}
		
		if (i==2) 
		{
			this[i] = 29;
		}
   }
	
   return this;
}

/**
 * Validate if at least on project member was added
 * 
 * @return bool		true on valid project start and end
 */
function validate_disclaimer ( action )
{
	disclaimer = document.form.elements["BLOGIC[disclaimer]"];
	
	if ( disclaimer.checked == false )
	{
		alert('Bitte den Disclaimer akzeptieren!'); // todo translation!
		
		return false;	
	}
	
	document_submit(action);
}

/**
 * Validate if at least on project member was added
 * 
 * @return bool		true on valid project start and end
 */
function validate_members ( action )
{
	var result = get_cookie('project_members');
	
	if ( result != 'true' )
	{
		alert('Bitte Projektmitarbeiter eingeben'); // todo translation!
		
		return false;
	}
	
	document_submit(action);
}

/**
 * Validate if at least on project member was added
 * 
 * @param  cookie_name	name of cookie element
 * @return mixed		value of cookie
 */
function get_cookie ( cookie_name )
{
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	if ( results )
	{
		return ( unescape ( results[2] ) );
	}
	else
	{
		return null;
	}
}

/**
 * Validates Date
 * 
 * @param  str		empty
 * @param  date		quickform object
 * @return bool		true on valid date
 */
function validate_date ( str, date )
{
	days_in_month = days_month();
	
	if ( (date[1] == 2 && parseInt(date[0]) > days_february(date[2])) )
	{
		return false;
	}
	
	if ( parseInt(date[0]) > days_in_month[date[1]] )
	{
		return false;
	}

	if ( date[0] && !date[1] )
	{
		return false;
	}
	
	return true;
}

/**
 * Validates correct project start and project end date
 * 
 * @param  str		empty
 * @param  date		quickform object
 * @return bool		true on valid project start and end
 */
function validate_range ( str, date )
{
	if ( this.start.length == 0 ){
		this.start = date;
	}
	else {
		var result = false;
		
		if ( parseInt(this.start[2]) < parseInt(date[2] ) )
		{
			result = true;
		}
		else if ( parseInt(this.start[2]) == parseInt(date[2]) && 
				 parseInt(this.start[1]) < parseInt(date[1]) )
		{
			result = true;
		}
		else if ( parseInt(this.start[2]) == parseInt(date[2]) && 
			 parseInt(this.start[1]) == parseInt(date[1]) && 
			 parseInt(this.start[0]) < parseInt(date[0]) )
		{
			result = true;
		}
		
		this.start = Array();
		return result;
	}
	
	return true;
}

/**
 * Registering submit event for login box
 */
var Util = 
{
	addEvent: function(obj, type, fn) 
	{
		if(obj.addEventListener) {
			obj.addEventListener(type, fn, false);
		}
		else if(obj.attachEvent) {
			obj["e" + type + fn] = fn;
			obj[type+fn] = function() {
											obj["e" + type + fn]( window.event );
										 }
			obj.attachEvent("on" + type, obj[type + fn]);
		}
	},
	
	addInputSubmitEvent: function(form, input) 
	{
	  Util.addEvent( input, "keydown", function(e) {
	      var e = e || window.event;
	      if (e.keyCode == 13) {
	          form.submit();
	          return false;
	      }
	  });
	}
};


var AbstractBrowser = function() 
{
	this.init.apply( this, arguments );
};

AbstractBrowser.AGENT_FF = 1;
AbstractBrowser.AGENT_IE = 2;
AbstractBrowser.AGENT_SF = 3;
AbstractBrowser.OS_WIN = 1;
AbstractBrowser.OS_MAC = 2;

AbstractBrowser.prototype = 
{

	agent: null,
	version: null,
	os: null,

	init: function() 
	{

		this.agent = -1;
		this.version = -1;
		this.os = -1;

		if(navigator.userAgent.match(/msie/gi)) 
		{
			this.agent = AbstractBrowser.AGENT_IE;
			this.os = AbstractBrowser.OS_WIN;
			
			try 
			{
				var agt = navigator.userAgent;
				var token = agt.match(/MSIE [0-9\.]*;/gi);
				this.version = token[0].substring(5, token[0].length - 1);
			}
			catch(e) 
			{
				this.version = -1;
			}
		}
		else if(navigator.userAgent.match(/firefox/gi)) 
		{
			this.agent = AbstractBrowser.AGENT_FF;
			try 
			{
				var agt = navigator.userAgent;
				this.version = navigator.userAgent.substring(agt.indexOf("Firefox/") + 8, agt.length);
			}
			catch(e) 
			{
				this.version = -1;
			}
			if( navigator.platform.match(/Win/gi) ) 
			{
				this.os = AbstractBrowser.OS_WIN;
			}
			else if( navigator.platform.match(/Mac/gi) ) 
			{
				this.os = AbstractBrowser.OS_MAC;
			}
		}
		else if(navigator.userAgent.match(/safari/gi)) 
		{
			this.agent = AbstractBrowser.AGENT_SF;
			this.os = AbstractBrowser.OS_MAC;
			this.version = -1;
		}
	}

};

var browser = new AbstractBrowser();

autocomplete();

