var bedankt_text    = 'Bedankt!';
var incorrect_text  = 'Incorrect email!';

var cookie_expires  = 7;
var slider_start = 0;

var scrollPane;
var scroll_api;

$(document).ready(function(){
  
  
  $('div#main_menu ul li.menu_item:has(div.menu_item_content)').each(function(){
    var child_submenu = $(this).children('.menu_item_content');
    if( $(this).outerWidth() > $(child_submenu).outerWidth() ){
      $(child_submenu).width( $(this).outerWidth() );
    }
  });
  
  
  
  // Index page cycle slider
  if($("#j_cycle").length){
    if($(".cycle_item").length > 1){        
      // If count items is more than 1 - start cycling
      $('#j_cycle').cycle({
          fx:      'fade',    // changer effect
          pause:    0,        // pause on hover
          timeout:  autostart_caroussel,        // for test pause
          speed:    400,      // ms for effect
      //    startingSlide: start_slide_caroussel,
          startingSlide: slider_start,
          prev:    '#prev',
          next:    '#next',
          pager:   '#nav',
          pagerAnchorBuilder: function(idx, slide){
            var img = $(slide).find('img');
            var count = $(".cycle_item").length - 1;
            var add_class = '';
            
            if( count == idx ){
              add_class = 'class="last"';
            }
            
            return '<a ' + add_class + ' href="#"><img id="link_' + $(img).attr('id') + '" src="/file/' + $(img).attr('name') + '?height=30" /></a>'; //width=45&
          }
      });
    }else{
      // If only one item = hide controls
      $("#prev a").css('background', 'none');
      $("#nav a").css('background', 'none');
      $("#next a").css('background', 'none');
    }
  }
  
  
  // Separate page text on 2 columns
  var wide_text = $('.wide_text');
  
  
  
  if( !$(wide_text).hasClass('single_column') ){
    
    $('div.man_team').addClass("dontsplit");
    
    var col_config = {};
    col_config.columns = 2;
    col_config.dontsplit =".map_item";
    
    if( location.pathname != "/read/contact" )
    {
      col_config.balance = false;
    }
    
    
    wide_text.columnize( col_config );
  }
  
  
  
  
  
  
  
  
  
  /////////////////////////////////////////////////////////////////
  // Show 'intro movie' item in carousel only with first visit 
  /*var visited = $.cookie('visited');
  var video_id; 
  
  if($('#j_cycle .cycle_item').length){
    
    $('#j_cycle .cycle_item:first p').each(function(){
      if( $(this).attr('id') != null && $(this).attr('id') != '' && video_id != '' ){
        video_id = $(this).attr('id');
      }
    });
    
    if( visited != null && visited == video_id ){
      // Hide first item in carousel
      //$('#j_cycle .cycle_item:first').remove();
      slider_start = 1;
    }else{
      $.cookie('visited', video_id, { expires: cookie_expires });
    }
  }*/
  
  
  
  
  
  /////////////////////////////////////////////////////////////////
  // Search block hover fix (background change)
  $("#srch_block input[type=button], #srch_block input[type=submit]").hover(
    function(){
      $(this).prev().addClass('hover_srch_block');
    },
    function(){
      $(this).prev().removeClass('hover_srch_block');
    }
  );
  
  /////////////////////////////////////////////////////////////////
  // Search field
  var search_field  = "input[name=search]";
  var search_text   = "Vul hier een zoekterm in";
  var search_hint   = $(search_field).attr('title');
  
  // Hint for search field
  $(search_field).Watermark(search_hint);
  
  // On search form submit - check if search field text != search hint
  $('form#search_form').submit(function(){
    if($(search_field).val() == search_hint || $(search_field).val() == search_text){
      $(search_field).val('');
    }
  });
  
  $(search_field).hover(
    function(){
      if($(this).val() == search_hint){
        $(this).val(search_text);
      }
    }, function(){
      if($(this).val() == search_text){
        $(this).val('');
        $(this).Watermark(search_hint);
      }
    }
  );
  $(search_field).click(function(){
    if($(this).val() == search_text){
      $(this).val('');
    }
  });
  
  
  /////////////////////////////////////////////////////////////////
  // Subscribe field
  var subscribe_field = 'input[name=subscribe]';
  var subscribe_text  = 'Wat is je mailadres?';
  var subscribe_hint  = $(subscribe_field).attr('title');
  
  // Hint for subscribe field
  $(subscribe_field).Watermark(subscribe_hint);
  
  // On subscribe field hover - show question string, on click - set empty field value
  $(subscribe_field).hover(
    function(){
      if($(this).val() == subscribe_hint){
        $(this).val(subscribe_text);
      }
    }, function(){
      if($(this).val() == subscribe_text){
        $(this).val('');
        $(this).Watermark(subscribe_hint);
      }
    }
  );
  $(subscribe_field).click(function(){
    if($(this).val() == subscribe_text || $(this).val() == bedankt_text || $(this).val() == incorrect_text){
      $(this).val('');
    }
  });
  
  
  /////////////////////////////////////////////////////////////////
  // Left menu subtext
  if($('.descr').length){
    var body_height = $('div#body').height() - 10; // Making extra space for padding 
    
    
    $.each($('.descr').get().reverse(), function(key, value){ // backward each loop
      // Each time check main menu height
      var main_menu = $('div#main_menu').height() + parseInt($('#main_menu').css('padding-top')) + parseInt($('#main_menu').css('padding-bottom'));
      // Possible height of main menu with current block 
      var tmp_height = main_menu + $(value).height();
      
      // Check, if possible height is lower or equal to div#body height
      if( tmp_height <= body_height ){
        $(value).css('display', 'block');
      }
    });
  }
  
  
  
  /////////////////////////////////////////////////////////////////
  // Index page cycle slider
  /*if($("#j_cycle").length){
    if($(".cycle_item").length > 1){
      // If count items is more than 1 - start cycling
      $('#j_cycle').cycle({
          fx:      'fade',    // changer effect
          pause:    0,        // pause on hover
          //timeout:  0,        // for test pause
          speed:    400,      // ms for effect
          timeout:  12000,     // ms between changing
          startingSlide: slider_start,
          prev:    '#prev',
          next:    '#next',
          pager:   '#nav',
          pagerAnchorBuilder: function(){
            return '<a href="#">&nbsp;</a>';
          }
      });
    }else{
      // If only one item = hide controls
      $("#prev a").css('background', 'none');
      $("#nav a").css('background', 'none');
      $("#next a").css('background', 'none');
    }
  }*/
  
  
  /////////////////////////////////////////////////////////////////
  // Setting position for page image
  /*var div_page_text = $('.page_text_p');
  var div_page_image = $('#page_image');*/
  
  /*if(div_page_text.length && div_page_image.length && location.pathname.indexOf('over-mtnl') > 0){
    
    var page_text = $(div_page_text).html();
    // Split by <br>
    //page_text_ar = page_text.split(/<br[^>]*>/);
    page_text_ar = page_text.split("</p>");
    
    
    if($.browser.msie && location.pathname == "/read/over-mtnl"){
      //page_text_ar = page_text_ar.toString().split('\n');
    }
    
    
    // Clear page_text
    $(div_page_text).html('');
    
    
    
    $(page_text_ar).each(function(index, value){
      
      var el_val = trim(strip_tags(value, '<br><br/>'));
      
      // Append each paragraph in place
      $('.page_text_p').append("<p>" + el_val + "</p>");
      
      // Insert page image after second element
      if( index == 0 || page_text_ar.length < 2 ){ $('.page_text_p').append( $(div_page_image) ); }
      
    });
  }*/
  
  
  
  /////////////////////////////////////////////////////////////////
  // Custom scroller
  /*
  scrollPane = $('#container');
  
  if(scrollPane.length){
    scrollPane.jScrollPane({
        verticalDragMinHeight: 22,
        verticalDragMaxHeight: 22,
        showArrows: false
    });
    
    scroll_api = scrollPane.data('jsp');    
    setTimeout(function(){ scroll_api.reinitialise();  },  1500);
  }
  */
  
  /////////////////////////////////////////////////////////////////
  // Moder links
  /*var edit_links = $('a.editpage_link, a.addpage_link');
  
  if(edit_links.length){
    $(edit_links).bind('click', function() {
      var win_width   = $(document).width() - 200;
      var win_height  = $(document).height() - 100;
      
      openDiv( this.href, win_width, win_height, true);
      return false;
    });
  }*/
  
  
  if($('.p_contact_info').length){
    $('.p_contact_info').each(function(){
      var paragraph_text = strip_tags($(this).html()).replace(/(^\w+)/,'<strong>$1</strong>').split('\n');
      paragraph_text = "<p>" + paragraph_text.join('</p><p>') + "</p>";
      $(this).html( paragraph_text );
    });
    
  }
  
  $('.cycle_item a').click(showSLVideo);
  $('#cycle_nav_container a').click(closeSLVideo);
  
});


function findVideo(video_id){
  var th_link = $('#nav img[id*="' + video_id + '"]');
  th_link = $(th_link).parent('a');
  th_link.click();
  var nav_link = $('#j_cycle img[id*="' + video_id + '"]');
  nav_link = $(nav_link).parent('a');
      $('#j_cycle').cycle('pause');
  nav_link.click();
 
  return false;
}


function showSLVideo(){
  $(this).hide();
  $(this).addClass('thisisthis');
  var parent_el = $(this).parent('div.cycle_item');
  var video_source = parent_el.find('.video_source');
  video_source.show();

  $('#j_cycle').cycle('pause');
  return false;
}

function closeSLVideo(){
  $('#j_cycle').cycle('resume');
  $('.cycle_item a').show();
  $('.cycle_item div.video_container').html('');
}



function scrollToEl(el_id){
  if( $('#' + el_id).length ){
    scroll_api.scrollToElement( $('#' + el_id), true, true );
  }
  return false;
}






function doSubscribe(){
  var email = $('input[name=subscribe]').val();
  if(email != '' && checkemail(email)){
    
    params_obj = {
      form: 299,
      fields: {
        'E-mail': email
      }, 
      options: {
        react_id: 'new'
      }
    };
    
    var params_string = 'task=ajax_actions&module=react&act=save_react&params=' + jQuery.toJSON(params_obj);
    
    
    /*
    $save_stat_href ='/?task=ajax_actions&module=react&act=save_react&params='.htmlspecialchars(json_encode($params)).'&redir='.$_['REQUEST_URI'];
    */
    
    /*$.ajax({
      type: "GET",
      url: '/',
      data: params_string,
      
      success: function(data){
        //alert('sent');
        //alert(data);
        //alert('Load was performed.');
        $('input[name=subscribe]').val(bedankt_text);
      }
    });*/
    
    
  }else{
    $('input[name=subscribe]').val(incorrect_text);
  }
  //window.location.href = document.form1.text1.value;
}


function checkemail(str){
  var filter=/^.+@.+\..{2,3}$/;
  
  if (filter.test(str)){
    return true;
  }else{
    return false;
  }
}


























(function($) {
    /** jQuery.toJSON( json-serializble )
        Converts the given argument into a JSON respresentation.

        If an object has a "toJSON" function, that will be used to get the representation.
        Non-integer/string keys are skipped in the object, as are keys that point to a function.

        json-serializble:
            The *thing* to be converted.
     **/
    $.toJSON = function(o)
    {
        if (typeof(JSON) == 'object' && JSON.stringify)
            return JSON.stringify(o);
        
        var type = typeof(o);
    
        if (o === null)
            return "null";
    
        if (type == "undefined")
            return undefined;
        
        if (type == "number" || type == "boolean")
            return o + "";
    
        if (type == "string")
            return $.quoteString(o);
    
        if (type == 'object')
        {
            if (typeof o.toJSON == "function") 
                return $.toJSON( o.toJSON() );
            
            if (o.constructor === Date)
            {
                var month = o.getUTCMonth() + 1;
                if (month < 10) month = '0' + month;

                var day = o.getUTCDate();
                if (day < 10) day = '0' + day;

                var year = o.getUTCFullYear();
                
                var hours = o.getUTCHours();
                if (hours < 10) hours = '0' + hours;
                
                var minutes = o.getUTCMinutes();
                if (minutes < 10) minutes = '0' + minutes;
                
                var seconds = o.getUTCSeconds();
                if (seconds < 10) seconds = '0' + seconds;
                
                var milli = o.getUTCMilliseconds();
                if (milli < 100) milli = '0' + milli;
                if (milli < 10) milli = '0' + milli;

                return '"' + year + '-' + month + '-' + day + 'T' +
                             hours + ':' + minutes + ':' + seconds + 
                             '.' + milli + 'Z"'; 
            }

            if (o.constructor === Array) 
            {
                var ret = [];
                for (var i = 0; i < o.length; i++)
                    ret.push( $.toJSON(o[i]) || "null" );

                return "[" + ret.join(",") + "]";
            }
        
            var pairs = [];
            for (var k in o) {
                var name;
                var type = typeof k;

                if (type == "number")
                    name = '"' + k + '"';
                else if (type == "string")
                    name = $.quoteString(k);
                else
                    continue;  //skip non-string or number keys
            
                if (typeof o[k] == "function") 
                    continue;  //skip pairs where the value is a function.
            
                var val = $.toJSON(o[k]);
            
                pairs.push(name + ":" + val);
            }

            return "{" + pairs.join(", ") + "}";
        }
    };

    /** jQuery.evalJSON(src)
        Evaluates a given piece of json source.
     **/
    $.evalJSON = function(src)
    {
        if (typeof(JSON) == 'object' && JSON.parse)
            return JSON.parse(src);
        return eval("(" + src + ")");
    };
    
    /** jQuery.secureEvalJSON(src)
        Evals JSON in a way that is *more* secure.
    **/
    $.secureEvalJSON = function(src)
    {
        if (typeof(JSON) == 'object' && JSON.parse)
            return JSON.parse(src);
        
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        
        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };

    /** jQuery.quoteString(string)
        Returns a string-repr of a string, escaping quotes intelligently.  
        Mostly a support function for toJSON.
    
        Examples:
            >>> jQuery.quoteString("apple")
            "apple"
        
            >>> jQuery.quoteString('"Where are we going?", she asked.')
            "\"Where are we going?\", she asked."
     **/
    $.quoteString = function(string)
    {
        if (string.match(_escapeable))
        {
            return '"' + string.replace(_escapeable, function (a) 
            {
                var c = _meta[a];
                if (typeof c === 'string') return c;
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + string + '"';
    };
    
    var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    
    var _meta = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };
    
})(jQuery);
