function makeFieldItemSortable() {
	$('div.fieldsWrapper').Sortable( {
		accept: 'fieldItem',
		helperclass: 'sortHelper',
		activeclass : 	'sortableactive',
		hoverclass : 	'sortablehover',
		handle: 'div.itemHeader',
		tolerance: 'pointer',
		onChange : function(ser){ },
		onStart : function(){ $.iAutoscroller.start(this, document.getElementsByTagName('body')); },
		onStop : function(){ $.iAutoscroller.stop(); }
	});
}
// Ajax session keep-alive
function ping() {
	$.get("/settings/ping", null, function() {
		// console.log('pingd');
	});
}

function newExcitingAlerts() {
    var oldTitle = document.title;
    var msg = "Incoming chat request";
    var timeoutId = setInterval(function() {
        document.title = document.title == msg ? oldTitle : msg;
    }, 1000);
	window.onmousemove = function() {
        clearInterval(timeoutId);
        document.title = oldTitle;
        window.onmousemove = null;
    };
}


function checkChatRequest() {
	$.get("/meeting/x/chat/monitor", null, function(response) {
		
		if (response.match("Incoming")) {
			window.focus();
			var chatId = $("#chatId").text();
			var chatattendeeId = $("#chatattendeeId").text();
			/*if(confirm($('#chat-request').html())){
				window.open('/meeting/chat/'+ chatId,'popup','height=600,width=800');
			}else{
				$('#chat-request').load('/meeting/x/chat/reject/'+ chatattendeeId);
			}*/
			newExcitingAlerts()
			$('body').append(response);
		}

	});
}

var popup = 1;

function chatStart(form){
	popup += 1;
	$(form).attr('target', 'popup'+popup);
}

$(function() {
	$('.showPanel').click(function(){
		$(this).parent('.itemHeader').next('.itemContent').toggle();
		$(this).hide();
		return false;
	});
	
	$('.menuToggle').click(function(){
		$('.admin_menu').toggle();
		$(this).toggleClass('showMenu');
		if($(this).is('.showMenu')){
			var state = "hidden";
		}else{
			var state = "visible";
		}
		$.get("/settings/setmenu/" + state, null, function() {
			// console.log('pingd');
		});
		return false;
	});
	
	$('.dashboardHelp').click(function() {
		$('#dashboardHelp').toggle(400);
	});
	
	$('.closeHelp').click(function() {
		$('#dashboardHelp').toggle(400);
	});
	
	if( $("#noMonitor").length == 0 || $("#noMonitor").val() != '1' )
	{
		checkChatRequest();
		setInterval(checkChatRequest, 20000);
		ping();
		setInterval(ping, 20000);
	}
	
	$(".chatAccept").live('click', function(){
		popup += 1;
		$('#chat-request').remove();
		window.open('/meeting/chat/'+ $(this).attr('rel'),popup,'height=600,width=800');
		return false;
	});
	
	$(".chatDeny").live('click', function(){
		$('#chat-request').hide();
		$('#chat-request').load('/meeting/x/chat/reject/'+ $(this).attr('rel'));
		return false;
	});
	
	$('.meeting-start').live('click', function(){
		popup += 1;
		$('#meeting-panel form').attr('target', 'popup'+popup);
	});
	
	// initiate tooltips
	$('.tooltip').livequery( function(){
		$(this).tooltip({track: true,delay: 0,showURL: false, showBody: " ~ "});
	});
	
	// ONA topic submit
	$('.submit-topic, #topic-submit .cancel').live('click', function(){
		$('#topic-submit').slideToggle();
		$('.listing-title').toggle();
		return false;
	});
	
	// 
	$('#SearchWorkshop').change(function(){
		if($(this).val() == -2){
			var pSel = $(this);
			var errorMsg = pSel.attr('rel');
			alert(errorMsg);
			pSel.children('option:first').attr('selected', 'selected');
		}
	});
	/*$(".disabledOption").live('click', function(){
		var pSel = $(this).parent('select');
		var errorMsg = pSel.attr('rel');
		alert(errorMsg);
		pSel.children('option').not('.disabledOption').eq(0).attr('selected', 'selected');
	});*/


	$('.level-option input').livequery(function() {
		$(this).example(function() {
			if($(this).val() == ''){
				return $(this).attr('title');
			}
		}, {className: 'default-value'});
	});
	
	$("#AppSelectedCompany").change(function() {
		$("#currentCompanyForm").submit();
	});
			
	$(".table-list tr:even").addClass('odd');
	// $('#tabs-container > ul').tabs({ fx: { opacity: 'toggle' } });
	$('textarea.resizable:not(.processed)').TextAreaResizer();
		
	$('div.groupWrapper').Sortable(
			{
				accept: 'groupItem',
				helperclass: 'sortHelper',
				activeclass : 	'sortableactive',
				hoverclass : 	'sortablehover',
				handle: 'div.itemHeader',
				tolerance: 'pointer',
				onChange : function(ser){
				},
				onStart : function(){
					$.iAutoscroller.start(this, document.getElementsByTagName('body'));
				},
				onStop : function(){
					$.iAutoscroller.stop();
				}
			}
		);
		
	makeFieldItemSortable();

	$('div#enquiry-sections').Sortable(
			{
				accept: 'enquiry-section',
				helperclass: 'sortHelper',
				activeclass : 	'sortableactive',
				hoverclass : 	'sortablehover',
				handle: 'div.section-title',
				tolerance: 'pointer',
				onChange : function(ser){
				},
				onStart : function(){
					$.iAutoscroller.start(this, document.getElementsByTagName('body'));
				},
				onStop : function(){
					$.iAutoscroller.stop();
				}
			}
		);
		
	$('div#enquiry-questions').Sortable(
			{
				accept: 'enquiry-element',
				helperclass: 'sortHelper',
				activeclass : 	'sortableactive',
				hoverclass : 	'sortablehover',
				handle: 'div.question-title',
				tolerance: 'pointer',
				onChange : function(ser){
				},
				onStart : function(){
					$.iAutoscroller.start(this, document.getElementsByTagName('body'));
				},
				onStop : function(){
					$.iAutoscroller.stop();
				}
			}
		);
		
	$('label#partner').click(function() {
	    $(this).html($(this).html() == 'Not Partners' ? 'Partners' : 'Not Partners');
	    return false;
	});

	$('.toggle').click(function() {
		var div = $(this).attr('title');
		$(this).toggleClass("hide");
		$('#'+div).toggle(400);
		return false;
	});
	
	$('.linkDisabled a').click(function() {
		return false;
	});
	
	$('.disabledLink').click(function() {
		return false;
	});
});
	
var lastDiv = "";
function showDiv(divName) {
	if (!lastDiv){
		lastDiv = "agent";
	}
	// hide last div
	testString = "country, course-level";
	testString2 = "country, course-level";
	if (lastDiv && testString.indexOf(divName) == -1 && testString2.indexOf(divName) == -1) {
		document.getElementById(lastDiv).className = "hiddenDiv";
	}
	//if value of the box is not nothing and an object with that name exists, then change the class
	if (divName && document.getElementById(divName)) {
		document.getElementById(divName).className = "visibleDiv";
		lastDiv = divName;
		
		if (divName == "agent"){
			types = "Agencies";
			type = "Agency name";
			countryType = "Agencies with offices";
			//staff = "Agent";
			tableLocation = "Agency location/s";
		}else if (divName == "provider"){
			types = "Service providers";
			type = "Service provider name";
			countryType = "Service providers offering services";
			//staff = "Staff";
			tableLocation = "Service location/s";
		}else if (divName == "educator"){
			types = "Educators";
			type = "Educator name";
			countryType = "Educators with campuses";
			//staff = "Staff";
			tableLocation = "Campus location/s";
		}
		document.getElementById('country-type').innerHTML = countryType;
		document.getElementById('status-type').innerHTML = types;
		document.getElementById('city-type').innerHTML = countryType;
		document.getElementById('table-type').innerHTML = type;
		//document.getElementById('staff').innerHTML = staff;
		document.getElementById('location').innerHTML = tableLocation;
	}
	if (divName == "country"){
		document.getElementById('city').className = "visibleDiv";
	}
	if (divName == "level"){
		document.getElementById('course-level').className = "form-element select visibleDiv";
	}
	if (divName == "provider"){
		document.getElementById('city').className = "hiddenDiv";
	}
}

status = "none";
function showDiv2(divName) {
	if (status == "visible"){
		document.getElementById(divName).className = "hiddenDiv";
		document.getElementById("advanced-link").className = "show";
		status = "hidden";
	}
	
	else if (divName == "advanced") {
		document.getElementById(divName).className = "visibleDiv";
		document.getElementById("advanced-link").className = "hide";
		status = "visible";
	}
}

function showThread(divName) {
	if ($('#'+divName).is(":hidden")){
		$('#'+divName).slideDown("slow");
	}else{
		$('#'+divName).slideUp("slow");
	}
}

function show(divName) {
	if ($('#'+divName).is(":hidden")){
		$('#'+divName).show("slow");
	}
}

function hide(divName) {
	if (divName && document.getElementById(divName)){
		$('#'+lastDiv).hide("slow");
	}
	return false;
}

function showHide(divName) {
	if (lastDiv && $('#'+lastDiv).is(":hidden")){
		lastDiv = "";
	}else if (lastDiv && lastDiv != divName){
		$('#'+lastDiv).slideUp("fast");
	}
	if (divName && document.getElementById(divName) && lastDiv != divName){
		$('#'+divName).slideDown("slow");
		lastDiv = divName;
	}
}

function setClass(target){
	var targetDiv = target.parentNode.parentNode;
   
    if(targetDiv.nodeName.toLowerCase() != 'div'){
		return;
	}
        
	if(target.checked === true){
		targetDiv.className = 'selected';
	}
	else{
		targetDiv.className = 'unselected';
	}
}

function AddToFavourites(id) {
	$("#favourites-list").append("<tr id='fav-" + id + "'>" + $("#"+id).html() + "</tr>");
	$("tr#fav-"+id).children('td.'+id).html("<a href='javascript: removeFavourite(\"fav-" + id + "\");'><img src='img/delete.png'></a>");
	$("#none").remove();
}

function removeFavourite(id) {
	$("#"+id).remove();
}

function killPopup() {
	setTimeout(function() {
		tb_remove();
	}, 3000);
}

// Marvel static functions
var Marvel = {
	// Html helper
	htmlHelper:{
		_vars:{
			loadingImage:'loading.gif',
			loadingImageBig:'loading.gif',
			loadingImageSmall:'loadingSmall.gif'
		},

		fadeReplace:function (source, target) {
			$(target).fadeOut(400);
			setTimeout(function () {
				$(target).html($(source).html());
				$(target).fadeIn(400);
			}, 450);
		},

		slideHide:function (target) {
			$(target).slideUp(800);
			setTimeout(function() { $(target).empty(); }, 900);
		},

		showLoading:function (target) {
			Marvel.htmlHelper.showCustomLoading(target, 'center', Marvel.htmlHelper._vars.loadingImageBig);
		},

		showCustomLoading:function (target, align, image) {
			if (!$(target).html().match(/loading/i)){
				$(target).html('<div id="loadingdiv" style="text-align:' + align + '"><img src="/img/' + image + '" alt="" /></div>');
			}
		}

	},

	// Page messaging via flash functionality
	message:{
		settings:{
			slideTime:900,
			displayTime:3000
		},

		flash:function (message) {
			// Make sure message is not empty
			message = $.trim(message);
			if (!message){
				return;
			}

			// Attach message
			if ($('#flash').html()) {
				$('#flash').append("<br>" + message);
			} else {
				$('#flashPoint').html('<div class="flash" id="flash">' + message + '</div>');
			}

			// Show
			if (!Marvel.message.isFlashing) {
				$('#flashPoint').hide();
				$('#flashPoint').slideDown(Marvel.message.settings.slideTime);
				Marvel.message.isFlashing = setTimeout(Marvel.message.hide, Marvel.message.settings.displayTime);
			} else {
				clearTimeout(Marvel.message.isFlashing);
				Marvel.message.isFlashing = setTimeout(Marvel.message.hide, Marvel.message.settings.displayTime);
			}
		},

		hide:function () {
			$('#flashPoint').slideUp(Marvel.message.settings.slideTime);
			setTimeout(Marvel.message.clear, Marvel.message.settings.slideTime + 5);
			Marvel.message.isFlashing = false;
		},

		clear:function() {
			$('#flashPoint').empty();
		}
	},

	// Php clones (http://kevin.vanzonneveld.net/code/php_equivalents/php.js)
	php:{
		empty:function(mixed_var) {
			var key;
			
			if (mixed_var === ""
				|| mixed_var === 0
				|| mixed_var === "0"
				|| mixed_var === null
				|| mixed_var === false
				|| mixed_var === undefined
			){
				return true;
			}
			if (typeof mixed_var == 'object') {
				for (key in mixed_var) {
					if (typeof mixed_var[key] !== 'function' ) {
						return false;
					}
				}
				return true;
			}
			return false;
		}
	}
};
