// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//
	function morphImage(imageID)
	{
		img = $('image-' + imageID);
		himg = $('delete-image-' + imageID);
		if (img.hasClassName('deleted'))
		{
			img.morph('opacity:1; filter:alpha(opacity=100)');
			img.removeClassName("deleted");
			himg.value = null;
			//    $('toggle_logo_a').innerHTML = "I don't want to use a logo. Please remove it";
		}
		else
		{
			img.morph('opacity:0.3; filter:alpha(opacity=30)');
			img.addClassName("deleted");
			himg.value = imageID;
			//  $('toggle_logo_a').innerHTML = "I changed my mind. I want to use the original logo";
		}
		//  $('logo_image').removeClassName('current');$('logo_image').addClassName('deleted'); return false;
	}


var Toggler = Class.create();

Toggler.prototype = {
  initialize : function(pr, ids)  {
    this.selected = new Array;
    this.prefix = pr;
    this.ids = ids;
    this.checked =false ;
  },

  select: function(id) {
    this.selected.push(id);
    this.check(id);
  },

  selectAll: function() {
    this.checked = true;
    this.selected = this.ids.clone();

    for (i=0; i < this.ids.length; i++)
      this.check(this.selected[i]);

    this.updateIndicator();
  },

  deselectAll: function() {
    this.checked = false;

    for (i=0; i < this.ids.length; i++)
      this.uncheck(this.selected[i]);

    this.selected.clear();

    this.updateIndicator();
  },

  updateIndicator: function() {
    if ($('toggler_indicator'))
      $('toggler_indicator').checked = this.checked;
  },

  check: function(id) {
    $(this.prefix + id).checked = true;       
  },

  uncheck: function(id) {
    $(this.prefix + id).checked = false;       
  },

  ischecked: function(id) {
    return $(this.prefix + id).checked;
  },

  toggle: function() {
    this.checked ? this.deselectAll() : this.selectAll();
  },

  reselect : function() {
    for (i=0; i < this.selected.length; i++)
        this.check(this.selected[i]);
  },

  selectedValues:  function() {
    this.selected.clear();

    for (i=0; i < this.ids.length; i++)
      if (this.ischecked(this.ids[i]))
        this.selected.push(this.ids[i]);

    return this.selected;

  }
}

function toggle_children(parent)
{
    child = $('children-of-category-'+parent)
    var action = child.getStyle('display');
        if(action == "none")
        {
          $('click_img_'+parent).src="/images/tree-open.png"
          child.show();
        }
        else
        {
          $('click_img_'+parent).src="/images/tree-close.png"
          child.hide();
        }
}

	function updateVat(direction)
	{
	  percentage = ($('product_vat_id').options[$('product_vat_id').selectedIndex].text.match(/[\d\.,]+/)[0] * 1) + 100;
      if (direction == '0')
      {
        if ($('product_price') && $('product_price').value.length > 0)
    		$('final_price').value = ((($('product_price').value.replace(",", ".") * 1) * 100 * percentage) / 10000).toFixed(4).replace(/\.(\d*[1-9])?0+$/, '.$1').replace(/\.$/, '');
		
        if ($('sales_price_checkbox') && $('sales_price_checkbox').checked)
		{
			if ($('product_sales_price').value.length > 0)
    		  $('final_sales_price').value = ((($('product_sales_price').value.replace(",", ".") * 1) * 100 * percentage) / 10000).toFixed(4).replace(/\.(\d*[1-9])?0+$/, '.$1').replace(/\.$/, '');
		}
      }
      else
      {
        if ($('final_price') && $('final_price').value.length > 0)
    		$('product_price').value = ((($('final_price').value.replace(",", ".") * 1) / percentage) * 100);

        if ($('sales_price_checkbox') && $('sales_price_checkbox').checked)
		{
			if ($('final_sales_price').value.length > 0)
        		$('product_sales_price').value = ((($('final_sales_price').value.replace(",", ".") * 1) / percentage) * 100);
		}
  
      }
	}

function updateMass()
{

  svalues = toggler.selectedValues();
  var toggler_indicator = $('toggler_indicator');
  var old_checked = toggler_indicator.checked;
  toggler_indicator.checked = toggler.checked = svalues.length == toggler.ids.length;

  if (!$('mass_applyto'))
    return;

  if (old_checked !== toggler_indicator.checked) {
    $('select_all_products').toggle();
  }

  if (svalues.length != 0)
  {
    $('mass_applyto').value = toggler.selectedValues().join(',');

      $('mass_form').show();
      $('mass_empty').hide();
  }
  else
  {
    $('mass_applyto').value = '';
      $('mass_empty').show();
      $('mass_form').hide();
  }

}

function reset_product_selection() {
  var mass_applyto = $('mass_applyto');

  if (mass_applyto) {
    mass_applyto.value = '';
  }

  $('reset_product_selection').hide();
  $('select_all_products').show();
}

var FormToggler = Class.create();

FormToggler.prototype = {
  change : function(event) {
    elem = event.element();

    //hide everything
    this.truth_hash.values().each(function(i) { $(i).hide();
        fs = $(i).down('fieldset');
        if (fs)
          fs.disabled = true;
    });
    //now display the correct one if one exists
    to_display = $(this.truth_hash.get(elem.value));
    if (to_display)
    {
      new Effect.toggle(to_display, 'appear');
      fs = to_display.down('fieldset');
      if (fs)
        fs.disabled = false;
    }
  },
  
  initialize : function(elements, truth_hash )  {
    this.elements = elements;
    this.truth_hash = truth_hash;

    //iterate elements and bind their onchange event
    for (i = 0; i < this.elements.length; i++)
    {
      elem = this.elements[i];
      elem.observe('change', this.change.bind(this));
    }

  }

}

     function createSortables(section)
        {
          Sortable.create('link_listing_' + section,
              {	
                constraint:false,
    			onUpdate:function(){
				new Ajax.Request('/admin/static_links/sort_links',
                  {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("link_listing_" + section)}
					)
				},
				tag:'tr',
        //ghosting:true, Changes the position attribute of row from relative to absolute
                hoverclass:'hoverclass'});
        }


function update_pricing_table(el, plan_price, subscription_discounts) {
  var period = $F(el.getAttribute('id'));

  $('preview_plan_price').value = plan_price;
  $('preview_duration').value = period;
  $('preview_sum').value = plan_price * period;

  if ($('preview_credit')) {
    $('preview_total').value = plan_price * period - $('preview_credit').value;
  }
  else {
    $('preview_discount').value = -1 * plan_price * period * (subscription_discounts[period] || 0);
    $('preview_total').value = plan_price * period + (1 * $('preview_discount').value);
  }

  $$('#credit_card .coupon').invoke(period * 1 === 1 ? 'show' : 'hide');
  $$('cc_form').invoke($('preview_total').value > 0 ? 'show' : 'hide');
}

function createSortablesForFrontpage()
{
          Sortable.create('featured-list', 
              {	
                constraint:false,
    			onUpdate:function(){
				new Ajax.Request('/admin/frontpage/sort',
                  {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("featured-list")}
					)
				},
				tag:'div',
				ghosting:false,
                hoverclass:'hoverclass'});

}

function checkPasswordValidity(warn)
{
      if ($('user_password').value.length < 6)
      {
        $('user_password').addClassName('error');
        $('user_password').removeClassName('ok');
        if (warn == '1')
          $('user_password').prototip.show();
      }
      else
      {
        $('user_password').addClassName('ok');
        $('user_password').removeClassName('error');
        if (warn == '1')
          $('user_password').prototip.hide();
      }
      
      if ($F('user_password_confirmation').length == 0)
        return;

      if($('user_password_confirmation').value == $('user_password').value)
      {
        $('user_password_confirmation').removeClassName('error');
        $('user_password_confirmation').addClassName('ok');

        if (warn == '1')
          $('user_password_confirmation').prototip.hide();
      } 
      else
      {
        $('user_password_confirmation').addClassName('error');
        $('user_password_confirmation').removeClassName('ok');

        if (warn == '1')
          $('user_password_confirmation').prototip.show();
      }
}

Ajax.Responders.register({
  onCreate: function(request) {
    var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
    if (csrf_meta_tag) {
      var header = 'X-CSRF-Token',
          token = csrf_meta_tag.readAttribute('content');
      if (!request.options.requestHeaders) {
        request.options.requestHeaders = {};
      }
      request.options.requestHeaders[header] = token;
    }
  }
});

document.observe('dom:loaded', function() {
  $$('#categories_tree a').invoke('observe', 'click', function (e) {
    var category_id = $(this).readAttribute('href').split('/').slice(-1);
    var form = $('product_filters');
    form.select('input[name=category_id]').invoke('setValue', category_id);
    form.submit();
    Event.stop(e);
  });
});

Event.observe(window, 'load', function() {
  Event.observe('issue_button', 'click', function (event){
    $('issue_overlay').setStyle({height:$(document).viewport.getHeight()+"px"});
    $('issue_overlay').toggle();
    $('issue').toggleClassName('issue-div-appear');
  });
  Event.observe('issue_overlay', 'click', function (event){
    $('issue_overlay').hide();
    $('issue').removeClassName('issue-div-appear');
  });
});

function validate_issue_form() {
  if ($F('issue_description').replace(/^\s+|\s+$/g, '').length === 0) {
      alert('Παρακαλώ συμπληρώστε την περιγραφή του προβλήματός σας.');
      return false;
  }

  return true;
}

