﻿var fancyBoxUrl;

$(document).ready(function () {
	$("#subscribe").click(function () {
		$("#subscribe-dialog").dialog({ modal: true });
	});

	InitializeContextMenu('li.showContext', '#contextMenu');
	InitializeContextMenu('span.headerFilter', '#headerFilter');
	InitializeContextMenu('span.quickLaunch', '#quickLaunch');

	InitializeCollapsable();

	InitializeContent();
});

function InitializeContent() {
    $.ajaxSetup({ cache: false });

    InitializePaginators();
	InitializeDialogs();
	InitializePreviews();
	InitializeBBCodeEditor();
	InitializeCharactersRemaining();
	InitializeAutoComplete();
	InitializeNewFilters();
	InitializeContextMenu('span.filterDropdown', '#filterMenu');
	populateSearch();
}

function clearSearch() {
    if ($('#txtMasterSearch').val() == "click search to see everything...") {
        $('#txtMasterSearch').val('');
    }
}

function populateSearch() {
    if ($('#txtMasterSearch').val() == "") {
        $('#txtMasterSearch').val('click search to see everything...');
    }
}

function split(val) {
	return val.split(/,\s*/);
}

function extractLast(term) {
    return split(term).pop();
}

function setDDL(ddlId, value) {
	$('#' + ddlId).val(value);
}

function postAndRemove(elementId, url) {
	$.post(url, function (data) {
		if (data == 'success') {
			$('#' + elementId).fadeOut('slow', function () {
				$(this).remove();
			});
		}
	});
}

function SetEditable() {
	hideDialog();
	if ($('#EditablePropertiesSave:visible').length == 1) {
		$('.ROProperties').hide(); 
		$('.EditableProperties').show();
	}
	else {
		$('.EditableProperties').hide();
		$('.ROProperties').show();
	}
}

function InitializePaginators() {
    $('.paginatorLink[loaded!=true]').each(function () {
        $(this).attr("loaded", "true");
        $(this).click(function () {
        	var updateTarget = $(this).closest('.dragbox');
            if (changeRefreshValue(updateTarget, 'page', $(this).attr('page'))) {
                RefreshModule(updateTarget.attr('id'));
            }
        });
    });

    $('.leftArrow[loaded!=true],.rightArrow[loaded!=true]').each(function () {
        $(this).attr("loaded", "true");
        $(this).click(function () {
            var updateTarget = $(this).closest('.dragbox');
            var currentPageString = getQueryStringValue(updateTarget.attr('refresh').toLowerCase(), 'page');
            var currentPage = parseInt(currentPageString);

            if (isNaN(currentPage) || currentPage <= 0)
                currentPage = 1;

            currentPage += ($(this).hasClass("leftArrow") ? -1 : 1)

            if (currentPage > 0) {
                if (changeRefreshValue(updateTarget, 'page', currentPage)) {
                    RefreshModule(updateTarget.attr('id'));
                }
            }
        });
    });
}

function InitializeCollapsable() {
    // Move all modules to be collapsed into this module
    $('.AdditionalInfo').each(function () {
    	$('.collapsibleContainer').append($(this).closest('.dragbox').remove());
    });

    $('#collapsible').click(function () {
        $('.collapsibleContainer').toggle('blind');
        $(this).toggleClass('arrowUp');
        $(this).toggleClass('arrowDown');
    });
}

function changeRefreshValue(module, key, value) {
    var refresh = module.attr('refresh').toLowerCase();
    var start = refresh.indexOf(key + '=');
    if (start != -1) {
        start += key.length + 1
        var end = refresh.indexOf('&', start);
        if (end == -1) end = refresh.length;
        var newRefresh = module.attr('refresh').substring(0, start) + value + module.attr('refresh').substring(end);
        module.attr('refresh', newRefresh);
    }
    else {
        module.attr('refresh', module.attr('refresh') + '&' + key + '=' + value);
    }
    return true;
}

function getQueryStringValue(queryString, key) {
    var qs = queryString.toLowerCase();
    var start = qs.indexOf(key + '=');
    if (start != -1) {
        start += key.length + 1
        var end = qs.indexOf('&', start);
        if (end == -1) end = qs.length;

        return queryString.substring(start, end);
    }
    return '';
}

function ReplaceQueryStringValue(queryString, key, value) {
	var qs = queryString.toLowerCase();
	key = key.toLowerCase();
    var start = qs.indexOf(key + '=');
    if (start != -1) {
        start += key.length + 1;
        var end = qs.indexOf('&', start);
        if (end == -1) end = qs.length;
        var nqs = queryString.substring(0, start) + value + queryString.substring(end);
        return nqs;
    }
    return queryString + "&" + key + "=" + value;
} 


function InitializeContextMenu(button, content) {
    $(content).click(function (e) {
        e.stopPropagation();
    });

    $(button).click(function (e) {
        $('.contextMenu').hide();
        $(content).show();
        e.stopPropagation();
        $(document).one('click', function () { $(content).hide(); });
    });
}

function InitializeAutoComplete() {
	$('.autoComplete[loaded!=true]').each(function () {
		$(this).attr("loaded", "true");

		// don't navigate away from the field on tab when selecting an item
		$(this).bind("keydown", function (event) {
			if (event.keyCode === $.ui.keyCode.TAB &&
					$(this).data("autocomplete").menu.active) {
				event.preventDefault();
			}
		})

		var dataSource = $(this).attr('dataSource');
		$(this).autocomplete({
			source: function (request, response) {
				$.getJSON(dataSource, {
					term: extractLast(request.term)
				}, response);
			},
			search: function () {
				// custom minLength
				var term = extractLast(this.value);
				if (term.length < 1) {
					return false;
				}
			},
			focus: function () {
				// prevent value inserted on focus
				return false;
			},
			select: function (event, ui) {
				var terms = split(this.value);
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push(ui.item.value);
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				return false;
			}
		});
	});
}

function InitializeDialogs() {

	$('.ui-dialog').each(function () {
		if ($('.ui-dialog-content .popoutHeading', $(this)).length > 0) {
			$('.ui-dialog-titlebar .popoutHeading', $(this)).remove();
			$('.ui-dialog-titlebar', $(this)).append($('.popoutHeading', $(this)).remove());
			var pop = $('.ui-dialog-content .dialogPopout', $(this));
			$('.mediaContent > img', pop).css({ maxHeight: pop.height() - 80, maxWidth: pop.width() });
		}
	});

	$("a#.popout").unbind("click").click(function (e) {
		e.preventDefault();

		var href = $(this).attr('href');
		href = ReplaceQueryStringValue(href, 'ModuleId', '');
		var pop = $('<div>Loading...</div>');

		pop.wijdialog({
			width: 597,
			height: 454,
			minWidth: 300,
			minHeight: 200,
			resize: function (event, ui) {
				$('.mediaContent > img', $(this)).css({ maxHeight: pop.height() - 80, maxWidth: pop.width() });
			},
			close: function () {
				$(this).empty().remove();
			}
		});

		$.ajax({
			type: 'GET',
			url: href,
			success: function (data) {
				pop.html(data);
				InitializePaginators();
				var popDialog = pop.closest('.ui-dialog');
				$('.ui-dialog-titlebar', popDialog).append($('.popoutHeading', pop).remove());
				$('.mediaContent > img', pop).css({ maxHeight: pop.height() - 80, maxWidth: pop.width() });
			}
		});

	});

	$("a#.confirm").unbind("click").click(function(e){
		e.preventDefault();

		var title = $(this).attr('title');
		if(title == undefined || title == '') title = "Confirmation";
		var message = $(this).attr('message');
		if(message == undefined || message == '') message = "Are you sure?";
		var href = $(this).attr('href');
		var method = $(this).attr('method');
		var updateTarget = $(this).attr('updateTarget');
		var onSuccess = $(this).attr('onSuccess');
		var dynamicRouteValues = $(this).attr('dynamicRouteValues') == undefined ? "" : $(this).attr('dynamicRouteValues');

		var $dialog =   $('<div></div>')
						.html(message)
						.dialog({
							autoOpen: false,
							title: title,
							resizable: false,
							modal: true,
							buttons:{
										'Cancel': function() {
											$(this).dialog('close');
										},
										'OK': function() {
											if (method == "post") {
												
												$.ajax({
													type: 'POST',
													url: href + dynamicRouteValues,
													success:    function(data) {
																	if(updateTarget != undefined){
																		RefreshModule(updateTarget);
																	}
																	if(onSuccess != undefined){
																		fun = eval(onSuccess);
																		fun();
																	}
																}
												});

											} else {
												window.location = href;
											}
											$(this).dialog('close');
										}
									}
						});

		$dialog.dialog('open');

		return false;

	});
}

function InitializeCharactersRemaining() {
	$('.characterLimit[maxCharacterLoaded!=true]').each(function () {
		$(this).attr("maxCharacterLoaded", "true");

		var characterLimitOptions = {
			'maxCharacterSize':  $(this).attr("allowCharacters"),
			'originalStyle': 'originalDisplayInfo',
			'warningStyle': 'warningDisplayInfo',
			'warningNumber': 40,
			'displayFormat': '#left Characters Left'
		};

		$(this).textareaCount(characterLimitOptions);

	});
}

function InitializeToolTips() {
    $(".tip").tooltip({
        position: {
            my: "right center",
            at: "right center",
            offset: "-50 0"
        }
    });
}


function setShowHelp() {
	$.ajax({ url: "account/setshowhelp", type: "POST" });
	$('.bubble').RemoveBubblePopup();
}

function InitializePreviews() {
    $("a#.lightbox").fancybox({ width: 830, onComplete: InitializeContent });

    $("a#.widelightbox").fancybox({ width: 830, onComplete: InitializeContent });
}

function hideFancybox() {
    $('#fancybox-close').trigger('click');
}

function InitializeBBCodeEditor() {
	$('.BBCodeTextArea[loaded!=true]').each(function () {
		$(this).attr("loaded", "true");
		$(this).before('<div class="btn bold" title="bold"></div><div class="btn italic"></div><div class="btn underline"></div><div class="btn link"></div>'); //<div class="btn quote"></div>
		$(this).bbcodeeditor(
		{
			bold: $(this).parent().find('.bold'), italic: $(this).parent().find('.italic'), underline: $(this).parent().find('.underline'), link: $(this).parent().find('.link'), //quote: $('.quote'),
			back_disable:true, forward_disable:true,
			exit_warning: false //, preview: $('.preview')
		});
	});
}

function hasHtml(content) {
    if (/<\S+/.test(content)) {
        alert('Sorry html tags are not allowed. Example <p> <div> <br>');
        return true;
    }
    return false;
}

function saveBBCodeEditor() {
	$('.BBCodeTextArea').each(function () {
		//var content = tinyMCE.get($(this).attr('id'));
		var content = $(this).val();

		if (!hasHtml(content)) {
			$(this).siblings('.HiddenBBCodeResult').each(function () {
				//$(this).val(content.getContent());
				$(this).val(content);
			});
		}
		else {
			$(this).siblings('.HiddenBBCodeResult').each(function () {
				//$(this).val(content.getContent());
				$(this).val('');
			});
		}
	});
}

function RefreshModule(moduleId) {
    if (moduleId != '') {
        var refresh = $('#' + moduleId).attr('refresh');
        if (refresh != undefined) {
        	if (refresh.indexOf('ModuleType') != -1) {
        		$.ajax({
        			type: 'POST',
        			url: '/refresh/',
        			data: refresh.substring(9),
        			success: function (data) {
        				$('#' + moduleId).replaceWith(data);
        				InitializeContent();
        			}
        		});
        	} else {
        		$.ajax({
        			type: 'POST',
        			url: refresh,
        			success: function (data) {
        				$('#' + moduleId).replaceWith(data);
        				InitializeContent();
        			}
        		});
        	}
        }
    }
}

function refreshFancyBox() {
	$.ajax({
		cache: false,
		url: $('#fancybox-tmp').attr('url'),
		success: function (data) {
		    $('#fancybox-content').html($(data));
			InitializeContent();
		}
	});
}

function GetFilterFlag(parent, name) {
	var flags = 0;
	$("." + name + ":checked", parent).each(function () {
		flags += parseInt($(this).attr('value'));
	});

	return flags;
}

function SetFilterFlag(parent, name, value) {
    $("." + name, parent).each(function () {
        var targetValue = parseInt($(this).attr('value'));
        var sourceValue = parseInt(value);

        if ((sourceValue & targetValue) == targetValue) {
            $(this).attr('checked', 'checked');
        } else {
            $(this).removeAttr('checked');
        }
    });
}

function InitializeNewFilters() {
    $(".contentFilter[loaded!=true]").each(function () {
        $(this).attr("loaded", "true");
        var contentFilter = $(this);
        var moduleId = $(this).attr('moduleId');
        var keywords = $('.filterKeywords', $(this));
        var filterButtons = $('.applyFilterButton', $(this));

        filterButtons.click(function () {
            var module = $('#' + moduleId);
            changeRefreshValue(module, 'page', "1");
            changeRefreshValue(module, 'keywords', $.URLEncode(keywords.val()));
            changeRefreshValue(module, 'contenttypes', GetFilterFlag(contentFilter, 'contentFilterCheckbox'));
            changeRefreshValue(module, 'mediatypes', GetFilterFlag(contentFilter, 'mediaFilterCheckbox'));
            RefreshModule(moduleId);
            $('#filterMenu').hide();
        });

        keywords.keypress(function (e) {
            if (e.keyCode == 13) {
                filterButtons.first().click();
            }
        });

		// Check Children
        $('.selectAllFilterCheckbox', contentFilter).change(function () {
			if ($(this).is(':checked') == true) {
              	$(this).closest('ul').find('input[type=checkbox]').attr("checked", true);
			} else {
              	$(this).closest('ul').find('input[type=checkbox]').attr("checked", false);
			}
		});

		// Check Media Children
        $('.contentFilterCheckbox[value=1]', contentFilter).change(function () {
			if ($(this).is(':checked') == true) {
              	$(this).parent().find('.mediaFilterCheckbox').attr("checked", true);
			} else {
              	$(this).parent().find('.mediaFilterCheckbox').attr("checked", false);
			}
		});

		// Check Media Parent
        $('.mediaFilterCheckbox', contentFilter).change(function () {
			if ($(this).is(':checked') == true) {
				$('.contentFilterCheckbox[value=1]', contentFilter).attr("checked", true);
			}
		});

    });
}

//
// SEARCH
//

var runningSearch = false;
var loadSearch = false;

$(document).ready(function () {
	$('.btnMasterSearch').click(RunSearch);

	$('#txtMasterSearch').keypress(function (e) {
		if (e.keyCode == 13) {
			RunSearch();
		}
	});

	// If we are on the search page
	if (typeof (window["OnSearchPage"]) != "undefined") {
		// Load the checkboxes from the current search
		if (window.location.hash != '' && !runningSearch) {
			//SetFilterFlag($('.filterDropDown'), 'contentFilterCheckbox', getQueryStringValue(window.location.hash, 'contenttypes'));
		}

		$('body').hashchange(function (e, newHash) {
			if (window.location.hash != '' && !runningSearch) {
				loadSearch = true;
				$('#txtMasterSearch').val($.URLDecode(getQueryStringValue(newHash, 'keywords')));
				SetFilterFlag($('.filterDropDown'), 'contentFilterCheckbox', getQueryStringValue(newHash, 'contenttypes'));
				SetFilterFlag($('.filterDropDown'), 'mediaFilterCheckbox', getQueryStringValue(newHash, 'mediatypes'));

				if (getQueryStringValue(newHash, 'details') == "true") {
					$('#DetailViewButtons span.showDetails').hide();
					$('#DetailViewButtons span.hideDetails').show();
				} else {
					$('#DetailViewButtons span.hideDetails').hide();
					$('#DetailViewButtons span.showDetails').show();
				}

				RunSearch();
				loadSearch = false;
			}
		});

		$.hash.init('home/blank');
	}
});

function RunSearch() {
    runningSearch = true;
	var searchUrl = window.location.hash;

	// Close the fancybox if it's open
	$('#fancybox-close').trigger('click');

	if (searchUrl == '') {
	    searchUrl = SiteRoot + 'Search/Search?page=1';
	} else {
	    // remove the #
	    searchUrl = searchUrl.substring(1);
	}

	if ($('#txtMasterSearch').val() == "click search to see everything...") {
	    searchUrl = ReplaceQueryStringValue(searchUrl, 'keywords', "");
	} else {
	   	searchUrl = ReplaceQueryStringValue(searchUrl, 'keywords', $.URLEncode($('#txtMasterSearch').val().trim()));
	   	$('#txtMasterSearch').val($('#txtMasterSearch').val().trim());
	}
	
	searchUrl = ReplaceQueryStringValue(searchUrl, 'contenttypes', GetFilterFlag($('#headerFilter'), 'contentFilterCheckbox'));
	searchUrl = ReplaceQueryStringValue(searchUrl, 'mediatypes', GetFilterFlag($('#headerFilter'), 'mediaFilterCheckbox'));

	searchUrl = ReplaceQueryStringValue(searchUrl, 'details', $('#DetailViewButtons span:visible').attr('value'));

	if (typeof (window["OnSearchPage"]) != "undefined") {
	    if (!loadSearch) {
	        $.hash.go(searchUrl);
	    }

		//$("#resultMozaic").fadeOut('fast');
		$("#searching").fadeIn('fast');

		$("#resultMozaic").load(searchUrl, function () {
			//$("#resultMozaic").fadeIn('fast');
			$("#searching").fadeOut('fast');
			InitializeContent();

			if ($('#resultMozaic').children().length == 1) {
				$('#DetailViewButtons').hide();
				$('#resultMozaic').append('<p class="SearchResultMessage">No Results Found</p>');
			} else {
				$('#DetailViewButtons').show();
			}
		});

	} else {
		window.location = SiteRoot + 'Search/#' + searchUrl;
	}

    runningSearch = false;
};

function textCounter(field, countfield, maxlimit) {
	if (field.val().length > maxlimit) // if too long...trim it!
		field.val(field.val().substring(0, maxlimit));
	// otherwise, update 'characters left' counter
	else
		countfield.val(maxlimit - field.val().length);
}

function GetAvatarSource(id, fileExtension, hasAvatar) 
{
	if (hasAvatar)
		return "/Resources/images/Avatars/" + id + "." + fileExtension;
	else
		return "/Resources/images/Avatars/0.jpg";
}

