var ImageLoader = new Class({

	initialize: function(el) {
		this.element = $(el);
		this.image = (this.element.get('tag') == 'img')
			? this.element
			: this.element.getElement('img');
		if (!this.image) return;
		this.originalSrc = this.image.src;
		if (this.image.naturalWidth !== undefined) {
			if (this.image.naturalWidth) return;
		}
		else if (this.image.complete) return;
		this.element.addClass('loading');
		this.loader = new Image();
		this.loader.onload = this.onLoad.bind(this);
		this.loader.onerror = this.onError.bind(this);
		this.loader.src = this.originalSrc;
	},
	
	complete: function() {
		this.image.src = this.loader.src;
		this.element.removeClass('loading');
	},
	
	onError: function() {
		this.retry.delay(5000, this);
	},
	
	onLoad: function() {
		this.complete();
	},
			
	retry: function() {
		this.loader.src = this.originalSrc + (this.originalSrc.indexOf('?') < 0 ? '?' : '&') + 'ts=' + (new Date()).getTime();
	}
	
});


Element.implement({

	enableImageLoader: function() {
		return new ImageLoader(this);
	},
	show: function() {
		this.setStyle('display', this.get('tag') == 'tr' ? '' : 'block');
		return this;
	},
	hide: function() {
		this.setStyle('display', 'none');
		return this;
	},
	toggle: function() {
		if (this.visible()) {
			this.hide();
		}
		else {
			this.show();
		}
	},
	visible: function() {
		return this.getStyle('display', 'none') != 'none';
	}

});


window.addEvent('domready', function() {

/*  $$('.product-card-item p.thumbnail img').enableImageLoader();
*/

  $$('.product-card-item p.thumbnail').enableImageLoader();

  $$('ul.tabs li').each(function(el) {
	
/*	var rel = $(el.get('rel'));
	
    if(el.match('.selected')) {
	  rel.show();
    }
    else {
      rel.hide();
    }*/
	
	el.adopt(new Element('span'));
	
  /*el.addEvent('click', function() {
		var siblings = $$(this.getAllPrevious(), this.getAllNext());
		siblings.each(function(el) {
			$(el.get('rel')).hide();
		});
		rel.show();
		siblings.removeClass('selected');
		this.addClass('selected');
	});*/
  });
  
  $$('#popup .cancel').addEvent('click', function() {
	$$('#dim, #popup').hide();
	$$('#popup-content').empty();
  });
  
  $$('table.item-list tr:even').addClass('even');
  $$('table.item-list tr:odd').addClass('odd');
  
  var rows = $$($$('table.item-list tr').slice(1));
  
  rows.addEvent('click', function(e) {
	
    if(!$(e.target).match('input')) {
      $(this).getElements('input[type=checkbox]').each(function() {
        if(this.checked) {
          this.checked = false;
        }
        else {
          this.checked = true;
        }
      });
    }
	
  });
  
  
  /**
   * Quicksearch
   */

  $$('.quick-search input.keyword').addEvent('keydown', function(event) {
    if (event.key == 'enter')
    {
      var search_word = $(this.getParent()).getElement('input[class=keyword]').get('value');
      var parent_folder = $(this.getParent()).getElement('input[class=parent_folder]').get('value');
      var url = 'materialsearch?keyword=' + search_word + '&folder_id=' + parent_folder;

      if (search_word.length == 0 || parent_folder == 0)
      {
        return false;
      }

      window.parent.location = url;
      return false;
    }
  }); 
  
  /**
   * Advanced menu
   */
  
  var hideDropdowns = function() {
    $$('.advanced-menu .dropdown').removeClass('active');
    $$('.advanced-menu li').removeClass('hover');
  }
  
  $$('.advanced-menu .dropdown > a').addEvent('mousedown', function(e) {
    hideDropdowns();
    this.getParent('.dropdown').addClass('active');
    e.stop();
  });
  
  document.addEvent('mousedown', hideDropdowns);
  
  $$('.advanced-menu li').addEvents({
      mouseenter: function() {
          this.addClass('hover');
      },
      mouseleave: function() {
          this.removeClass('hover');
      }
  });

  $$('.advanced-menu .dropdown ul li').addEvents({
      mousedown: function(e) {
          if ($(e.target).get('tag') == 'input') {
            e.stop();
          }
          var input = this.getElement('input');
          if (input) {
              input.checked = !input.checked || input.type == 'radio';
              e.stop();
          }
          if (this.onclick) {
              this.onclick(e);
          }
          this.fireEvent('click');
          hideDropdowns();
		  try {
			closeInfo();
		  }
		  catch (e) {}
      }
  }).each(function(li) {
      var ul = li.getElement('ul');
	  if (!ul) return;
	  if (!li.hasClass('sub')) return;
      li.addEvent('mouseover', function(e) {
		  var ul = this.getElement('ul');
          if(window.getScroll().x + window.getSize().x < this.getCoordinates().right + 170) {
              ul.setStyles({
                  left: 'auto',
                  right: 170
              });
          }
          else {
              ul.setStyles({
                  left: 170,
                  right: 'auto'
              });
          }
      });
  });
  
  $$('.advanced-menu .dropdown').each(function(li) {
      var ul = li.getElement('ul');
	  if (!ul) return;
      li.addEvent('mouseover', function(e) {
          if(window.getScroll().x + window.getSize().x < this.getCoordinates().right + 170) {
              ul.addClass('flipped');
          }
          else {
              ul.removeClass('flipped');
          }
      });
  });
                                                                                                             
  
});

function openInfo(section) {
  /*$('section-info').show();*/
  var tool = $('tool-' + section);
  var siblings = $$(tool.getAllPrevious('div'), tool.getAllNext('div'));
  $('tool-' + section).show();
  siblings.hide();
  $('main').setStyle('right', 341);
}




function showDynamicTree(val,org) {
  $('operations-packet').hide();
  $('operations-remove').hide();
   $('folderselector').show();
   if (val==1){
    $('movebutton').hide();
    $('copybutton').show();
   }
    else{
    $('copybutton').hide();
    $('movebutton').show();
    }
/*  alert(parent.frames['selector']);
   if (undefined==parent.frames['selector']){
  
   }*/
/*   else {*/
     window.frames[0].document.location='folders?ac=folderlist&folder_id=0&org='+org+'&mode='+val;
/*   }*/
 
}
function hideDynamicTree() {
    $('copybutton').hide();
    $('movebutton').hide();
  $('folderselector').hide();
}

function goView(jump,view){
document.forms['files'].actionsel.value=0;
document.forms['files'].jump.value=jump;
document.forms['files'].view.value=view;
document.forms['files'].submit();
}

function closeInfo() {
/*  $('section-info').hide();*/
  $('main').setStyle('right', 0);
}

function reloadLeftMenu( company )
{
	var leftMenu = window.parent.menu;
	if( leftMenu != null )
	{
		leftMenu.location = '../digtator/campaigns?ac=listcampaigns&org=1&selectedcompany=' + company ;
	}
}


function selectAll (){

  daFiles = document.forms['files'].elements;

    for (i = 0; i < daFiles.length; i++)
   {
   elemName = daFiles[i].name;
         if (elemName.substring(0, 8) == 'filesel_')
	       {
	               if (daFiles[i].checked == false)
		               {
			           daFiles[i].checked = true;
		           }
         }
   }
}

function selectNone (){

  daFiles = document.forms['files'].elements;


    for (i = 0; i < daFiles.length; i++)
   {
   elemName = daFiles[i].name;
   if (elemName.substring(0, 8) == 'filesel_'){
              if (daFiles[i].checked == true)  {
	           daFiles[i].checked = false;
	      }
  }
  }
}

function showfl(jump){
document.forms['files'].jump.value=0;
document.forms['files'].submit();
}



function showRemoveFiles() {
    $('copybutton').hide();
    $('movebutton').hide();
  $('folderselector').hide();
  $('operations-packet').hide();
  $('operations-remove').show();
}
function hideRemoveFiles() {
  $('operations-remove').hide();
}

function showPackage() {
  $('copybutton').hide();
  $('movebutton').hide();
  $('folderselector').hide();
  $('operations-remove').hide();
  $('operations-packet').show();
}
function hidePackage() {
  $('operations-packet').hide();
}




