// Add indexof function for IE
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}

//string format function like in C# only for javascript
String.prototype.format = function() {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + i + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

String.prototype.formatWith = function() {
    var formatted = this;
    for (param in arguments[0]) {
        var regexp = new RegExp('\\{' + param + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[0][param]);
    }
    return formatted;
};

function canPlayH264() {
	var v = document.createElement('video');
	if (!!(v.canPlayType && v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"').replace(/no/, ''))) { 
		// it processed the video tag, so now test for mac and iOS devices
		var IsiPhone = navigator.userAgent.indexOf("iPhone") != -1;
	 	var IsiPod = navigator.userAgent.indexOf("iPod") != -1;
	 	var IsiPad = navigator.userAgent.indexOf("iPad") != -1;
	 	if (IsiPhone || IsiPad || IsiPod)
			return true;
	} else {
		return false;
	}
}

// Highlight the row in a table when checkbox is checked 
function highlightRow() {
    $(".checkbox input").click(function() {
        if ($(this).attr("checked") === true) {
            $(this).parent().parent().addClass("selected");
        }
        else {
            $(this).parent().parent().removeClass("selected");
        } 
    });
}
// When using the datatables plugin, this sets up the filter textbox
function setTableFilter() {
    $("#FilterQuery").keyup(function() {

        if ($("#FilterQuery").val() != "") {
            oTable.fnFilter(this.value);
            $("#FilterLabel").html('<a href="#">Clear</a>');
            $("#FilterLabel a").click(function() {
                $("#FilterQuery").val("").focus();
                oTable.fnFilter('');
                $("#FilterLabel").html('Filter: ');
            });
        } else {
            $("#FilterLabel").html('Filter: ');
            oTable.fnFilter('');
        }
    });
}

//Course Launch
function courseLink() {
	 $('a.CourseLink').click( function() {			
		var width = $(this).attr('puWidth');
		var height = $(this).attr('puHeight');
		var left   = (screen.width  - width)/2;
	 	var top    = (screen.height - height)/2;
		window.open($(this).attr('href'),
		'CourseWin','toolbar=no,location=no,scrollbars=no,status=no,resizable=yes,width='+width+',height='+height+',left=' + left + ',top=' + top);
		 $(".Popup").hide();
		return false;
	 });
}

// Quicksearch
function quicksearchInit() {

    $('#QuickSearch').tagdragon({
        'field': 'SearchQuery',
        'url': '/search/quicksearch',
        'delay': 400,
        'charMin': 3,
		'dblClick': false,
        onRenderItem: function(val, index, total, filter) {
            return '<img class="Icon" src="/userfiles/kod/bundleicons/' + val.icon + '" />' +
				val.title +
				'<span class="Cat">' + val.cats + '</span>';
        },
        onSelectItem: function(val) { window.location = '/resource/' + val.id; },
		onLoadList: function() {$('#SearchQuery').addClass('Loading'); },
		onLoadedList: function() {
			$('#SearchQuery').removeClass('Loading'); 
			pageTracker._trackPageview("/search?q="+$('#SearchQuery').val());
		}
    });

	$('#SearchForm').submit(function() {
		$(".SearchDefault a").text("Seaching all items...");
	});
}

// Quicklist buttons on asset view pages
function quicklistButtons() {
	//Button: Add to Quicklist
	$("#mQuicklist a").click(function() {
		$("#mQuicklist").addClass('Loading');
		$.post($(this).attr("href"), { __RequestVerificationToken: $("input[name='__RequestVerificationToken']").val() }, function(){
			$("#mQuicklist").removeClass('Loading');
			$("#mQuicklist").addClass('On');
			$("#mQuicklist span").text('Added');
		});
		return false;
	});

	//Button: Add to other user Quicklist
	$("#mOtherQuicklist a").click(function() {
	    $('#QuicklistUserAdd').dialog('open');
	    return false;
	});

	//Dialog: Add to other user
	$('#QuicklistUserAdd').dialog({
	    autoOpen: false,
	    modal: true,
	    width: 450, height: 350,
	    open: function() { $('#UserQuery').focus() },
	    buttons: { "Done": function() { $(this).dialog("close"); } }

	});
}

//AJAX Delete
(function($) {
    $.fn.confirmLink = function(m) {
        return this.click(function() {
                var answer = confirm(m);
                if (!answer) { return false; }
        });
    };
})(jQuery);

//AJAX Delete
(function($) {
    $.fn.ajaxDeleteAndHideRow = function(options) {
        var defaults = {
            confirm: false,
            message: 'Are you sure you want to delete this item?'
        };

        var options = $.extend(defaults, options);

        var deleteItem = function(item) {
            row = $(item).parents("tr");
            row.addClass("Deleted");

            $.post($(item).attr("href"), function() {
                row.hide();
            });

        };

        return this.click(function() {
            if (options.confirm) {
                var answer = confirm(options.message);
                if (answer) { deleteItem(this); return false; }
            } else {
                deleteItem(this);
                return false;
            }
            return false;
        });
    };
})(jQuery);

//Popup menu
(function($) {
    $.fn.popupMenu = function(m) {
        return $(this).click(function() {
	        var t = $(this);
			$(".Popup").not($(this).next('ul')).hide();
	        var position = $(this).position();
			var ptop = position.top + 20;

			// too close to the bottom, so make the menu go up
			if ($(window).height() + $(document).scrollTop() - position.top < $(this).next('ul').height()) { 
				ptop = position.top - $(this).next('ul').height();
			}

	        $(this).next('ul').css({"top" : ptop, "left" : position.left});
	        $(this).next('ul').toggle();
			$("body").click(function() { $(".Popup").hide() });
	        return false;
	    });
    };
})(jQuery);

//Default value for textfield
(function($) {
    $.fn.defaultValue = function(val) {
	       return this.each(function() {
				var t = $(this);
				t.val(val);
				t.focus(function(){
					if (t.val() == val)
						t.val("").addClass("On");
				});
				t.blur(function(){
					if (t.val() == "")
						t.val(val).removeClass("On");
				});
	    });
    };
})(jQuery);

//Page help
(function($) {
    $.fn.togglePageHelp = function(settingName) {
	       return this.each(function() {
				var t = $(this)
				t.click(function() {
					if (t.find("span").text() == "Hide") {
						$.post("/api/setusersetting/", {name: settingName, value: "off"});
						$("#PageHelp").slideUp();
						t.find("span").text("Show");
						return false;
					} else {
						$.post("/api/setusersetting/", {name: settingName, value: "on"});
						$("#PageHelp").slideDown();
						t.find("span").text("Hide");
						return false;
					}	
				});
	    });
    };
})(jQuery);

//Pagehelp FAQ Modal
function faqModalInit(page) {
	$("body").append('<div id="PageHelpModal" title="FAQ" class="Pad"></div>');

	$('#PageHelpModal').dialog({
	    autoOpen: false,
	    modal: true,
	    width: 750, 
		height: $(window).height() - 100
	});

	$('#FAQ a').click(function() {
		var t = $(this);
		$("#PageHelpModal").load(page, function() {
			var divOffset = $('#PageHelpModal').offset().top;
		    var pOffset = $(t.attr('href')).offset().top;
		    var pScroll = pOffset - divOffset;
			$('#PageHelpModal').animate({scrollTop: '+=' + pScroll + 'px'}, 500);
		}).dialog('open');
		return false;
	});
}

$.fn.equalHeights = function(px) {
    $(this).each(function() {
        var currentTallest = 0;
        $(this).children().each(function(i) {
            if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
     //   if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
        $(this).children().css({ 'min-height': currentTallest });
    });
    return this;
};

$(document).ready(function() {
/* Hide notify panel */
setTimeout(function() {$('#Notify').slideUp();}, 5000);
$('#UserMenu li:last').addClass("Last");
$("#SearchQuery").defaultValue("Search Articles and Videos");

});
