/*
  using legacy jquery (1.3.2) as some jquery-ui widged cycled itself in $.extend function
*/
(function ($) {
$(document).ready(function () {
  /* menu autoresizing */
  if((container = $('.page-menu').filter(":eq(0)")).length > 0) {
    if(container.width() < $('#header').width()-41) // 40 = margin-left + margin-right of .main_menu + 1px?
      total_w = $('#header').width()-41; // IE6 must rely on menu ul container
    else
      total_w = container.width();
    children_width_new = container.getChildrenWidth();
    addPadding = Math.floor((total_w - children_width_new) / (container.children().filter(':not(.separator)').length * 2));
    children = container.children();
    children_width_new = 0;
    for(i=0;i<children.length;i++) {
      $(children[i]).find('>A>SPAN').each(function () {
        if($(this).parents('.submenu').length == 0) {
          padd = {paddingLeft: (myParseInt($(this).css('paddingLeft'))|0)+addPadding, paddingRight: (myParseInt($(this).css('paddingRight'))|0)+addPadding};
          $(this).css(padd);
          children_width_new += $(children[i]).outerWidth();
        }
      });
    }
    children_width_new = container.getChildrenWidth();
    to_add = total_w - children_width_new - 5;
    if(children.length == 1) {
      return;
    }
    child = children[0];
    paddingPlace = 'paddingLeft';
    while(to_add > 0 && child) {
      $(child).find('>A').each(function () {
        if($(this).parents('.submenu').length == 0) {
          o = $(this).find('SPAN');
          if(to_add >= 1) {
            $(o).css(paddingPlace, (myParseInt($(o).css(paddingPlace))|0) + 1);
          }
          to_add --;
        }
      });
      do {
        child = $(child).next();
      } while (child.is('.separator'));
      if(child == null || typeof child == 'object' && typeof child.length != 'undefined' && child.length == 0) {
        if(paddingPlace == 'paddingRight')
          paddingPlace = 'paddingLeft';
        else
          paddingPlace = 'paddingRight';
        child = children[0];
      }
      if(total_w - children_width_new == to_add) {
        break;
      }
    }
  }
  var submenu_offset = 6;
  zIndex_total = 2;
  $('.page-menu li.has-submenu').live('mouseover', function (event) {
    $(this).addClass('mouse-is-over');
    i = 0;
    par = $(event.originalTarget).parent();
    while (par != null && par.length > 0) {
      if($(par).hasClass('submenu'))
        return;
      if($(this).get(0) == $(par).get(0)) {
        break;
      }
      par = $(par).parent();
      i++;
      if(i > 100) {
        return;
      }
    }
    $(this).oneTime(10, function () {
      if($(this).hasClass('mouse-is-over')) {
        submenu_container = $($(this).children()).filter('.submenu-container');
        submenu_width = submenu_container.outerWidth();
        max_pos = $('ul.page-menu').position().left + $('ul.page-menu').width(); // we don't want to make menus over this position
        pos = $(this).position();
        /* now show menu on right side of previous menu */
        if($(this).parents('li.has-submenu').length != 0) {
          /* parent is vertical */
          parent_container = $(this).parents('div.submenu-container:eq(0)');
          pos.left = 0;
          pos.left = submenu_container.width();
          /* check if we are not over the edge */
          if($(this).offset().left + (submenu_container.outerWidth()+parent_container.outerWidth()) - submenu_offset > max_pos) {
            /* we are, move the menu to the left */
            pos.left -=  (submenu_container.outerWidth()) + (parent_container.outerWidth()) - submenu_offset;
          } else {
            pos.left -= submenu_offset;
          }
        } else {
          /* check if we are not over the edge */
          if(pos.left + submenu_width > max_pos) {
            pos.left = max_pos - submenu_width;
          }
          /* parent was horizontal */
          pos.top += $(this).height();
        }
        pos.position='absolute';
        pos.zIndex=zIndex_total++;
        pos.height='';
        submenu_container.css(pos).slideDown('slow');
      }
    })
  }).live('mouseout', function (event) {
    $(this).removeClass('mouse-is-over');
    $(this).oneTime(200, function() {
      if(!$(this).hasClass('mouse-is-over') && $(this).find('li.mouse-is-over').length == 0) {
        $($(this).children()).filter('.submenu-container').fadeOut('slow');
      }
      /* let parents know, we have left with the mouse */
      $(this).parents('li.has-submenu:not(.mouse-is-over)').mouseout();
    })
  });
  $('a.ico-quick-search').live('click', function () {
    if($(this).parent().hasClass('show-submenu')) {
      $(this).parent().find('.submenu').fadeOut('slow');
    } else {
      $(this).parent().find('.submenu').fadeIn('slow');
    }
    $(this).parent().toggleClass('show-submenu');
    return false;
  });
  if($('.accordion').length > 0) {
    $('.accordion').accordion({fillSpace: true, change: function () {
      // check if news tab is shown
      $('.accordion-content.ui-accordion-content-active UL:eq(0)').scrollingNews({anim_speed: 1000});
      $('.accordion-content:not(.ui-accordion-content-active) UL:eq(0)').scrollingNews({stop: 1});
    }});
    $('.accordion-content.ui-accordion-content-active UL:eq(0)').scrollingNews({anim_speed: 1000});
  }
  $('#TopBanner, .video-open').click(function () {
    params = $(this).parseClassToArray('params');
    src = params['src'];
    width = params['width'];
    height = params['height'];
    delete params['src'];
    delete params['width'];
    delete params['height'];
    var sa = new SWFObject(src, "vflash-video-container-popup", width, height,"9");
    for (i in params) {
      if(typeof params[i] == 'string')
        sa.addParam(i, params[i]);
    }
    variables = $(this).parseClassToArray('variables');
    for (i in variables) {
      if(typeof variables[i] == 'string')
        sa.addVariable(i, variables[i]);
    }
    if($.browser.msie)
      sa.addParam('FlashVars', 'autostart=0'+/*variables['autostart']+*/'&controlbar='+variables['controlbar']+'&file='+variables['file']+'&image='+variables['image']);
    //autostart=true&controlbar=none&file=http://nela/courses4u/files/video/Madonna - frozen.flv&image=http://nela/courses4u/files/images/madonna-frozen.jpg
    $('#video_container').remove();
    $('<div id="video_fancy_container"><div id="video_fancy_container_inner"></div></div>').css({display: 'none'}).appendTo('BODY');
    $('<a href="#video_fancy_container"></a>').fancybox({hideOnContentClick: false, frameHeight: height, frameWidth: width, callbackOnClose: function () {
      $('#fancy_div').attr('innerHTML','');
      $('body').removeClass('lightbox-shown');
    }}).click();
    $('body').addClass('lightbox-shown');
    if(variables['autostart'] == '1')
      $(document).oneTime(1000, function () {
        if(typeof $('#vflash-video-container-popup').get(0).sendEvent != 'undefined')
          $('#vflash-video-container-popup').get(0).sendEvent('PLAY', 'true');
      });
    sa.write('video_fancy_container_inner');
    $('#video_container, body>#video_fancy_container').remove();
  });

});

// *****************
// * Tracking clicks within the page
// *****************
$(document).ready(function() {
  $('a').live('click', function () { // track events (external link click, mailto click, pdf click)
    if(typeof settings_google_analytics_code != 'undefined' && typeof _gat != 'undefined'){
      //_gaq.push(['_trackPageview'], $(this).attr('href'));
      var filetypes_track = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
      var pageTracker = _gat._getTracker(settings_google_analytics_code);
      var href = $(this).attr('href');
      if ((href.match(/^https?\:/i)) && (!href.match(document.domain))){
        var extLink = href.replace(/^https?\:\/\//i, '');
        pageTracker._trackEvent('External', 'Click - external link', extLink);
      }else if (href.match(/^mailto\:/i)){
        var mailLink = href.replace(/^mailto\:/i, '');
        pageTracker._trackEvent('Email', 'Click - mailto', mailLink);
      }else if (href.match(filetypes_track)){
        var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
        filePath = href.replace(new RegExp('^https?\:\/\/'+document.domain+'\/', "i"), '/');
        pageTracker._trackEvent('Download', 'Click - ' + extension, href);
      }
    }
  });
});


$.extend($.fn, {
  /**
  * parseClassToArray(): parses element's class and returns known elements as array
  * @param String prefix: class prefix
  * example:
  *  elements class = 'blah--name--value blah--name2--val'
  *  out = $(element).parseClassToArray('blah')
  *  output: object:{name: 'value', name2: 'val'};
  */
  parseClassToArray: function (prefix) {
    out = {};
    cl = $(this).attr('class');
    if(typeof cl == 'undefined')
      cl = $(this).attr('className');
    if(typeof cl != 'undefined' && cl.length > 0) {
      classes = cl.split(' ');
      reg=/^\-\-(.*)$/;
      for(i=0;i<classes.length;i++) {
        cl = $.trim(classes[i]);
        if(cl.indexOf(prefix) == 0){
          cl = cl.substr(prefix.length);
          if((preg = reg.exec(cl)) && preg[1].length > 0) {
            pos = preg[1].indexOf('--');
            if(pos > 0) {
              out[unescape((''+preg[1]).substr(0, pos))] = unescape((''+preg[1]).substr(pos+2));
            } else {
              out[out.length] = unescape(preg[1]);
            }
          }
        }
      }
    }
    return out;
  },
  getChildrenWidth: function () {
    children = $(this).children();
    total = 0;
    for(i=0;i<children.length;i++) {
      total += $(children[i]).width()+myParseInt($(children[i]).css('marginLeft'))+myParseInt($(children[i]).css('marginRight'))+myParseInt($(children[i]).css('paddingLeft'))+myParseInt($(children[i]).css('paddingRight'));
    }
    return total;
  },
  calcChildrenSize: function (size_type) {
    if(!this || $(this).length != 1) return 0;
    if(!size_type) size_type = 'width';
    total_size = 0;
    this.children().each(function () {
      if(size_type == 'width') { total_size += $(this).outerWidth(); }
      else { total_size += $(this).outerHeight(); }
    });
    return total_size;
  },
  scrollingNews: function(new_options) {
    return this.each(function () {
      /* default options */
      options = { fade_speed: 'slow', anim_speed: 2000, change_time: 5000, stop: 0 };

      /* is there some previous options on this container? */
      options2 = $(this).data('scrollingNews');
      if (typeof options2 != 'undefined' && options2 != null && options2.length > 0)
        $.extend(options, options2);

      if (options && options2 && typeof options2.scrolling_news_id != 'undefined' && typeof options.scrolling_news_id == 'undefined') {
        options.scrolling_news_id = options2.scrolling_news_id;
      }

      /* some options were set in initialization */
      $.extend(options, new_options);

      $(this).stopTime('scrollingNews_'+(options.scrolling_news_id));
      if(options.stop == 1) {
        /* we should stop the timer */
        return this;
      } else {
        $(this).css('overflow', 'hidden');
      }

      /* is the box smaller than it's content? */
      if($(this).calcChildrenSize('height') <= $(this).height() && $(this).calcChildrenSize('height') <= $(this).parent().height()) {
        return;
      }

      /* add/remove mouse-is-over */
      $(this).mouseover(function () { $(this).addClass('mouse-is-over'); }).mouseout(function () { $(this).removeClass('mouse-is-over'); })
      if(typeof options.scrolling_news_id == 'undefined' || options.scrolling_news_id.length == 0) {
        if(typeof $.scrollingNewsI == 'undefined') $.scrollingNewsI = 0;
        options.scrolling_news_id = ++$.scrollingNewsI;
      }

      /* set the options to the container */
      $(this).data('scrollingNews', options);

      /* the loop */
      $(this).everyTime(options.change_time, 'scrollingNews_'+(options.scrolling_news_id), function() {
        if($('BODY').hasClass('lightbox-shown'))
          return;
        options = $(this).data('scrollingNews');
        if(!$(this).hasClass('mouse-is-over')) {
          /* do the animation */
          children = $(this).children(); //cont1 children

          /* we want to put the first at the end */
          $(this).append($(children[0]).clone(true).fadeOut(0).fadeIn(options.fade_speed));
          $(children[0]).fadeTo(options.fade_speed, 0, function() {
            $(this).css({lineHeight: 1, fontSize: 1, height: $(this).height()}).animate({height: 1}, options.anim_speed, function () {
              $(this).remove();
            })
          });
        }
      });
      return this;
    });
  }
});
})(jQuery);

function myParseInt(int) {
  o = parseInt(int);
  if(isNaN(o))
    return 0;
  return o;
}
