function MoveSideBar(el) {
	if(el.innerHTML.indexOf('ui-icon-arrowstop-1-e') > 1) {
		el.innerHTML = el.innerHTML.replace('ui-icon-arrowstop-1-e', 'ui-icon-arrowstop-1-w');
		NewPos = 'Left';
		CurrentPos = 'Right';
	} else {
		el.innerHTML = el.innerHTML.replace('ui-icon-arrowstop-1-w', 'ui-icon-arrowstop-1-e');
		NewPos = 'Right';
		CurrentPos = 'Left';
	}
	document.getElementById('SideBarPositionCSS').href = document.getElementById('SideBarPositionCSS').href.replace(NewPos + '.css', CurrentPos + '.css');
	SavePref('Type=SideBarPosition&Position=' + CurrentPos);
}

function SavePref(postData) {
	if (window.XMLHttpRequest) {
		http = new XMLHttpRequest();
	} else {
		http = new ActiveXObject("Microsoft.XMLHTTP");
	}
	http.open("POST", "/Scripts/SavePref.php", true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", postData.length);
	http.setRequestHeader("Connection", "close");
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			switch(http.responseText) {
				case '':
					break;
				case 'Error-SessionTimeout':
					alert('Your session has timmed out');
					window.location="/Membership/Login.html";
					break;
				case 'Error-InValidChange':
					alert('Invalid request');
					window.location.reload();
					break;
				default:
					alert(http.responseText);
					break;
			}
		}
	}
	http.send(postData);
}

$(function() {
	$('#AvailableItems').removeClass('portlet')
		.attr('title', 'Available items')
		.find('.portlet-header')
		.remove();
	$('#AvailableItems').dialog({
		autoOpen: false,
		width: 550,
		modal: false
	});
	$('#ViewAvailableItems').click(function(){
		$('#AvailableItems').dialog('open');
		return false;
	});
	$(".portlet, .portletMin")
		.addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
		.find(".portlet-header")
		.addClass("ui-widget-header ui-corner-all");
	$(".portlet:not(.PortletSticky), .portletMin:not(.PortletSticky)")
		.find(".portlet-header")
		.prepend('<div class="CreateIcon" title="Remove this portlet"><span class="ui-icon ui-icon-closethick"><\/span><\/div><div class="CreateIcon" title="Min/Max portlet"><span class="ui-icon ui-icon-minusthick ui-icon-plusthick"><\/span><\/div>');
	$(".portlet-header .ui-icon-minusthick").click(function() {
		$(this).toggleClass("ui-icon-minusthick");
		Portlet = $(this).parents(".portlet:first")[0];
		ParentDiv = findParentDiv(Portlet);
		if($(this).parents(".portlet:first").find(".portlet-content").is(':visible')) {
			Max = 0;
		} else {
			Max = 1;
		}
		SavePref('Type=PortletChangeMax&Portlet=' + Portlet.id + '&Max=' + Max + '&Parent=' + ParentDiv.id);
		$(this).parents(".portlet:first").find(".portlet-content").toggle();
	});
	$(".portletMin")
		.toggleClass("portlet")
		.toggleClass("portletMin")
		.find(".portlet-header .ui-icon-minusthick")
		.toggleClass("ui-icon-minusthick")
		.end()
		.find(".portlet-content")
		.toggle();
	$(".portlet-header .ui-icon-closethick").click(function() {
		Portlet = $(this).parents(".portlet:first")[0];
		ParentDiv = findParentDiv(Portlet);
		SavePref('Type=RemovePortlet&Portlet=' + Portlet.id + '&Parent=' + ParentDiv.id);
		$(this).parents(".portlet:first").remove();
	});
	$(".SSortable").sortable({
		connectWith: '#UL_SBP_Manage, .SSortable',
		beforeStop: BeforeSortStopItems,
		items: 'li:not(.NoSort)'
	});
	$(".MSortable").sortable({
		connectWith: '#UL_SBP_Manage, .MSortable',
		beforeStop: BeforeSortStopItems,
		items: 'li:not(.NoSort)'
	});
	$("#ContentSecondarySortable").sortable({
		update: SavePortletSort
	});
	$("#PageFlip").hover(function() {
		$("#PageFlip img, .MsgBlock").stop()
			.animate({
				width: '307px',
				height: '319px'
			}, 500);
		} , function() {
		$("#PageFlip img").stop()
			.animate({
				width: '50px',
				height: '52px'
			}, 1140);
		$(".MsgBlock").stop()
			.animate({
				width: '50px',
				height: '50px'
			}, 1100);
	});
	$("#SubTabs").tabs();
	$("#SubTabs").find('.ui-tabs-panel').sortable({
		update: SavePortletSort
	});
	$('.MainTabsLi').hover(
		function() {
			$(this).addClass('ui-state-hover');
		},
		function() {
			$(this).removeClass('ui-state-hover');
		}
	);
	$('.Status_Error')
		.addClass('ui-corner-all ui-state-error')
		.prepend('<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span><strong>Alert:</strong>')
		.wrapInner('<p style="padding: .4em 2em;"/>');
	$('.Status_Warning')
		.addClass('ui-corner-all ui-state-highlight')
		.prepend('<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>')
		.wrapInner('<p style="padding: .4em 2em;"/>');
	$('.Status_Success')
		.addClass('ui-corner-all ui-state-highlight')
		.prepend('<span class="ui-icon ui-icon-check" style="float: left; margin-right: .3em;"></span>')
		.wrapInner('<p style="padding: .4em 2em;"/>');
	$('#ResetSideBarDialog').dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		buttons: {
			"Yes": function() {
				SavePref('Type=ResetSidebar');
				$(this).dialog("close");
				setTimeout("window.location.reload()",300);
			},
			"No": function() {
				$(this).dialog("close");
			}
		}
	});
	$('#ResetSidebar').click(function(){
		$('#ResetSideBarDialog').dialog('open');
		return false;
	});
	$(':submit, div.CreateIcon, div.CreateButton')
		.hover(
			function() { $(this).addClass('ui-state-hover'); },
			function() { $(this).removeClass('ui-state-hover'); }
		)
		.addClass('ui-state-default ui-corner-all');
	$('#AddNewQuickLinkDialog').dialog({
		autoOpen: false,
		width: 190,
		modal: true,
		buttons: {
			"Save": function() {
				t = document.getElementById('LinkText').value.replace(/(<([^>]+)>)/ig,'');
				t = t.replace(/[^a-zA-Z 0-9]+/g,'');
				SavePref('Type=AddQL&Text=' + t + '&Page=' + '/' . BWHC_RequestedPage);
				$(this).dialog("close");
				setTimeout('window.location.reload()',300);
			},
			"Cancel": function() {
				$(this).dialog("close");
			}
		}
	});
	$('#AddNewQuickLinkB').click(function(){
		$('#AddNewQuickLinkDialog').dialog('open');
		return false;
	});
	$('#ResetThisSetDialog').dialog({
		autoOpen: false,
		width: 220,
		modal: true,
		buttons: {
			"Yes": function() {
				SavePref('Type=ThisSetReset&Set=' + $(document.getElementById('ResetThisTabSet')).find(".ui-icon")[0].id);
				$(this).dialog("close");
				setTimeout("window.location.reload()",300);
			},
			"No": function() {
				$(this).dialog("close");
			}
		}
	});
	$('#ResetThisTabSet').click(function(){
		$('#ResetThisSetDialog').dialog('open');
		return false;
	});
	$('#DoNothingDialog').dialog({
		autoOpen: false,
		width: 650,
		modal: true,
		closeOnEscape: false,
		buttons: {
			"1=2": function() {},
			"3 types of people": function() {},
			"Yes": function() {},
			"Click here until this closes": function() {},
			"Free Candy": function() {},
			"...": function() {},
			"11 types of people": function() {},
			"No": function() {},
			"Im not very bright": function() {
				document.getElementById('JustReported').style.display = 'block';
				$(this).dialog("close");
			},
			"Cancel": function() {},
			"Thursday": function() {}
		},
		open: function(event, ui) {
			$(this).parent().find(".ui-dialog-titlebar").find(".ui-dialog-titlebar-close").remove();
		}
	});
	$('#DoNothing').click(function(){
		$('#DoNothingDialog').dialog('open');
		return false;
	});
	$('.datepicker').datepicker({
		changeMonth: true,
		changeYear: true,
		appendText: '(mm/dd/yyyy)',
		gotoCurrent: true,
		numberOfMonths: 3
	});
	$('.ShowBox').click(function(){
		Pieces = this.href.split('?');
		URL = Pieces[0];
		Vars = GetQueryVariables(Pieces[1]);
		if (!Vars.Width) {
			Vars.Width = 600;
		}
		$('#ShowBox').dialog({
			autoOpen: false,
			width: Vars.Width,
			modal: true,
		});
		if (window.XMLHttpRequest) {
			http = new XMLHttpRequest();
		} else {
			http = new ActiveXObject("Microsoft.XMLHTTP");
		}
		http.open("GET", this.href, true);
		http.onreadystatechange = function() {
			if(http.readyState == 4 && http.status == 200) {
				document.getElementById('ShowBox').innerHTML = http.responseText;
				$('#ShowBox').dialog('open');
			}
		}
		http.send(null);
		return false;
	});
});

$(document).ready(function(){
	setClickable();
});

function AddPortletToThisTabSet(){
	CurrentTabIndex = $("#SubTabs").tabs().data("selected.tabs");
	ID = $(document.getElementById('SubTabs')).find(".ui-tabs-panel")[CurrentTabIndex].id;
	SavePref('Type=AddNewPortlet&Parent=' + ID);
	setTimeout("window.location.reload()",300);
}

function BeforeSortStopItems(event, ui) {

	SenPortlet = $(this).parents(".portlet:first")[0];
	RecPortlet = $(ui.item).parents(".portlet:first")[0];
	if (this.id == 'UL_AvailableItems') {
		SenPortlet = document.getElementById('AvailableItems');
	}

	if (SenPortlet.id == RecPortlet.id) {
		SaveOrder(RecPortlet.id);
	} else {
		RecUL = ui.item.parent('ul');
		if (RecUL.is('.NoInsert') && SenPortlet.id != 'SBP_Manage') {
			$(this).sortable('cancel');
			alert('Unable to drag items here.');
			return false;
		}
		if (RecPortlet.id == 'SBP_Manage') {
			SaveOrder(SenPortlet.id);
		} else {
			if (SenPortlet.id != 'SBP_Manage') {
				NewULHTML = RecUL[0].innerHTML;
				NewULHTML = NewULHTML.replace('<li style="visibility: hidden; height: 13px;" class="ui-sortable-placeholder"></li>', '');
				$(this).sortable('cancel');
				RecUL[0].innerHTML = NewULHTML;
			}
			SaveOrder(RecPortlet.id);
		}
	}
}

function SaveOrder(ID) {
	positions = '';
	Portlet = document.getElementById(ID);
	ParentDiv = findParentDiv(Portlet);
	uls = Portlet.getElementsByTagName("ul");
	length = uls[0].childNodes.length;
	litest = uls[0].childNodes[5];
	for (lis=0; lis<length; lis++){
		li = uls[0].childNodes[lis];
		if (li.id) {
			positions += ':' + li.id;
		}
	}
	SavePref('Type=Sort&Portlet=' + Portlet.id + '&Parent=' + ParentDiv.id + '&Order=' + positions);
}

function setClickable() {
	$('.EditInPlace').click(function() {
		textarea = '<div class="EditArea"><textarea rows="1" cols="20">'+$(this).html()+'</textarea>';
		button = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL" class="cancelButton" /></div></div>';
		revert = $(this).html();
		$(this).after(textarea+button).remove();
		$('.saveButton').click(function(){SaveEditInPlace(this, false);});
		$('.cancelButton').click(function(){SaveEditInPlace(this, revert);});
	})
	.mouseover(function() {
		$(this).addClass("editable");
	})
	.mouseout(function() {
		$(this).removeClass("editable");
	});
};

function SaveEditInPlace(obj, cancel) {
	if(!cancel && t !='') {
		var t = $(obj).parent().siblings(0).val();
		t = t.replace(/(<([^>]+)>)/ig,"");
		t = t.replace(/[^a-zA-Z 0-9]+/g,"");
		Portlet = $(obj).parents(".portlet:first")[0];
		ParentDiv = findParentDiv(Portlet);
		SavePref('Type=ChangeTitle&Portlet=' + Portlet.id + '&Parent=' + ParentDiv.id + '&Title=' + t);
	} else {
		var t = cancel;
	}
	if(t=='') t='(click to add text)';
	$(obj).parent().parent().after('<div class="EditInPlace">'+t+'</div>').remove();
	setClickable();
}

function SavePortletSort(event, ui) {
	Div = $(this)[0];
	var positions = '';
	var yindex = 0;
	$('#' + Div.id).find(".portlet").each(function(){yindex++;positions+=(this.id + ":");});
	SavePref('Type=PortletOrder&Parent=' + Div.id + '&Order=' + positions);
}