$.fn.tinymce = function(options) {
    return this.each(function() {
        preString = "<";
	preString += "div class='jqHTML_frame' style='width:"+$(this).css("width")+"px;height:" + ($(this).css("height")+20) + "px;'>";
        postString = "<";
	postString += "/div>";
        $(this).wrap(preString + postString);
        tinyMCE.addMCEControl(document.getElementById(this.id), this.id);
    });
}

function maps()
{
	if(GBrowserIsCompatible())
	{
		// Conf Map
		mapdiv = document.getElementById("confmap");
		if(!mapdiv)
		{
			return;
		}

		map = new GMap2(mapdiv);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		
		var point = new GLatLng(39.76575, -86.16179)
		map.setCenter(point, 14);
		var marker = new GMarker(point);
		map.addOverlay(marker);
		var textInfo = "<span class=\"mapAdd\"><b>Indianapolis Convention Center<\/b><br \/>100 S. Capitol Ave.<br \/>Indianapolis, IN 46225<br \/>";
		map.openInfoWindowHtml(point, textInfo);
	}
}

function fileBrowserCallBack(field_name, url, type, win) {
	var connector = "/js/tiny_mce/filemanager/browser.html?Connector=connectors/php/connector.php";
	var enableAutoTypeSelection = true;
	
	var cType;
	tinyfck_field = field_name;
	tinyfck = win;
	
	switch (type) {
		case "image":
			cType = "Image";
			break;
		case "flash":
			cType = "Flash";
			break;
		case "file":
			cType = "File";
			break;
	}
	
	if (enableAutoTypeSelection && cType) {
		connector += "&Type=" + cType;
	}
	
	window.open(connector, "tinyfck", "modal,width=600,height=400");
}

function initMCE()
{
	tinyMCE.init({ mode : "none",
			file_browser_callback : "fileBrowserCallBack",
			theme : "advanced",
			plugins : "advlink,visualchars,table,style,save,preview,contextmenu,autosave,advimage,paste,xhtmlxtras",
			theme_advanced_buttons1 : "save,separator,cut,copy,pastetext,pasteword,selectall,separator,bold,italic,underline,styleprops,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo",
			theme_advanced_buttons2 : "tablecontrols,separator,link,unlink,image,hr,charmap",
			theme_advanced_buttons3 : "formatselect,separator,visualaid,visualchars,removeformat,cleanup,help,separator,code,preview",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "center",
			theme_advanced_path_location : "bottom",
			extended_valid_elements : "form[action|method|enctype],input[type|name|value],a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],div[name|id|style]",
			content_css : "/css/dynamic.css",
			save_enabledwhendirty : true,
			plugin_preview_width :  800,
			plugin_preview_height :  600,
			plugin_preview_pageurl :  "../../../../templates/default.html",
			remove_script_host :  false,
			relative_urls : false
	});


}
initMCE();

/*
function ajaxfilemanager(field_name, url, type, win)
{
	var ajaxfilemanagerurl = "/js/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php";

	switch (type) {
		case "image":
			ajaxfilemanagerurl += "?type=img";
			break;
		case "media":
			ajaxfilemanagerurl += "?type=media";
			break;
		case "flash": //for older versions of tinymce
			ajaxfilemanagerurl += "?type=media";
			break;
		case "file":
			ajaxfilemanagerurl += "?type=files";
			break;
		default:
			return false;
	}

	var fileBrowserWindow = new Array();
	fileBrowserWindow["file"] = ajaxfilemanagerurl;
	fileBrowserWindow["title"] = "File Manager";
	fileBrowserWindow["width"] = "782";
	fileBrowserWindow["height"] = "440";
	fileBrowserWindow["close_previous"] = "no";
	tinyMCE.openWindow(fileBrowserWindow, {
	  window : win,
	  input : field_name,
	  resizable : "yes",
	  inline : "yes",
	  editor_id : tinyMCE.getWindowArg("editor_id")
	});
	
	return false;
}
*/

function clearfilters()
{
	$(":text,:password,:radio,:checkbox,:file").val("");
	$("tr.filter").remove();
}

function cleardisplayfields()
{
	$("tr.displayfield").remove();
}

function rotateSponsors()
{
	$.getJSON("/sponsors/json", function(sponsor){
		$('#sponsor_image').fadeOut('slow', function(){
			$('div.side_sponsor').animate({height: sponsor.height}, 'slow', function(){
				$('#sponsor_image').attr("src", sponsor.logo);
				$('#sponsor_image').attr("alt", sponsor.name);

				$('#sponsor_link').attr("href", sponsor.url);
				$('#sponsor_link').attr("title", sponsor.name);
				$('#sponsor_image').fadeIn('slow');
			});
		});
	});
}

var fields = null;

function loadQuery()
{
	var id = $("#query").val();
	if(id.length == 0)
	{
		return;
	}
	$.get("/queries/load/" + id, function(query){
		window.location = "http://www.ihif.org/companies" + query;
	});
}

function saveQuery(query)
{
	var name = prompt("Name of Query:");
	$.get("/queries/save/" + name + "/" + query);
	window.location.reload();
}

function deleteQuery()
{
	var id = $("#query").val();
	if(id.length == 0)
	{
		return;
	}
	
	if(confirm("Are you sure?"))
	{
		$.get("/queries/delete/" + id, function(){
			window.location.reload();
		});
	}
}

function updatesubsector(sector, subsector)
{
	if(!sector || !subsector)
	{
		return;
	}

	var sector_id = $(sector).val();
	$.getJSON("/companies/subsectors/" + sector_id, function(json){
		var code = '';
		for(subsector_id in json)
		{
			var name = json[subsector_id];
			code += "<option value=\"" + subsector_id + "\">" + json[subsector_id] + "</option>";
		}
		$(subsector).html(code);
	});
}

function updatefilter(obj)
{
	var id = $(obj).attr('id');
	var field_id = $(obj).val();
	id.match(/filter(\d*)name/);
	var count = RegExp['$1'];
	var field = fields[field_id];
	var type = field.type;
	var code;

	if(field_id == "Classification.sector_id")
	{
		code = '<select style="vertical-align: top; margin-left: 4px; margin-right: 4px;" name="filter[' + count + '][value]" id="sector" onchange="updatesubsector(this, document.getElementById(\'subsector\'));">';
		$.getJSON("/companies/sectors", function(json){
			for(sector_id in json)
			{
				var name = json[sector_id];
				code += "<option value=\"" + sector_id + "\">" + name + "</option>";
			}
			code += '</select>';
			code += '<button type="button" style="vertical-align: top; margin-left: 4px" onclick="removefilter(' + count + ');">Remove</button>';
			$("#filter" + count + "cell").html(code);
		});
	}
	else if(field_id == "Classification.subsector_id")
	{
		code = '<select style="vertical-align: top; margin-left: 4px; margin-right: 4px;" name="filter[' + count + '][value]" id="subsector" onchange="updatesubsector(document.getElementById(\'sector\', this));">';
		$.getJSON("/companies/subsectors", function(json){
			for(subsector_id in json)
			{
				var name = json[subsector_id];
				code += "<option value=\"" + subsector_id + "\">" + name + "</option>";
			}
			code += '</select>';
			code += '<button type="button" style="vertical-align: top; margin-left: 4px" onclick="removefilter(' + count + ');">Remove</button>';
			$("#filter" + count + "cell").html(code);
		});
	}
	else if(field_id == "Company.core_function_id")
	{
		code = '<select style="vertical-align: top; margin-left: 4px; margin-right: 4px;" name="filter[' + count + '][value]">';
		$.getJSON("/companies/corefunctions", function(json){
			for(corefunction_id in json)
			{
				var name = json[corefunction_id];
				code += "<option value=\"" + corefunction_id + "\">" + name + "</option>";
			}
			code += '</select>';
			code += '<button type="button" style="vertical-align: top; margin-left: 4px" onclick="removefilter(' + count + ');">Remove</button>';
			$("#filter" + count + "cell").html(code);
		});
	}
	else if(type == "phone")
	{
		code = '<input style="vertical-align: top; margin-left: 4px;" name="filter[' + count + '][value]" type="text" class="phone" />';
	}
	else if(type == "datetime")
	{
		code  = '<select style="vertical-align: top; margin-left: 4px; margin-right: 4px;" name="filter[' + count + '][quantity]">';
		code += '<option value="&lt;">&lt;</option>';
		code += '<option value="&#61;&lt;">&#61;&lt;</option>';
		code += '<option value="&#61;" selected="selected">&#61;</option>';
		code += '<option value="&gt;&#61;">&gt;&#61;</option>';
		code += '<option value="&gt;">&gt;</option>';
		code += '</select>';	
		code += '<input style="vertical-align: top;" name="filter[' + count + '][value]" type="text" class="date" />';
	}
	else if(type == "yesno")
	{
		code = '<select style="vertical-align: top; margin-left: 4px;" name="filter[' + count + '][value]">';
		code += '<option value="0">No</option>';
		code += '<option value="1">Yes</option>';
		code += '</select>';
	}
	else if(type == "integer" || type == "float")
	{
		code  = '<select style="vertical-align: top; margin-left: 4px; margin-right: 4px;" name="filter[' + count + '][quantity]">';
		code += '<option value="&lt;">&lt;</option>';
		code += '<option value="&#61;&lt;">&#61;&lt;</option>';
		code += '<option value="&#61;" selected="selected">&#61;</option>';
		code += '<option value="&gt;&#61;">&gt;&#61;</option>';
		code += '<option value="&gt;">&gt;</option>';
		code += '</select>';	
		code += '<input style="vertical-align: top;" name="filter[' + count + '][value]" type="text" />';
	}
	else
	{
		code = '<input style="vertical-align: top; margin-left: 4px;" name="filter[' + count + '][value]" type="text" />';
	}

	code += '<button type="button" style="vertical-align: top; margin-left: 4px" onclick="removefilter(' + count + ');">Remove</button>';

	$("#filter" + count + "cell").html(code);
}

function removetable(type, count)
{
	$('#' + type + '_' + count).remove();
}

function removefilter(count)
{
	$('#filter' + count + 'row').remove();
}

function addfilter()
{
	var count = new Date().getTime();
	$("#filters").append('<tr class="filter" id="filter' + count + 'row"><td style="vertical-align: top;"><select name="filter[' + count + '][name]" class="filter" id="filter' + count + 'name" style="vertical-align: top;" onchange="updatefilter(this);"></select></td><td style="vertical-align: top;" id="filter' + count + 'cell"></td>');

	var options = "";
	for(field_id in fields)
	{
		var field = fields[field_id];
		options += '<option value="' + field_id + '">' + field.name + '</option>';
	}
	$("#filter" + count + "name").html(options);
	$("option:first", "#filter" + count + "name").attr("selected", "selected");

	var obj = document.getElementById('filter' + count + 'name');
	updatefilter(obj);

	$("#filter" + count + "name").css("width", "300px");
}

function removedisplayfield(count)
{
	$('#displayfield' + count + 'row').remove();
}

function adddisplayfield()
{
	var count = new Date().getTime();
	$("#displayfields").append('<tr class="displayfield" id="displayfield' + count + 'row"><td style="vertical-align: top;"><select name="displayfield[' + count + '][name]" class="displayfield" id="displayfield' + count + 'name" style="vertical-align: top;"></select><button type="button" style="vertical-align: top; margin-left: 4px;" onclick="removedisplayfield(' + count + ');">Remove</button></td></tr>');

	var options = "";
	for(field_id in fields)
	{
		var field = fields[field_id];
		options += '<option value="' + field_id + '">' + field.name + '</option>';
	}
	$("#displayfield" + count + "name").html(options);
	$("option:first", "#displayfield" + count + "name").attr("selected", "selected");
	$("#displayfield" + count + "name").css("width", "300px");
}

function delete_session(session_id)
{
	$("#session" + session_id).remove();
}

function promocode_type(obj)
{
	var id = $(obj).attr("id");
	var type = $(obj).val();

	id = id.replace(/pat/, '');

	alert(id + ":" + type);

	if(type == "session")
	{
		$.getJSON("/admin/admin/json_sessions/" + id, function(json){
			var html = '<select name="data[EventPromocodeAssignment][' + id + '][data]">';

			for(var session_id in json)
			{
				var session = json[session_id];
				html += '<option value="' + session_id + '">' + session + '</option>';
			}
				
			$('#pad' + id).html(html);
		});
	}
	else if(type == "discount_percent")
	{
		var html = '<input type="text" name="data[EventPromocodeAssignment][' + id + '][data]" size="10" />%';
		$('#pad' + id).html(html);
	}
	else if(type == "discount_amount")
	{
		var html = '$<input type="text" name="data[EventPromocodeAssignment][' + id + '][data]" size="10" />';
		$('#pad' + id).html(html);
	}
}

$(document).ready(function(){
	$('body').minmax();
	$('#mainBorder').minmax();
	$('#footer').minmax();
	$('#maintxt').minmax();

	$('#ContentContent').tinymce();

	$('input.phone').mask("(999) 999-9999", {placeholder:" "});
	$('input.date').mask("99/99/9999 99:99");

	$.getJSON("/companies/fields", function(json){
		fields = json;
	});

	rotateSponsors();
	window.setInterval("rotateSponsors()", 10000);

	$('button.company').click(function(){
		var fieldset = $(this).parent();
		var id = $(fieldset).attr('id');
		var count = new Date().getTime();

		if(id == 'classification')
		{
			$.getJSON('/companies/sectors', function(json){
				var sectors = '<select name="data[Classification][' + count + '][sector_id]" id="sector' + count + '" onchange="updatesubsector(this, document.getElementById(\'subsector' + count + '\'));">';
				for(sector_id in json)
				{
					var name = json[sector_id];
					sectors += "<option value=\"" + sector_id + "\">" + name + "</option>";
				}
				sectors += '</select>';
				
				$.getJSON('/companies/subsectors/1', function(json){
					var subsectors = '<select name="data[Classification][' + count + '][subsector_id]" id="subsector' + count + '">';
					for(subsector_id in json)
					{
						var name = json[subsector_id];
						subsectors += "<option value=\"" + subsector_id + "\">" + name + "</option>";
					}
					subsectors += '</select>';

					var html = '<tr class="classification_row" id="classification_' + count + '">';
					html += '<td>' + sectors + '</td><td>' + subsectors + '</td>';
					html += '<td><button type="button" onclick="removetable(\'classification\', \'' + count + '\');">Remove</button></td>';
					html += '</tr>';
					$('tbody', fieldset).append(html);
				});
			});
		}
		else if(id == 'contact')
		{

			var html = '<tr class="contact_row" id="contact_' + count + '">';
			for(field_id in fields)
			{
				if(field_id.match("Contact\.(.*)"))
				{
					var id = RegExp.$1;
					var field = fields[field_id];
					html += '<td>';
					if(field.type == "yesno")
					{
						html += '<select name="data[Contact][' + count + '][main_contact]">';
						html += '<option value="0">No</option>';
						html += '<option value="1">Yes</option>';
						html += '</select>';
					}
					else
					{
						html += '<input type="text" name="data[Contact][' + count + '][' + id + ']" style="width: 100%;" />';
					}
					html += '</td>';
				}
			}
			html += '<td><button type="button" onclick="removetable(\'contact\', \'' + count + '\');">Remove</button></td>';
			html += '</tr>';
			$('tbody', fieldset).append(html);
		}
		else if(id == 'membership')
		{
			var html = '<tr class="membership_row" id="membership_' + count + '">';
			html += '<td><input type="text" name="data[Membership][' + count + '][year]" style="width: 50px;" /></td>';
			html += '<td><input type="text" name="data[Membership][' + count + '][amount_due]" style="width: 100px;" /></td>';
			html += '<td>';
			html += '<select name="data[Membership][' + count + '][renewal_invoice_sent]">';
			html += '<option value="0">No</option>';
			html += '<option value="1">Yes</option>';
			html += '</select>';
			html += '</td>';

			html += '<td><input type="text" name="data[Membership][' + count + '][payment_received]" style="width: 100px;" /></td>';
			html += '<td>';
			html += '<select name="data[Membership][' + count + '][thankyou]">';
			html += '<option value="0">No</option>';
			html += '<option value="1">Yes</option>';
			html += '</select>';
			html += '</td>';
			html += '<td><button type="button" onclick="removetable(\'membership\', \'' + count + '\');">Remove</button></td>';
			html += '</tr>';
			$('tbody', fieldset).append(html);
		}
		else if(id == 'note')
		{
			var html = '<tr class="note_row" id="note_' + count + '">';
			html += '<td style="width: 100%;"><input type="text" name="data[Note][' + count + '][note]" style="width: 100%;" /></td>';
			html += '<td><button type="button" onclick="removetable(\'note\', \'' + count + '\');">Remove</button></td>';
			html += '</tr>';
			$('tbody', fieldset).append(html);
		}
	});
	$("#EventPromocodeType").change(function(){
		var id = $(this).val();
		$(".promosection").each(function(){
			$(this).hide();
		});
		$("#" + id).show();
	});
	$("#EventRegistrantTypeId").change(function(){
		var id = $(this).val();
		$(".event_session").each(function(){
			$(this).remove();
		});

		$.getJSON("/conference/json_sessions/" + id, function(json){
			html = "";
			for(var id in json)
			{
				html += "<tr class=\"event_session\"><td colspan=\"2\">";
				html += "<input id=\"event" + id + "\" class=\"attend required\" type=\"checkbox\" value=\"" + id + "\" name=\"data[EventRegistrant][attend][]\" />";
				html += "<label id=\"event" + id + "_name\" for=\"event" + id + "\">" + json[id] + "</label>";
				html += "</td></tr>";
			}
			$("#RegisterSubmit").before(html);
		});
	});
	/**
	* Add Field Row on Add Session Title
	*/	
	$("#add_session_field").click(function(){
		var html = '<tr>';
		html += '<td style="width: 150px;">';
                html += '<input type="text" size="30" name="data[EventSession][]" />';
                html += '</td>';
		html += '</tr>';
		
		$("#SessionAddField").append(html);
	});

	/**
	* Add Field Row on Add Type name
	*/	
	$("#add_type_field").click(function(){
		var count = new Date().getTime();
		var html = '<tr>';
		html += '<td style="width: 150px;">';
                html += '<input type="text" size="30" name="data[EventRegistrationType][]" />';
                html += '</td>';
		html += '</tr>';
		
		$("#TypeAddField").append(html);
	});

	/**
	* Add Promocode Assignment Row
	*/
	$(".promocode_assignment").click(function(){
		var id = $(this).attr("id");
		id = id.replace(/pa/, '');

		var count = new Date().getTime();
		
		var html = '<tr>';
		html += '<td><input type="text" name="data[EventPromocodeAssignment][' + id + '][' + count + '][quantity]" size="3" /></td>';
		html += '<td>';
		html += '<select name="data[EventPromocodeAssignment][' + id + '][' + count + '][type]" onchange="promocode_type(this);" id="pat' + id + '">';
		html += '<option value=""></option>';
		html += '<option value="session">Session</option>';
		html += '<option value="discount_percent">Discount (Percent)</option>';
		html += '<option value="discount_amount">Discount (Amount)</option>';
		html += '</select>';
		html += '</td>';
		html += '<td id="pad' + id + '">&nbsp;</td>';
		html += '<td><input type="checkbox" name="data[EventPromocodeAssignment][' + id + '][' + count + '][unlimited]" /></td>';
		html += '</tr>';
		
		$("#parow" + id).after(html);
	});
});
