$(function() {
    // only activate tab function if the tab nav exists
    if ( $('.vacancies-slide').length )
        	startCycle(); 
        	
    // only activate delete confirm function if the delete button exists
    if ( $('.delete-button').length )
        	confirmVacancyDelete(); 
        	
    // only activate delete confirm function if the delete button exists
    if ( $('#preview-button').length )
        	vacancyDetail(); 
    
    // only activate package info if button exists
    if ( $('.package-info-deprecated').length )
        	packageDetail(); 
        	
    // only activate tabs if the navigation exists
    if ( $('#tabnav').length )
            $('#tabnav').tabs();

    // only activate custom select function if the custom-select element exists
    if ( $('.custom-select').length )
            candidatesFormCustomSelect();

    // only activate if the edit-keywords element exists
    if ( $('#edit-keywords').length )
            keywordsFieldTrim();

});

/**
 *  script to fade the logo's at the homepage
 */
startCycle = function() {
    $('.vacancies-slide').cycle('fade');
}

confirmVacancyDelete = function() {
    $('.delete-button').click (function () {
        var answer = confirm ("Weet u zeker dat u deze vacature wilt verwijderen?");
			if (answer) {
			     return true;
			} else {
			    return false;
			}
        
    });
}

processUpload = function (id, fileName, responseJSON){
	if ($('#image_filename_img').length > 0) {
		$('#image_filename_img').attr('src', websiteGlobal.baseUrl + '/media/' + responseJSON.filename);
		$('#image_filename_text').val(responseJSON.filename);
	} else if ($('#upload_cv_img').length > 0) {
		$('#upload_cv_img')
			.attr('src', websiteGlobal.baseUrl + '/website/img/icon/' + responseJSON.ext + '.png')
			.click(function(){
				document.location.href=websiteGlobal.baseUrl+'/vacatures/getmyfile';
			})
			.css('cursor', 'pointer')
		;
		$('#upload_cv_text').val(responseJSON.ext);
	}
}

packageInfo = function(eltId) {
	$('#'+eltId).modal({
        close: true,
        position: ["20%",],
        overlayId: 'package-display-overlay',
	    containerId: 'package-display-container',
        onOpen: function (dialog) {
            dialog.overlay.fadeIn('fast');
            dialog.container.slideDown('fast', function () {   
                dialog.data.fadeIn('fast'); 
            });
        }
    });
    $('#package-display-overlay').click(function(){
        $.modal.close();
    })
    $('.package-display-close').click(function(){
        $.modal.close();
    })	
}

packageDetail = function() {
    
    $('.package-info').click(function() {
        postParams = 'edit[package-id]='+ $(this).attr('id');
        
        var url = window.location.href;
        postParams += '&edit[url]='+ url.replace(websiteGlobal.baseUrl, '');
    
        $.ajax({
            url: websiteGlobal.baseUrl+'vacatures/get_package_detail',
            type: 'POST',
            data: postParams,
            success: function(data, status) {
                $.modal(data, {
                    close: true,
                    position: ["20%",],
                    overlayId: 'package-display-overlay',
				    containerId: 'package-display-container',
                    onOpen: function (dialog) {
                        dialog.overlay.fadeIn('fast');
                        dialog.container.slideDown('fast', function () {   
                            dialog.data.fadeIn('fast'); 
                        });
                    }
                }) 
                
                $('#package-display-overlay').click(function(){
                    $.modal.close();
                })
                $('.package-display-close').click(function(){
                    $.modal.close();
                })
                
            }
        });

        return false;
    });    
   
}

showJobPreview = function () {
	
	for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement();

    $.ajax({
        url: websiteGlobal.fullUri+'/job_preview',
        type: 'POST',
        data: $('.form-standard').serialize(),
        success: function(data, status) {
        	
            $.modal(data, {
                close: true,
                position: ["5%",],
                onOpen: function (dialog) {
                    dialog.overlay.fadeIn('fast');
                    dialog.container.slideDown('fast', function () {   
                        dialog.data.fadeIn('fast'); 
                    });
                }
            });

            $('#simplemodal-overlay').click(function(){  $.modal.close(); });

            $('.modal-close').click(function(){ $.modal.close(); });
        }
    });
    
    return false;
}

function candidatesFormCustomSelect() {
    $('.custom-select .select-item').click(function() {
        // collect information of this item
        var idArray = $(this).attr('id').split('-');
        var name = $(this).find('label').html();
        var parent  = $(this).parent().parent();

        // if this item currently is in de deselected area
        // the user wants to select it so we will move it to the selected area
        if ($(parent).hasClass('form-custom-deselected')) {
            
            // find the parent's sibling (the selected area of this form item)
            // important if there are multiple custom-selects on the page
            var parentSibling  = parent.parent().find('.form-custom-selected');
            
            // get the siblings of the item that was clicked to put it in alphabetical order
            var siblingsArray = sortCustomSelect(parentSibling, $(this), name);

            // find our clicked item in the array.
            // look which item is one position higher in the array and we know 
            // after which item we should place our clicked item
            for (var i=0; i < siblingsArray.length; i++) {
                if (siblingsArray[i]['value'] == name && i != 0) {
                    var insertAfter = siblingsArray[i-1]['object'];
                    $(insertAfter).parent().after($(this));
                    
                }
                // if i = 0 we know that our clicked item should be the first item in the container
                // so we prepend it in the container
                else if (siblingsArray[i]['value'] == name && i == 0) {
                    parentSibling.find('.selectable-items').prepend($(this));
                }
            }
            
            // place a hidden field with the ID of the clicked item in the selected items container.
            var hiddenField = '<input class="input-hidden" type="hidden" value="'+ idArray[1] +'" name="elements['+ idArray[0] +'][page_ids]['+ idArray[1] +']" />';
            $(parentSibling).find('.selectable-items').append(hiddenField);
            
        } 
        // if this item currently is in de selected area 
        // the user wants to deselect it so we will move it to the deselected area
        else if ($(parent).hasClass('form-custom-selected')) {
            
            // find the parent's sibling (the deselected area of this form item)
            // important if there are multiple custom-selects on the page
            var parentSibling  = parent.parent().find('.form-custom-deselected');
            
            // get the siblings of the item that was clicked to put it in alphabetical order
            var siblingsArray = sortCustomSelect(parentSibling, $(this), name);
            
            // find our clicked item in the array.
            // look which item is one position higher in the array and we know 
            // after which item we should place our clicked item
            for (var i=0; i < siblingsArray.length; i++) {
                if (siblingsArray[i]['value'] == name && i != 0) {
                    var insertAfter = siblingsArray[i-1]['object'];
                    $(insertAfter).parent().after($(this));
                    
                }
                // if i = 0 we know that our clicked item should be the first item in the container
                // so we prepend it in the container
                else if (siblingsArray[i]['value'] == name && i == 0) {
                    $(parentSibling).find('.selectable-items').prepend($(this));
                }
            }
            // find the hidden field that matches the clicked item in the selected items container and remove it.
            var selectHiddenField = parent.find('input[value="' + idArray[1] + '"]');
            $(selectHiddenField).remove();

        }
        
    });

}

/**
 * Find labels of all children in the parent container
 * Put the array value column in alphabetical order
 * 
 * return   array
 */
function sortCustomSelect(parent, currentElement, name) {
    var siblingsArray = new Array();
    var counter = 0;
    
    $(parent).find('.select-item label').each(function() {
        siblingsArray[counter] = new Array();
        siblingsArray[counter]['value'] = $(this).html();
        siblingsArray[counter]['object'] = $(this);
        counter++;
    });
    siblingsArray[counter] = new Array();
    siblingsArray[counter]['value']  = name;
    siblingsArray[counter]['object'] = currentElement;
    siblingsArray.sort(sortByValue);
    
    return siblingsArray;
        
}

/**
 * Sort multidimentional array by value
 */
function sortByValue(a, b) {
    var x = a.value.toLowerCase();
    var y = b.value.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}


function keywordsFieldTrim() {
    $('#edit-keywords').blur(function () {
        var value = $(this).val();
        value = value.replace(/,/g, ' ');
        trimmedValue = value.replace(/  /g, ' ');
        $(this).val(trimmedValue);
    });
}
