/*
 * IE7 doesn't support array.indexOf out of the box, so define it here...
 */
if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
    return -1;
    }
}

function confirmAttachmentDelete() {
	return confirm("Weet u zeker dat u deze verdiepende video wilt verwijderen? Alle gegevens inclusief het videobestand worden onomkeerbaar verwijderd.");
}

function confirmVideoDelete() {
	return confirm("Weet u zeker dat u deze video wilt verwijderen? Alle gegevens inclusief het videobestand worden onomkeerbaar verwijderd en koppelingen met dossiers worden verbroken, maar deze dossiers blijven nog wel beschikbaar.");
}

function confirmCancel(redir) {
	if (confirm("Weet u zeker dat u wilt annuleren? Wijzigingen worden dan niet doorgevoerd.")) {
		location.replace(redir);
	}
	return false;
}

function clearDefaultSearchText(element, defaultText) {
	if (element.value == defaultText) {
		element.value = '';
	}
	return false;
}

/**
 * Standard Javascript escape also escapes spaces etc. 
 * This function only used to escape for XSS possibilities. 
 */
function simpleXmlEscape(input) {
	if (input) {
		return input.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
	} else {
		return input
	}
}

/**
 * Standard Javascript escape also escapes spaces etc. 
 * This function only used to unescape for XSS possibilities.
 * This function should be used if you wish to further use data that
 * was previously simpleXmlEsaped. 
 */
function simpleXmlUnescape(input) {
	if (input) {
		return input.replace('&lt;', '<').input.replace('&gt;', '>').replace('&amp;', '&');
	} else {
		return input
	}
}

function openUploadPopup(videoId, type) {
	if (!type) type = 'video';
window.open('/leraar24-portlets/servlet/' + type + '/upload?videoId=' + videoId, 'upload' + videoId, 'width=490,height=240,location=no,status=no,menubar=no,resizable=no,scrollbars=no');
}

/**
 * Moves the selected items of a select box up.
 * 
 * @param selectId
 * @return
 */
function moveSelectItemsUp(selectId) {
	$('#' + selectId + ' option:selected').each(function(){
		$(this).insertBefore($(this).prev());
	});
}

function removeSelectedDossiers() {
	var selected = $("#relatedDossiers option");       
	if(selected.val() != null && confirm("Weet u zeker dat u deze koppeling(en) wilt verbreken? Dit kan niet ongedaan gemaakt worden, maar u kunt de koppeling altijd nog opnieuw leggen.")) {
		$('#relatedDossiers option:selected').remove();
	}
	return false;
}

function removeSelectedDocuments() {
	var selected = $("#relatedDocuments option");       
	if(selected.val() != null && confirm("Weet u zeker dat u deze koppeling(en) wilt verbreken? Dit kan niet ongedaan gemaakt worden, maar u kunt de koppeling altijd nog opnieuw leggen.")) {
		$('#relatedDocuments option:selected').remove();
	}
	return false;
}

function removeSelectedVideos() {
	var selected = $("#relatedVideos option");       
	if(selected.val() != null && confirm("Weet u zeker dat u deze koppeling(en) wilt verbreken? Dit kan niet ongedaan gemaakt worden, maar u kunt de koppeling altijd nog opnieuw leggen.")) {
		$('#relatedVideos option:selected').remove();
	}
	return false;
}

function removeSelectedAttachments() {
	var selected = $('#relatedAttachments option');
	if(selected.val() != null && confirm("Weet u zeker dat u deze koppeling(en) wilt verbreken? Dit kan niet ongedaan gemaakt worden, maar u kunt de koppeling altijd nog opnieuw leggen.")) {
		$('#relatedAttachments option:selected').remove();
	}
	return false;
}

/**
 * Moves the selected items of a select box down.
 * 
 * @param selectId
 * @return
 */
function moveSelectItemsDown(selectId) {
	$('#' + selectId + ' option:selected').each(function(){
		$(this).insertAfter($(this).next());
	});
}

function alt_show() {
    document.getElementById('filetypes').style.display = 'block';
}

function alt_remove() {
    document.getElementById('filetypes').style.display="none";
}

function isIE6() {
	return $.browser.msie && jQuery.browser.version == "6.0";
}

$(document).ready(function() {

	if (isIE6() && $.cookie('ie6warning') == null) {
		alert('Uw browser Internet Explorer 6 wordt niet optimaal ondersteund.');
		$.cookie('ie6warning', 'shown', {path:'/'});
	}

	$('a[rel|=video]').click(function() {
		if (typeof popup != 'undefined') popup.close();
		var url = $(this).attr('href');
		popup = window.open(url, 'upload', 'width=510,height=540,location=no,status=no,menubar=no,resizable=no,scrollbars=yes');
		return false;
	});
	
	$('input[name="usergenerated"]').click(
		    function(){
		        $('input[name="_usergenerated"]').val(
		            $('input[name="usergenerated"]').attr('checked')
		        )
		    }
		);
	/**
	 * Fix for the IE form elements z-index Bug
	 */
    $('#createLinkDialog').bgiframe(); 
    $('#editLinkDialog').bgiframe(); 
    $('#relatedDocumentsDialog').bgiframe(); 
    $('#relatedVideosDialog').bgiframe(); 
    $('#relatedDossiersDialog').bgiframe(); 
    
	/**
	 * Add tablesorter to tables with class 'tablesorter' 
	 */
    $('.tablesorter').tablesorter();

	/**
	 * Add tablesorter to tables with class 'tablesorter' 
	 */
    $('.tablednd').tableDnD();

    /**
     *  attach events for related dossiers, videos and documents 
     */
    $('#relatedDossiersDialog table.related tbody tr td a').live('click', function() {
    	$(this).each(function(it, el) {
    		var id = el.id.substring('dossier_'.length);
    		$('#relatedDossiers').prepend('<option value=' + id + '>' + $(el).parent().prev().text() + '</option>');
    	});
    	$(this).parent().parent().remove();
    	return false;
    });
    $('#relatedDocumentsDialog table.related tbody tr td a').live('click', function() {
    	$(this).each(function(it, el) {
    		var id = el.id.substring('document_'.length);
    		$('#relatedDocuments').prepend('<option value=' + id + '>' + $(el).parent().prev().text() + '</option>');
    	});
    	$(this).parent().parent().remove();
    	return false;
    });
    $('#relatedAttachmentsDialog table.related tbody a').live('click', function() {
    	$('#' + this.id).each(function(it, el) {
    		var id = el.id.substring('video_'.length);
    		var title = $(el).parent().prev().text();
    		$('#relatedAttachments').prepend('<option value=' + id + '>' + title + '</option>');
    	});
    	$(this).parent().parent().remove();
    	return false;
    });
    $('#relatedVideosDialog table.related tbody tr td a').live('click', function() {
    	$('#' + this.id).each(function(it, el) {
    		var id = el.id.substring('video_'.length);
    		var title = $(el).parent().prev().text();
    		$('#relatedVideos').prepend('<option value=' + id + '>' + title + '</option>');
    	});
    	$(this).parent().parent().remove();
    	return false;
    });
    
    /**
     *  attach cancel handler on dialogs for dossiers, videos and documents 
     */
    $("#relatedDossiersDialog, #relatedDocumentsDialog, #relatedVideosDialog, #relatedAttachmentsDialog").dialog({
    	autoOpen: false,
    	buttons: {
	    	'Ok': function() { $(this).dialog('close'); }
	    },
	    modal:true,
	    width: 400,
	    height: 600
    });
    
    /**
     *  attach ok/cancel handler on the edit link dialog
     */
    $('#createLinkDialog').dialog({
    	autoOpen: false,
    	buttons: {
	    	'Ok': function() {
				if ($.trim($('#new_link_title').val()).length == 0) {
					// Prevalidation, otherwise link is not accessible anymore
					alert('De link titel is leeg');
				} else if ($.trim($('#new_link_url').val()).length == 0) {
					// Prevalidation, otherwise link is not accessible anymore
					alert('De link url is leeg');
				} else {
					var linkId = $('#new_link_id').val();
					
					var displayUrl = simpleXmlEscape($('#new_link_url').val());
					if(displayUrl.length > 45) {
						displayUrl = displayUrl.substring(0,45)+"...";
					}
					$('#linksTable tbody').append('<tr id="link_display_' + linkId + '">'
											+ '<td><input type="checkbox" id="select_' + linkId + '" class="link_select"/></td>'
											+ '<td><a href="#" onclick="editLink(\'' + linkId + '\'); return false;">' + simpleXmlEscape($('#new_link_title').val()) + '</a></td>'
											+ '<td><a href="' + simpleXmlEscape($('#new_link_url').val()) + '">'+displayUrl+'</a><span style="display:none">' + simpleXmlEscape($('#new_link_url').val()) + '</span></td>'
											+ '<td>' + simpleXmlEscape($('#new_link_description').val()) + '</td>'
										+ '</tr>');

					$('#new_link_id').val('');
					$('#new_link_title').val(''); 
					$('#new_link_url').val('');
					$('#new_link_description').val('');

					$('#linksTable').trigger("update");			

					$(this).dialog('close');
				}
			},

	    	'Cancel': function() {
				$(this).dialog('close');
			}
	    },
	    position:'top',
	    modal:true,
	    width: 400,
	    height: 400
    });

    /**
     *  attach ok/cancel handler on the edit link dialog
     */
    $('#editLinkDialog').dialog({
    	autoOpen: false,
    	buttons: {
	    	'Ok': function() {
				if ($.trim($('#edit_link_title').val()).length == 0) {
					// Prevalidation, otherwise link is not accessible anymore
					alert('De link titel is leeg');
				}
				else if ($.trim($('#edit_link_url').val()).length == 0) {
					// Prevalidation, otherwise link is not accessible anymore
					alert('De link url is leeg');
				} else {
					var linkId = $('#edit_link_id').val();

					var displayUrl = $('#edit_link_url').val();
					if(displayUrl.length > 45) {
						displayUrl = displayUrl.substring(0,45)+"...";
					}
	                $('#link_display_' + linkId + ' td:eq(1) a').text($('#edit_link_title').val());
	                $('#link_display_' + linkId + ' td:eq(2) a').attr('href', $('#edit_link_url').val());
	                $('#link_display_' + linkId + ' td:eq(2) a').text(displayUrl);
	                $('#link_display_' + linkId + ' td:eq(2) span').text($('#edit_link_url').val());
	                $('#link_display_' + linkId + ' td:eq(3)').text($('#edit_link_description').val());

					$(this).dialog('close');
				}
			},
	    	'Cancel': function() {

				$(this).dialog('close');
			}
	    },
	    position:'top',
	    modal:true,
	    width: 400,
	    height: 400
    });
    
    /**
     *  attach submit handler on editform for dossiers, videos and documents 
     */
	$("#dossier").bind("submit",function(){
		// gather relatedDocument ids
		var result = "";
		$("#relatedDocuments option",this).each(function(){
			if(result.length > 0) result += ',';
			result += this.value;
		});
		$("#relatedDocumentIds").val(result);

		result = "";
		// gather relatedVideo ids
		$("#relatedVideos option",this).each(function(){
			if(result.length > 0) result += ',';
			result += this.value;
		});
		$("#relatedVideoIds").val(result);
		return true;
	});
	$("#document").bind("submit",function(){
		var result = "";
		$("#relatedDossiers option", this).each(function(){
			if(result.length > 0) result += ',';
			result += this.value;
		});
		$("#relatedDossierIds").val(result);
		return true;
	});
	$("#video").bind("submit",function(){
		var result = "";
		$("#relatedDossiers option", this).each(function(){
			if(result.length > 0) result += ',';
			result += this.value;
		});
		$("#relatedDossierIds").val(result);

		var result = "";
		$('#relatedAttachments option', this).each(function() {
			if (result.length > 0) result += ',';
			result += this.value;
		});
		$('#relatedAttachmentIds').val(result);
		
		return true;
	});
	
    /**
     *  attach search handler on dialogs for dossiers, videos and documents 
     */
	$("#relatedDossiersSearch").bind("submit",function(){
		var result = [];
		$("#relatedDossiers option").each(function(){
			//if(result.length > 0) result += ',';
			result[result.length] = this.value;
		});
		var searchtext = $("input[name='searchtext']", this).val();
		dossierService.searchUnrelatedDossiers(searchtext, result, function(data) {
			$('#relatedDossiersDialog .related tbody tr').remove();

			if (data != null && typeof data == 'object' && data.length > 0) {
				for (var i = 0; i < data.length; i++) {
					var dossier = data[i];
					$('#relatedDossiersDialog .related').append('<tr><td>' + simpleXmlEscape(dossier.identifier) + '</td><td>' + simpleXmlEscape(dossier.title) + '</td><td><a href="#" id="dossier_' + dossier.id + '">Voegtoe</a></td></tr>');
				}
			}
			else {
				$('#relatedDossiersDialog .related').append('<tr><td colspan="3">Geen resultaten gevonden voor "' + searchtext + '"</td></tr>');
			}

			$('#relatedDossiersDialog .related').trigger("update");
		});

		return false;
	});
	$("#relatedDocumentsSearch").bind("submit",function(){
		var result = [];
		$("#relatedDocuments option").each(function(){
			//if(result.length > 0) result += ',';
			result[result.length] = this.value;
		});
		var searchtext = $("input[name='searchtext']", this).val();
		documentService.searchUnrelatedDocuments(searchtext, result, function(data) {
			$('#relatedDocumentsDialog .related tbody tr').remove();

			if (data != null && typeof data == 'object' && data.length > 0) {

				for (var i = 0; i < data.length; i++) {
					var document = data[i];
					$('#relatedDocumentsDialog .related').append('<tr><td>' + simpleXmlEscape(document.identifier) + '</td><td>' + simpleXmlEscape(document.title) + '</td><td><a href="#" id="document_' + document.id + '">Voegtoe</a></td></tr>');
				}
			}
			else {
				$('#relatedDocumentsDialog .related').append('<tr><td colspan="3">Geen resultaten gevonden voor "' + searchtext + '"</td></tr>');
			}

			$('#relatedDocumentsDialog .related').trigger("update");
		});

		return false;
	});
	$("#relatedVideosSearch").bind("submit",function(){
		var result = [];
		$("#relatedVideos option").each(function(){
			//if(result.length > 0) result += ',';
			result[result.length] = this.value;
		});
		var searchtext = $("input[name='searchtext']", this).val();
		videoSourceService.searchUnrelatedVideoMetadata(searchtext, result, function(data) {
			$('#relatedVideosDialog .related tbody tr').remove();
			
			if (data != null && typeof data == 'object' && data.length > 0) {
				for (var i = 0; i < data.length; i++) {
					var video = data[i];
					var videoIdentifier = (video.identifier === null ? "" : video.identifier);
					$('#relatedVideosDialog .related').append('<tr><td>' + simpleXmlEscape(videoIdentifier) + '</td><td>' + simpleXmlEscape(video.title) + '</td><td><a href="#" id="video_' + video.videoId + '">Voegtoe</a></td></tr>');
				}
			}
			else {
				$('#relatedVideosDialog .related').append('<tr><td colspan="3">Geen resultaten gevonden voor "' + searchtext + '"</td></tr>');
			}

			$("#relatedVideosDialog .related").trigger("update");
		});

		return false;
	});

	$('#relatedAttachmentsSearch').submit(function() {
		var result = [];
		$("#relatedAttachments option").each(function(){
			result.push( this.value );
		});
		var searchtext = $("input[name='searchtext']", this).val();
		videoAttachmentService.findUnrelatedAttachments(searchtext, result, function(data) {
			$('#relatedAttachmentsDialog .related tbody tr').remove();
			if (typeof data == 'object' && data.length > 0) {
				for (var i = 0; i < data.length; i++) {
					var video = data[i];
					var videoIdentifier = (video.identifier === null ? "" : video.identifier);
					$('#relatedAttachmentsDialog .related').append('<tr><td>' + simpleXmlEscape(videoIdentifier) + '</td><td>' + simpleXmlEscape(video.title) + '</td><td><a href="#" id="video_' + video.videoId + '">Voegtoe</a></td></tr>');
				}
			} else {
				$('#relatedAttachmentsDialog .related').append('<tr><td colspan="3">Geen resultaten gevonden voor "' + searchtext + '"</td></tr>');
			}

			$("#relatedAttachmentsDialog .related").trigger("update");
		});
		return false;
	});
	
	/**
	 * Enable keyword suggestions
	 */
	$("#keywordSuggestions").keyup(function(e) {
		var suggestionTextField = this;
		
		var currentText = suggestionTextField.value;
		if (currentText.length < 1) {
			$("#tagMatches").empty();
			return;
		}
		
		var segments = currentText.split(',');
		var lastSegment = segments.length > 0 ? segments[segments.length-1] : segments[0];
		lastSegment = $.trim(lastSegment);
		if (lastSegment.length < 1) {
			$("#tagMatches").empty();
			return;
		}
		
		
		keywordService.findUniqueKeywordTextsByCaseInsensitivePrefix(lastSegment, function(data) {
			if (data != null && typeof data == 'object') {
				$("#tagMatches").empty();
				for (var i = 0; i < data.length; i++) {
					$("#tagMatches").append('<span class="tag_suggestion">' + simpleXmlEscape(data[i]) + '</span>')
				}
				
				$("#tagMatches .tag_suggestion").click(function() {
					if (segments.length > 0) {
						segments.pop();
					}

					suggestionTextField.value = segments.length > 0
											  ? segments.join() + "," + $(this).text()
											  : $(this).text();
					$(this).remove();
					$("#tagMatches").empty();			  
					suggestionTextField.focus();
				});
			}
		});
	});
	
/*http://orkans-tmp.22web.net/star_rating/index.html#overview*/
   $("#stars-wrapper1").stars({
       oneVoteOnly: true,
       callback: function(ui, type, value){     
           $("#rateForm").submit();
       }
   });	

	$("h3").hover(
	      function () {
	        $(this).addClass("jan");
	      }, 
	      function () {
	        $(this).removeClass("jan");
	      }
	    );

		// $("input[type=text]").focus(function(){
		//     // Select field contents
		//     this.select();
		// });	
		if ( $("#accordion").length > 0 ) {		
			$("#accordion").accordion({
				alwaysOpen: false,
				header: 'h3',
				collapsible:true,
				active: false,
				autoHeight: false,
				change: function(event, ui) { 
			        if(ui.newHeader && ui.newHeader.hasClass('ui-state-active')){
			            $('#accordion h3').each(     
			                function(it, el){          
			                    var isActive = $(el).hasClass('ui-state-active');   
			                    if(isActive){
			                        $.cookie('accordion-active', it, {path:'/'});
			                    }   
			                } 
			            );
			        } else {
                    	$.cookie('accordion-active', '', {path:'/'});
                     }
			    }
			});
			
			if($.cookie('accordion-active')) {
			    $("#accordion").accordion('activate' , parseInt($.cookie('accordion-active'), 10));
			}
		}
		//http://sorgalla.com/projects/jcarousel/#Examples
 		if ( $("#mycarousel").length > 0 ) {
		    $("#mycarousel:has(ul)").jcarousel({
		        scroll: 1,
		        auto: 5,
		        visible: 1,
		        wrap: 'last',
		        initCallback: mycarousel_initCallback,
		        itemFirstInCallback:  mycarousel_itemFirstInCallback,
		        // This tells jCarousel NOT to autobuild prev/next buttons
		        buttonNextHTML: null,
		        buttonPrevHTML: null,
                        animation: false,
                        itemLoadCallback: {
                          onBeforeAnimation: function() {
                                $('.jcarousel-list p').css('opacity', 0);
                          },
                          onAfterAnimation: function() {
                                $('.jcarousel-list p').fadeTo(800, 1);
                          }
                        }
		    });
		}

		$('.tooltip').tooltip({ 
		    track: true, 
		    delay: 0, 
		    showURL: false, 
		    showBody: " - ", 
		    fade: 250 
		});
});

/**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
function mycarousel_initCallback(carousel) {
    jQuery('.jcarousel-control a').bind('click', function() {
        carousel.stopAuto();
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        carousel.startAuto();
        return false;
    });
/*
    jQuery('#mycarousel-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#mycarousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
*/
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
    
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });

};

/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
	$(".jcarousel-control a").removeClass("visible");
	$(".jcarousel-control a:eq("+(idx-1)+")").addClass("visible");
};
