
/**********************************
 *
 * TinyMCE
 *
 **********************************/

tinyMCE.init({
    mode : "exact",
    elements : "message, motivation, reply, company_description, candidate_description, job_description, bedrijfDescription,description,werkzaamheden,idolDescription,txt_description,txt_bedrijfDescription,txt_idolDescription,txt_overig,txt_reactie,txt_reageer_sollicitatie,txt_contact_bericht",
    theme : "advanced",
    theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,bullist,numlist,undo,redo,link,unlink",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    //width : "350",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    // theme_advanced_path_location : "bottom",
    extended_valid_elements : "a[name|href|target|title|onclick]",
    forced_root_block : false
});


/**********************************
 *
 * Selection
 *
 **********************************/

toggleSelection = function(element, holder)
{
    var toggle = element.checked;
    selector = '.' + holder + ' input[type=checkbox]';
    $$(selector).each(function(check) {
            check.checked = toggle;
    });
}

function updateReplyText(element)
{
    $.ajax({
        url: $(element).attr('url'),
        data: ({status: $(element).val()}), // the element has an application status id as a select value.
        start: tinyMCE.activeEditor.setContent('<img src="' + $(element).attr('loading_image_url') + '" />'),
        success: function(html) {
            tinyMCE.activeEditor.setContent(html);
        }
    });

}

/**
 * Function used in conjunction with jCrop.
 *
 * After the image is cropped in jCrop, the coordinates are
 * given to the hidden form. This form is then submitted in
 * the Zend Framework controller. That controller also
 * houses the image processing.
 *
 */
function showCropCoords(c)
{
    // Just set the form values
    // Processing is on server side
    jQuery('[name=x]').val(c.x);
    jQuery('[name=y]').val(c.y);
    jQuery('[name=w]').val(c.w);
    jQuery('[name=h]').val(c.h);
}

function copyBillingInformation(element) {
    if(element.checked) {
        var values = $.parseJSON($('#json').val());

        $('#invoice_street').val(values.street);
        $('#invoice_number').val(values.housenumber);
        $('#invoice_zipcode').val(values.zipcode);
        $('#invoice_city_id').val(values.city_id);
        $('#invoice_country_id').val(values.country_id);
    }
    else {
        $('#invoice_street').val('');
        $('#invoice_number').val('');
        $('#invoice_zipcode').val('');
        $('#invoice_city_id').val('');
        $('#invoice_country_id').val('161');
    }
}

function goToApplications(select)
{
	url = $(select).value;
	window.location = url;
}

$(function() {
    $( "#tabs" ).tabs({
//            event: "mouseover",
//            cookie: {
//                    // store cookie for a day, without, it would be a session cookie
//                    expires: 1
//            }
    }).find( ".ui-tabs-nav" ).sortable({ axis: "x" });

    if ($('#feedback_button')) {
        $("#feedback_button").bind("mouseover", onFeedbackButton);
        $("#feedback_button").bind("mouseout", offFeedbackButton);
        $('#feedback_button').animate({opacity: 0.4}, 0);
    }
    if ($('#company_help')) {
        $("#company_help").bind("click", openHelp, false);
        $("#company_help_close").bind("click", closeHelp, false);
        $("#comapny_help_contact_link").bind("click", goToContact, false);
        $('#company_help').animate({opacity: 0.4}, 0);
        $("#company_help_close").hide();
    }

    $(".qweeryDefault").each(function(){
        $(this).focus(function(){
            if($(this).val() == "Vul trefwoorden in (bijv. horeca, utrecht)"){
                $(this).val("");
                $(this).css("color", "#000000");
            }
        }).blur(function(){
            if($(this).val() == ""){
                $(this).val("Vul trefwoorden in (bijv. horeca, utrecht)");
                $(this).css("color", "#707070");
            }
        });
    });

    if(!Modernizr.input.placeholder){

        $('[placeholder]').focus(function() {
          var input = $(this);
          if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
          }
        }).blur(function() {
          var input = $(this);
          if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
          }
        }).blur();
        $('[placeholder]').parents('form').submit(function() {
          $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
              input.val('');
            }
          })
        });
    }

});

$(window).load(function() {
    if ($('#homepage-banner').length != 0) {
        $('#homepage-banner').orbit({
             animation: 'fade',                  // fade, horizontal-slide, vertical-slide, horizontal-push
             animationSpeed: 1200,                // how fast animtions are
             timer: true, 			 // true or false to have the timer
             advanceSpeed: 4000, 		 // if timer is enabled, time between transitions
             pauseOnHover: false, 		 // if you hover pauses the slider
             startClockOnMouseOut: false, 	 // if clock should start on MouseOut
             startClockOnMouseOutAfter: 1000, 	 // how long after MouseOut should the timer start again
             directionalNav: false, 		 // manual advancing directional navs
             captions: true, 			 // do you want captions?
             captionAnimation: 'fade', 		 // fade, slideOpen, none
             captionAnimationSpeed: 800, 	 // if so how quickly should they animate in
             bullets: false,			 // true or false to activate the bullet navigation
             bulletThumbs: false,		 // thumbnails for the bullets
             bulletThumbLocation: ''		 // location from this file where thumbs will be
        });
    }
});

$(document).ready(function() {

    // Image cropper
    $('#cropbox').Jcrop({
        //minSize: [120,60],
        //aspectRatio: 2,
        onSelect: showCropCoords
        //onChange: showCoords
    });

    //Init Lightbox;

   $("a.popup").fancybox({
       'hideOnContentClick': true,
       'titleShow' :	true
   });

    $("a.popupLogin").fancybox({
   });
    $("a.vacancyPreviewFancybox").fancybox({
        'hideOnContentClick': true,
        'titleShow' :	true
    });


    $("a.google_maps").fancybox({
        'onComplete':function() {
            google.maps.event.trigger(map, 'resize');
            map.setZoom( map.getZoom() - 1 );
        }
    });

    $("a.feedback").fancybox({
   });

   $("a.invite_flag").fancybox();

    // Toggle
    $('.toggle').click(function() {

        var target;

        if($(this).attr('rel')) {
            id = $(this).attr('rel')
            target = $('#' + id);
        }
        else {
            target = $(this).next();
        }

        target.toggle();

        if(target.is(':visible')) {
            $(this).removeClass('toggle-show');
            $(this).addClass('toggle-hide');
        }
        else {
            $(this).removeClass('toggle-hide');
            $(this).addClass('toggle-show');
        }

        return false;
    });

    // Menu
//   $('ul.sf-menu').superfish({
//        hoverClass:    'sfHover',
//        animation:   {opacity:'show', height:'show'},  // fade-in and slide-down animation
//        delay:       10000,                            // one second delay on mouseout
//        speed:       'fast',                          // faster animation speed
//        autoArrows:  false,                           // disable generation of arrow mark-up
//        dropShadows: true                            // enable drop shadows
//   });

   //Init maskedinput (user-create)
   $('input.mask_date').each(function(){
       $(this).mask('99-99-9999');
   });

   //Init maskedinput for mobile phone number (user-create)
   $('input.mask_mobile').each(function(){
       $(this).mask('06-99999999');
   });

  //Init maskedinput for zipcode (user-create)
   $('input.mask_zipcode').each(function(){
       $(this).mask('9999aa');
       $(this).blur(function(){$('#zipcode').val($('#zipcode').val().toUpperCase())});
   });

   //Init zipcode lookup
   $('input.getAddress').each(function(){
       $(this).blur(function(){
           fetchCityAndStreet();
        });
   });

   $('input.switch').change(function(){
       var target = '#' + $(this).attr('rel');
       if ($(target).is(":hidden") && $(this).val() == '1') {
           $(target).slideDown('slow');
       } else {
           $(target).slideUp('slow');
       }
   });

   $('select#education_level').change(function(){
       //Get the selected education_level id
       var id = $(this).val();
       //target div to show/hide
       var target = $('#education_direction_holder');

       //Only show the div when MBO/HBO/WO is selected, otherwise close
       if (id == 90 || id == 91 || id == 92)  {
           //Fetch the ajax url, which returns a json list
           var url = $(this).attr('rel');

           // Remove all current options from the education_direction selectbox and
           // adds the new ones, retrieved by JSON
           $('#education_direction').removeOption(/./).ajaxAddOption(url, {
             name: 'Opleiding1',
             key: id
           }, false);

           // Show div if needed
           if (target.is(':hidden')) {
             target.slideDown('slow');
           }
       } else {
           target.slideUp('slow');
       }

       var education_holder = $('#education_holder');
        //If MBO/HBO/WO is selected also show education selectbox
       if (id == 90 || id == 91 || id == 92)  {
           // Show div if needed
           if (education_holder.is(':hidden')) {
             education_holder.slideDown('slow');
           }
       } else {
          education_holder.slideUp('slow');
       }
   });


   $('select#education_direction').change(function(){
       //Get the selected education_direction id
       var id = $(this).val();

       //Fetch the ajax url, which returns a json list
       var url = $(this).attr('rel');

       // Remove all current options from the education_direction selectbox and
       // adds the new ones, retrieved by JSON
       $('#education').removeOption(/./).ajaxAddOption(url, {
         name: 'Opleiding2',
         key: id
       }, false);

   });

});


function fetchCityAndStreet()
{
   $.getJSON("/shared_public/ajaxRequest.php", {
       action: 'address',
       zipcode: $('#zipcode').val(),
       number: $('#housenumber').val()
    }, function(data){
        $('#street').val(data['straatnaam']);
        var city = data['plaatsnaam']
        $('#city').val(city);

        // Try to select the city for useability
        $('#city_id').find('option').each(function() {
            if ($(this).text().toLowerCase() == city.toLowerCase()){
                $('#city_id').val($(this).val());
            }
        });

    });
}

function setPlaceholders() {
    $(".clearDefault").each(function(){
        var default_value = $(this).val();
        var default_color = $(this).css("color");
        $(this).focus(function(){
            if($(this).val() == default_value){
                $(this).val("");
                $(this).css("color", "#000000");
            }
        }).blur(function(){
            if($(this).val() == ""){
                $(this).val(default_value);
                $(this).css("color", default_color);
            }
        });
    });
}



$(setPlaceholders);

/** MULTI BUTTONS **/

// some required vars
mbTimeout = 500;
mbButton = undefined;
openButtonTimer = undefined;
closeButtonTimer = undefined;

// open one
function openButtons(id) {
    // close currently opened button
    if (mbButton != id) {
        closeButton();
    }
    // open button
    $('#' + id).children('.multi_button_extension').show();
    // set this one as the opened one
    mbButton = id;
}

// close on delay
function timeOpenButton(id) {
    openButtonTimer = window.setTimeout('openButtons("' + id + '")', mbTimeout);
}

// remove close delay
function cancelOpenButton() {
    if (openButtonTimer) {
        window.clearTimeout(openButtonTimer);
        openButtonTimer = undefined;
    }
}

// actually closes a button
function closeButton() {
    if (mbButton != undefined) {
        $('#' + mbButton).children('.multi_button_extension').hide();
    }
    mbButton = undefined;
}

// close on delay
function timeCloseButton() {
    closeButtonTimer = window.setTimeout(closeButton, mbTimeout);
}

// remove close delay
function cancelCloseButton(id) {
    if (closeButtonTimer) {
        window.clearTimeout(closeButtonTimer);
        closeButtonTimer = undefined;
    }
    // open this button if another is allready opened (open on slide-to)
    if (mbButton != undefined && mbButton != id) {
        openButton(id);
    }
}

function bindLoginForm() {
    $("#form-login").bind("submit", function() {

        if ($("#email").val() == 'E-mailadres' || $("#password").val() == 'password') {
            $("#login_error").show();
            $.fancybox.resize();
            return false;
        }

        $.fancybox.showActivity();

        $.ajax({
                type : "POST",
                cache : false,
                url : $("#base_path").val() + "/inloggen",
                data : $(this).serializeArray(),
                success: function(data) {
                    if (data.indexOf('succesvol') >= 0 ) {
                        setTimeout(function() {
                            $.fancybox.close()
                            parent.location.reload(true);
                        }, 1500);
                    }
                    $.fancybox(data);
                }
        });

        return false;
    });
}
function bindInviteForm() {
    $("#form-company-invite-candidate").bind("submit", function() {

        $.fancybox.showActivity();

        $.ajax({
                type : "POST",
                cache : false,
                url : $("#url").val(),
                data : $(this).serializeArray(),
                success: function(data) {
                    if (data.indexOf('De kandidaat is uitgenodigd!') > 0 ) {
                        setTimeout(function() {
                            $.fancybox.close()
                            parent.location.reload(true);
                        }, 3000);
                    }
                    $.fancybox(data);
                }
        });

        return false;
    });
}
function bindFeedbackForm() {
    $("#feedback-form").bind("submit", function() {

        if ($("#feedback").val() == '') {
            $("#feedback_error").show();
            $.fancybox.resize();
            return false;
        }

        $.fancybox.showActivity();

        $.ajax({
                type : "POST",
                cache : false,
                url : $("#base_path").val() + "/feedback",
                data : $(this).serializeArray(),
                success: function(data) {
                        setTimeout(function() {
                            $.fancybox.close()
                        }, 3000);

                    $.fancybox(data);
                }
        });

        return false;
    });
}

function googleMaps(location, icon) {
    // init center latlng location
    var workLocation = new google.maps.LatLng(52.469397,5.509644);
    // init marker
    var marker = undefined;
    // init zoom
    var zoom = 5;
    // init geocoder
    var geocoder = new google.maps.Geocoder();
    // compose map options with location
    var mapOptions = {
        zoom: zoom,
        center: workLocation,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    // get the map
    var map = new google.maps.Map(document.getElementById("google_map_canvas"), mapOptions);
    // find location with geocoder
    geocoder.geocode(
        {'address': location},
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                workLocation = results[0].geometry.location;
                // set center and zoom in
                map.setCenter(workLocation);
                map.setZoom(12);
                // add a marker
                var marker = new google.maps.Marker({
                    map: map,
                    position: workLocation,
                    icon: icon
                });
            }
        }
    );
}

function onFeedbackButton() {
    if ($('#feedback_button')) {
        $('#feedback_button').stop(true, false).animate({left: '-180px', opacity: 1}, 200);
    }
}
function alertFeedBackButton(){
    if ($('#feedback_button')) {
        $('#feedback_button').stop(true, false).delay(3000).animate({left: '-50px', opacity: 1}, 200).delay(800).animate({opacity: 0.3}, 350).animate({opacity: 1}, 350)
        .delay(1200).animate({left: '-200px', opacity: 0.4}, 400);
    }
}
function offFeedbackButton(duration) {
    if ($('#feedback_button')) {
        $('#feedback_button').stop(true, false).animate({left: '-200px', opacity: 0.4}, 400);
    }
}

function closeHelp() {
    $('#company_help_close').hide();
    $('#company_help').stop(true, false).animate({left: '-360px', opacity: 0.4}, 200);
    return false;
}
function openHelp() {
    $('#company_help').stop(true, false).animate({left: '-10px', opacity: 1}, 200);
    $('#company_help_close').show();
    return false;
}

function goToContact(){
    window.location = 'http://www.bijbanen.nl/bedrijf/contact';
}
