debug = function(obj){
	try{
		console.log(obj);
	}
	catch(e){
		
	}
};

editAreaCssFix = function(){
	if(jQuery('.content').css('position') == 'relative')
		jQuery('.content, #main_content, #editModelpage').css('position','static');
	else
		jQuery('.content, #main_content, #editModelpage').css('position','relative');
};

setPasswordError = function() {
	if(jQuery("#signupPassword").val() == jQuery("#confirmSignupPassword").val())
	{
		jQuery("#frmSignup input:submit").removeAttr("disabled"); 
		jQuery("#passwordError").addClass("hidePasswordError")
		jQuery("#passwordError").removeClass("showPasswordError")
	}else {
		jQuery("#frmSignup input:submit").attr("disabled", "true"); 
		jQuery("#passwordError").addClass("showPasswordError")
		jQuery("#passwordError").removeClass("hidePasswordError")
	}
}

setChangePasswordError = function() {
	if(jQuery("#newPassword").val() == jQuery("#confirmPassword").val())
	{
		jQuery("#frmChangePassword input:submit").removeAttr("disabled"); 
		jQuery("#passwordError").addClass("hidePasswordError")
		jQuery("#passwordError").removeClass("showPasswordError")
	}else {
		jQuery("#frmChangePassword input:submit").attr("disabled", "true"); 
		jQuery("#passwordError").addClass("showPasswordError")
		jQuery("#passwordError").removeClass("hidePasswordError")
	}
}

function clickUserSelect(checkbox) {
	if(checkbox.checked)
	{
		var found = false;
		jQuery('#users option').each(function(i, selected){
			var id = jQuery(selected).val();
			if(id == checkbox.value)
			{
				jQuery(selected).attr("selected", true);
				found = true;
			}
		});
		
		if(!found){
			var options = jQuery("#users").html();
			options += '<option value="' + checkbox.value + '" selected="true">' + checkbox.value + '</option>'
			jQuery("#users").html(options);
		}
		
	}else {
		jQuery('#users option').each(function(i, selected){
			var id = jQuery(selected).val();
			if(id == checkbox.value)
			{
				jQuery(selected).attr("selected", false);
			}
		});
		
	}
}

var interface = {
		firstLoad: false,
		skipAnim: false,
		
		highlightSimDesciptionBlock: function(){
				jQuery('.simDisplayLayout').hover(
					function(){ jQuery(this).addClass('highlightedSim'); },
					function(){ jQuery(this).removeClass('highlightedSim'); }
				);
		},
		resizeMainContent: function(callback)
		{
			callbcack = callback || null;
			interface.resizeHandler(callback);
			jQuery(window).resize(function(){ interface.resizeHandler(); });
		},
		resizeHandler: function(callback){
			var windowHeight = jQuery(window).height(); 
			var navHeight = jQuery('#navigation').outerHeight(); 
			var newHeight = windowHeight - 75 - 10;
			jQuery('.content').css({'height':newHeight,'padding-bottom':0});
			jQuery('.run_sim .content').css({'height':parseInt(newHeight + 21),'padding-bottom':0});
			if(callback) callback();
		},
		
		callbackHandler: function(data) {
			dwr.util.setValue("main_content", data, { escapeHtml:false });
			
			var count = 20;
			
			var currentPage = parseInt(jQuery('#startIndex').attr('value'));
			var min = ((currentPage + 1)*count - (count - 1));
			var max = ((currentPage + 1)*count);
			var totalRecords = parseInt(jQuery('#totalRecords').attr('value'));
			(max > totalRecords)? max = totalRecords : max;
			var rest = (totalRecords  % count);
			
			
			(rest != 0) ? totalPages = ((totalRecords - rest) / count) + 1 : totalPages = ((totalRecords - rest) / count);
			
			
			if(jQuery('.pag_controls').length != 0){
				jQuery('.pag_controls').html('');
				
				if(min != 1) jQuery('.pag_controls').append('<a href="#" alt="' + currentPage +'">&laquo; Previous</a>');
				var maxCount = 10;
				if(totalPages > 1) 
				{	
					var maxTotalPages = totalPages > maxCount ? maxCount : totalPages;
					
					var startSearchPageIndex = 1;
					
					if(currentPage 	> maxCount/2 ) 
					{
						startSearchPageIndex = currentPage - maxCount/2;
						maxTotalPages = maxTotalPages + startSearchPageIndex;
					}
					
					for(i=startSearchPageIndex;i<=maxTotalPages;i++)
					{
						jQuery('.pag_controls').append('<a href="#" alt="'+i+'">'+i+'</a>');
					}
				}
				if(max != totalRecords) jQuery('.pag_controls').append('<a href="#" alt="'+parseInt(currentPage+2)+'">Next &raquo;</a>');
				pageControlHandler();
			}
			
			if(totalRecords > 0) interface.setPaginationUI(totalRecords,min,max,currentPage+1);
			else jQuery('.pag_index').html('');
			
			interface.highlightSimDesciptionBlock();
			
		},
		
		setPaginationUI: function(total,min,max,current){
			jQuery('.pagination').addClass('visible');
			if(total) jQuery('.totalResults_span').text(total);
			if(min) jQuery('.showingResultsMin_span').text(min);
			if(max) jQuery('.showingResultsMax_span').text(max);
			if(current) jQuery('.pag_controls a[alt='+current+']').addClass('current_page');
			else jQuery('.pag_controls a[alt=1]').addClass('current_page');
		},
		
		limitTagNumber: function(){
			var listItems = jQuery('.paginate').find('li');
			var total = listItems.size();
			interface.showMoreTags.total = listItems.size();
			if(total > 15)
			{
				interface.showMoreTags.currentPage = 1;
				jQuery('#tags.sidebar_item').find('li:lt(15)').show();
				jQuery('#tags.sidebar_item').after('<span id="tagControls"><a href="#" id="previousTags" onclick="interface.showMoreTags.prevClickHandler(); return false;">&laquo; previous</a> &nbsp; <a href="#" id="nextTags" onclick="interface.showMoreTags.nextClickHandler(); return false;">next &raquo;</a></span>');
			}
			else {
				jQuery('.paginate li').show();
			}
		},
		
		showMoreTags: {
			currentPage: 0,
			total: 0,
			nextClickHandler: function(){
				var nextPage = interface.showMoreTags.currentPage + 1;
				var max = nextPage * 15;
				var min = parseInt(((nextPage - 1) * 15) - 1);
				var nextResults = jQuery('#tags.sidebar_item').find('li:lt('+max+'):gt('+ min +')');
				
				if(nextResults.size() > 0)
				{
					interface.showMoreTags.currentPage += 1;
					jQuery('#tags.sidebar_item').find('li').hide();
					nextResults.show();
				}
				if(max >= this.total) jQuery('#nextTags').hide();
				else jQuery('#nextTags').show();
				
				if(min != -1) jQuery('#previousTags').show();
				else jQuery('#previousTags').hide();
			},
			prevClickHandler: function(){
				var nextPage = interface.showMoreTags.currentPage - 1;
				var max = nextPage * 15;
				var min = parseInt(((nextPage - 1) * 15) - 1);
				var nextResults = jQuery('#tags.sidebar_item').find('li:lt('+max+'):gt('+ min +')');
				
				if(nextResults.size() > 0)
				{
					interface.showMoreTags.currentPage -= 1;
					jQuery('#tags.sidebar_item').find('li').hide();
					nextResults.show();
				}
				if(max >= this.total) jQuery('#nextTags').hide();
				else jQuery('#nextTags').show();
				if(min != -1) jQuery('#previousTags').show();
				else jQuery('#previousTags').hide();
			}
		}
};

var newWindows = new Array();
function popups(href,targetWindow){
	if(!targetWindow) targetWindow = 'newWindow';
	targetWindow = escape(targetWindow);
	
	for (var i =0; i< newWindows.length; i++)
	{
		var newWin = newWindows[i];
		if (newWin != null && !newWin.closed && newWin.name == targetWindow) {
			newWin.close();
		}
	}
	
	var newWindow = window.open(href, targetWindow);
	if(newWindow.outerWidth < 1024 || newWindow.outerHeight < 700)
	{
		newWindow.focus();
		newWindow.resizeTo(1024,768);
	}
	newWindows.push(newWindow);
	
	if(!newWindow){
	
		alertDialog = new Dialog({title:'Popup blocker detected', cssClass:'warning',id:'popupBlocker'});
	
		if(jQuery.browser.msie){
			alertDialog.update({message:'<p>We have detected that your browser&#39;s pop-up blocker is preventing you from running the simulation. Please add this site to your list of allowed exceptions and try again.</p><br/><p><strong>Click on the options as shown below:</strong></p><br/><img src="'+Globals.imageBasePath+'/popup_instructions_ie.gif"/>',width:500, height:300});
		}
		else if(jQuery.browser.mozilla){
			alertDialog.update({message:'<p>We have detected that your browser&#39;s pop-up blocker is preventing you from running the simulation. Please add this site to your list of allowed exceptions and try again.</p><br/><p><strong>Click on the options as shown below:</strong></p><br/><img src="'+Globals.imageBasePath+'/popup_instructions_mozilla.gif"/>',width:532, height:300});
		}
		else if(jQuery.browser.safari){
			alertDialog.update({message:'<p>We have detected that your browser&#39;s pop-up blocker is preventing you from running the simulation. Please disable the Safari popup blocker and try again.</p><br/><p><strong>Go to the "Safari" menu and untick the option to block pop-ups, as shown below:</strong></p><br/><img src="'+Globals.imageBasePath+'/popup_instructions_safari.gif"/>',width:290, height:390});
		}
		else{
			alertDialog.update({message:'<p>We have detected that your browser&#39;s pop-up blocker is preventing you from running the simulation. Please disable your popup blocker and try again.</p>',width:290, height:600});
		}
		alertDialog.show();
	}	
	else newWindow.focus();
}

function logoutIfSessionInvalid() {
	KeepSessionAlive.isSessionAlive("", function(data) {
			if(!data) { 
				document.location.href = jQuery("#timeoutUrl").val();
			}
		}); 
}

var timer = {
	set: function(){
		if(jQuery("#timeoutUrl").length > 0){
			jQuery(document).everyTime("100s", "timeout", function() {
				logoutIfSessionInvalid();
			});
		}	
	},
	
	update: function(){
		jQuery(document).stopTime("timeout");
		timer.set();	
	},
	
	poll: function(){
		jQuery(document).stopTime("timeout");
		jQuery(document).everyTime("300s", "keepSessionAlive", function() { KeepSessionAlive.pollServer(); }, 0);	
	}
	
};

var preventTimeout = function(){
	timer.update();
}

var simControls = {
	addTags: function(){
		jQuery('#add_tags_form').toggle();
	},
	deleteSim: function(simPath){
		utility.post(Globals.linkBasePath+"manager/" + simPath +"/delete.html","",null,function(){ window.location.reload(true)})
	},
	setSimulationUrl: function() {
	
		jQuery(".setSimulationUrl").keyup(function(event) {
			var callbackFunction = function(data) {
				jQuery("#path").val(data);
				jQuery("#simulationUrl").text(data);
			};
			
			var errorHandlerFunction = function(message) {
				//alert("Select Proper Author : " + message);
			};
			
			SimulationPathService.getNewPath(jQuery('#name').val(), jQuery('#authorId').val(), 
					{callback: callbackFunction, errorHandler :errorHandlerFunction, async: true}
			);
			
		});
		
	},
	getEmbedTags: function(width, height, swfFilePath, url){
		return "<object width='"+width+"' height='"+height+"'><param name='movie' value='"+url+swfFilePath+"'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='"+url+swfFilePath+"' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='"+width+"' height='"+height+"'></embed></object>";
	}
}

var dropdown = {
	init: function(selectors){
		var selectorString = selectors.join();
		jQuery(selectorString).click(function(event){
			if(jQuery(event.originalTarget).attr('id') == 'mini_avatar') event.preventDefault();
			(jQuery(this).hasClass('clicked')) ? jQuery(this).data('stick',true) : jQuery(this).data('stick',false);
		});
		jQuery(selectorString).hover(
			function(){ dropdown.show(jQuery(this)); },
			function(){ dropdown.hide(); }
		);
		
		jQuery('.content').click(function(){
			jQuery(selectorString).data('stick',false);
			dropdown.hide();
		});	
		
		jQuery('.menu_item, #navLvl1 li > a, #navInsideSim li > a').click(function(event){
			if(Globals.modelEdit.changed)
			{
				var confirmation = confirm("You have made changes to your model, if you leave this page without saving, you will lose all changes")
				if(confirmation)
				{
					if(jQuery(this).find('.popup').length == 0 && jQuery(this).find('.active_link').length == 1) window.location = jQuery(this).find('.active_link a').attr('href');
				}
				else
				{
					return false;
				}
			}
			else
			{
				if(jQuery(this).find('.popup').length == 0 && jQuery(this).find('.active_link').length == 1) window.location = jQuery(this).find('.active_link a').attr('href');
			}
		});
	},
	show: function(el){
		dropdown.hide();
		el.addClass('clicked');
		el.children('.dropped_down').show();		
	},
	hide: function(){
		jQuery('.clicked').each(function(){
			if(jQuery(this).data('stick') != true)
			{
				jQuery(this).children('.dropped_down').hide();
				jQuery(this).removeClass('clicked');
			}	
		});
	}
}

var sliderLogin = {
	speed: 500,
	init: function(){
		// Esc key listener
		jQuery(document).keypress(function(event){
			if(event.keyCode == 27)
			{
				sliderLogin.hide();
				dropdown.hide();
			}
		});
		
		jQuery('#slide_control a#slideThis, #slidey_forms input:submit').click(function(event){
			if(this.nodeName == 'A') { event.preventDefault(); }
			sliderLogin.toggle();
		});	
		
	},
	
	show: function(){
		jQuery('#slide_login').animate({ top: '0' }, this.speed );
		jQuery('#slideThis').text('Close panel');
		var iconURL = jQuery('#panelIcon').attr('src').substr(0,jQuery('#panelIcon').attr('src').lastIndexOf('/')+1);
		var newIconURL = iconURL+'close_panel.gif';
		jQuery('#panelIcon').attr('src',newIconURL);
		var login = jQuery('#StxtUserName').val();
		if(login != '') jQuery('#txtPassword').focus();
		else jQuery('#StxtFirstNames').focus();
	},
	
	hide: function(){
		jQuery('#slide_login').animate({ top: '-360px' }, this.speed ) ;
		jQuery('#slideThis').text('Login or Register');
		var iconURL = jQuery('#panelIcon').attr('src').substr(0,jQuery('#panelIcon').attr('src').lastIndexOf('/')+1);
		var newIconURL = iconURL+'contact-new.gif';
		jQuery('#panelIcon').attr('src',newIconURL);
	},
	
	toggle: function(){
		if(jQuery('#slide_login').css('top') == "-360px")
		{
			this.show();
		}
		else
		{
			this.hide();
		}
	}
};

var editable = {
	selector:'',
	id:'',
	set: function(selector,id){
		this.selector = selector;
		this.id = parseInt(id);
		id = parseInt(id);
		jQuery(selector).addClass('editable');
		jQuery(selector).hover(
			function(){ jQuery(this).addClass('hover'); },
			function(){ jQuery(this).removeClass('hover'); }
		);
		jQuery(selector).click(function(){
				jQuery(this).removeClass('editable');
				jQuery(this).removeClass('hover');
				jQuery(this).data('bound',false);
				var width = jQuery(this).width() - 5;
				var height = jQuery(this).height();
				(height < 100) ? height = 100 : height = height;
				var textarea ='';
				textarea += '<form id="enter_description_form" action="'+Globals.linkBasePath+'/simulations/editDescription.html" method="post">';
				textarea += '<input type="hidden" name="id" value="'+id+'" />';
				textarea += '<textarea name="description" id="enter_description" style="margin: 0; padding: 0; height: '+height+'px; width: '+width+'px;">';
				textarea += jQuery("#description_text input").val();
				textarea += '</textarea>';
				textarea += '<div style="text-align:right;"><input type="submit" value="Submit Changes" /> &nbsp; <input type="button" value="Cancel" onclick="editable.cancel(); return false;" /></div>';
				textarea += '</form>';
				jQuery(this).after(textarea);
				jQuery(this).hide();
				jQuery('#enter_description').focus();
		});
		jQuery(selector).data('bound',true);	
	},
	cancel: function(){
		jQuery(this.selector).addClass('editable');
		jQuery(this.selector).show();
		jQuery('#enter_description_form').hide();	
	}
};

function setPopupBehavior(){
	jQuery('.popup').click(function(event){
		popups(jQuery(this).attr('href'), jQuery(this).attr('rel'))
		event.preventDefault();
	});
}

function changeParentUrl(url)
{
	document.location=url;
}

jQuery(document).ready(function(){

	// Init Application
	sliderLogin.init();
	timer.set();
	dropdown.init(['#userMenu', '#navLvl1 ol li', '#navInsideSim ol li']);
	interface.limitTagNumber();
	interface.highlightSimDesciptionBlock();
		
	jQuery("#forioEquations").each(function() {
		timer.poll();
	});
	jQuery("#designerBox").each(function() {
		timer.poll();
	});
	

	
	jQuery(".closeWindow").click(function(){
		window.close();
	});
	
	jQuery(".webflowDisable").click(function(){
		jQuery("#webFlowEvent").attr("name", jQuery(this).attr("name"));
		jQuery("#webFlowEvent").attr("value", jQuery(this).attr("value"));
		jQuery(this).attr("disabled", "true");
		jQuery("#webFlowEvent").click();
	});
	
	jQuery("#deleteModel").click(function() {
		var result = confirm("Are you sure?");
	    if (result) jQuery('#deleteModelForm').submit();
			else return false;
	});
	
	jQuery("#partialReviewLink").click(function(event){
		jQuery("#_eventId_partialReview").click();
	});
	
	jQuery("#confirmSignupPassword").keyup(function(event){
		setPasswordError();
	});
	
	jQuery("#signupPassword").keyup(function(event){
		setPasswordError();
	});
	
	jQuery("#confirmPassword").keyup(function(event){
		setChangePasswordError();
	});
	jQuery("#newPassword").keyup(function(event){
		setChangePasswordError();
	});
	
	jQuery(".autoUploadFile").change(function() {
		this.form._eventId_submit.click();
	});
	
});

jQuery(window).resize(function(){
	jQuery('#designerObject').css('width',jQuery('#main_content').outerWidth());
	jQuery('#designerObject').css('height',jQuery('#main_content').height());
});