var timeout_wipajax_main = undefined;
var timeout_wipajax_basket_add = undefined;

function wipAjaxHttpAjaxSuccess (t, statusDiv) {
  window.fire('ajax:load');
}
function wipAjaxHttpAjaxError (t) {
  //alert('Error ' + t.status + ' -- ' + t.statusText);
  //alert('you can\'t user this pseudo (ndr : test version).');
  //$(imgPseudo).src = '/champNonValide.gif';
}

function wipAjaxHttpAjaxError404 (t) {
  //alert('Error ' + t.status + ' -- ' + t.statusText);
  //alert('you can\'t user this pseudo (ndr : test version).');
  //$(imgPseudo).src = '/champNonValide.gif';
}

var toggle_db = new Hash();
function wipAjax (queryString, htmlDiv, page, method, effect, toggle, toggle_keep_open, mixpanel) {
  // Mixpanel.com
  try {
    window.mixpanel.track(page);
  } catch (err) { }

  var url = page;
  var status = $(htmlDiv + 'status');
  if (status) {
    status.style.display = 'inline';
  }

  if (toggle) {
    try {
      clearTimeout(timeout_wipajax_main);
      clearTimeout(timeout_wipajax_basket_add);

      toggle_db.each( function(pair) {
        if (htmlDiv != pair.value) {
          //if ( $('debug') ) $('debug').insert({ bottom : (pair.key + ' = "' + pair.value + '"') });
          //alert(pair.key + ' = "' + pair.value + '"');
          var my_div_toggle = $(pair.key);
          if (my_div_toggle) {
            my_div_toggle.removeClassName('active');
          }
          if ($(pair.value).visible()) {
            new Effect.SlideUp($(pair.value), { duration: 0.5 } );
          }
          toggle_db.unset(pair.key);
        }
      });

      var div_toggle = $(htmlDiv + toggle);
      if ( toggle_db.get(htmlDiv + toggle) ) {
	if (toggle_keep_open) {
	  effect = '';
	} else {
          toggle_db.unset(htmlDiv + toggle);
          if (div_toggle) div_toggle.removeClassName('active');
          new Effect.SlideUp(htmlDiv, { duration: 0.5 } );
          return;
	}
      } else {
        toggle_db.set(htmlDiv + toggle, htmlDiv);
        if (div_toggle) div_toggle.addClassName('active');
      }

    } catch (err) {
    }
  }

  if (method == 'post') {
    new Ajax.Updater(
                     htmlDiv, url, {
                                    onComplete:function(){
                                                          if (effect) {
							    try {
							      if (effect == 'slidedown') {
							        new Effect.SlideDown(htmlDiv, { duration: 0.5 } );
							      } else {
							        htmlDiv.show();
                                                                new Effect.Highlight(htmlDiv, { duration: 0.5 } );
							      }
							    } catch (err) {
							    }
                                                          }
                                                         },
                                    asynchronous: true,
                                    evalScripts: true,
                                    method: 'post',
                                    parameters: '',
                                    postBody: queryString,
                                    on404: wipAjaxHttpAjaxError404,
                                    onSuccess: wipAjaxHttpAjaxSuccess,
                                    onFailure: wipAjaxHttpAjaxError
                                   }
                       );

  } else {
    new Ajax.Updater(
                     htmlDiv, url + '?' + queryString, {
                                                        onComplete:function(){
                                                                              if (effect) {
										try {
							                          if (effect == 'slidedown') {
							                            new Effect.SlideDown(htmlDiv, { duration: 0.5 } );
							                          } else {
							                            htmlDiv.show();
                                                                                    new Effect.Highlight(htmlDiv, { duration: 0.5 } );
							                          }
										} catch (err) {
										}
                                                                              }
                                                                             },
                                                        asynchronous: true,
                                                        evalScripts: true,
                                                        method: 'get',
                                                        on404: wipAjaxHttpAjaxError404,
                                                        onSuccess: wipAjaxHttpAjaxSuccess,
                                                        onFailure: wipAjaxHttpAjaxError
                                                       }
                    );
  }

}



function focus_textarea (ev) {
  var el = ev.element();
  if (el.readAttribute('alt') == el.value) { el.value=''; }
  var par = el.up(1);
  par.removeClassName('wipajaxinactive');
  par.addClassName('wipajaxactive');
}
function blur_textarea (ev) {
  var el = ev.element();
  var par = el.up(1);
  if (!el.value) {
    el.value=el.readAttribute('alt');
    par.removeClassName('wipajaxactive');
    par.addClassName('wipajaxinactive');
  }
}


function update_user_box(div, page, query_string) {
  // alert(div);
  if (div && page) {
    wipAjax(query_string, div, page);
  } else {
    var user_box = document.getElementById("wip_person_fb");
    // add in some XFBML. note that we set useyou=false so it doesn't display "you"
    user_box.innerHTML = "<span>" +
         "<fb:profile-pic uid=loggedinuser facebook-logo=true></fb:profile-pic>" +"<fb:name uid=loggedinuser useyou=false></fb:name>. You are signed in with your Facebook account." +
         "</span>";
    // because this is XFBML, we need to tell Facebook to re-process the document
    FB.XFBML.Host.parseDomTree();
  }
}

function init_user_box() {
  // because this is XFBML, we need to tell Facebook to re-process the document
  FB.XFBML.Host.parseDomTree();
}



var menu_db = new Hash();
function menu_toggle (current, parent) {
  menu_db.each( function(pair) {
    if (current != pair.key) {
      //alert(pair.key + ' = "' + pair.value + '"');
      if ($(pair.key)) {
        $(pair.key).removeClassName('current');
      }
      menu_db.unset(pair.key);
    }
  });

  menu_db.set(current, 1);
  if ($(current)) {
    $(current).addClassName('current');
  }
}


// Activate rating links if any
Event.observe(window, 'load', function() {
    $$('.rating_list a.rating_line_toggle').each( function (element) {
        var art = element.up('.rating_list');
        var rating = element.up('.rating_line_child');
        //alert( 'artid:' + art.id + 'ratingid:' + rating.id );
        $(element).observe('click', function(event){
            // alert(Event.element(event).innerHTML);
            $(rating.id).innerHTML = '<img src="/tools/ajax/img/loading_animation_liferay.gif" alt="loading..." />';
            wipAjax('div='+rating.id+'&type=article&level=1&objid='+art.id+'&parent='+rating.id, rating.id, '/tools/wip_v4/ajax_v2/rating/list_simple.epl', 'get');
        });
    });

    $$('.rating_list a.comment_add').each( function (element) {
        var art = element.up('.rating_list');
        var div = art.id;
        var rating = '';
        if ( element.up('.rating_line') ) {
            rating = element.up('.rating_line');
            div = rating.id;
        }
        $(element).observe('click', function(event){
            // alert(Event.element(event).innerHTML);
            $('comment_add_'+div).innerHTML = '<img src="/tools/ajax/img/loading_animation_liferay.gif" alt="loading..." />';
            wipAjax('div=comment_add_'+div+'&type=article&objid='+art.id+'&parent='+rating.id+'&class=ajax_v2_rating_form_sub&submit_txt=txt_form_submit_2&insertion=Before', 'comment_add_'+div, '/tools/wip_v4/ajax_v2/rating/add.epl', 'get');
        });
    });

    $$('.rating_list a.like_add').each( function (element) {
        var art = element.up('.rating_list');
        var div = art.id;
        var rating = '';
        if ( element.up('.rating_line') ) {
            rating = element.up('.rating_line');
            div = rating.id;
        }
        $(element).observe('click', function(event){
            // alert(Event.element(event).innerHTML);
            $('like_add_'+div).innerHTML = '<img src="/tools/ajax/img/loading_animation_liferay.gif" alt="loading..." />';
            if (rating) {
                wipAjax('div=like_add_'+div+'&debug=&type=user_rating&objid='+rating.id+'&action=save&insertion=Before', 'like_add_'+div, '/tools/wip_v4/ajax_v2/rating/like.epl', 'get');
            } else {
                wipAjax('div=like_add_'+div+'&debug=&type=article&objid='+art.id+'&action=save&insertion=Before', 'like_add_'+div, '/tools/wip_v4/ajax_v2/rating/like.epl', 'get');
            }
        });
    });


});




/**
* - @element: element to fire event on
* - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
* - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
*
* $('foo').simulate('click'); // => fires "click" event on an element with id=foo
*
**/
(function(){
  
  var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  }
  var defaultOptions = {
		      pointerX: 0,
		      pointerY: 0,
		      button: 0,
		      ctrlKey: false,
		      altKey: false,
		      shiftKey: false,
		      metaKey: false,
		      bubbles: true,
		      cancelable: true
  }
  
    Event.simulate = function(element, eventName) {
    var options = Object.extend(defaultOptions, arguments[2] || { });
    var oEvent, eventType = null;
    
    element = $(element);
    
  for (var name in eventMatchers) {
    if (eventMatchers[name].test(eventName)) { eventType = name; break; }
  }

    if (!eventType)
      throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

  if (document.createEvent) {
      oEvent = document.createEvent(eventType);
      if (eventType == 'HTMLEvents') {
        oEvent.initEvent(eventName, options.bubbles, options.cancelable);
      }
      else {
        oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
      }
      element.dispatchEvent(oEvent);
    }
    else {
      options.clientX = options.pointerX;
      options.clientY = options.pointerY;
      oEvent = Object.extend(document.createEventObject(), options);
      element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}
  
  Element.addMethods({ simulate: Event.simulate });
})()






function basket_pay_same(overwrite) {
  ['company', 'company_ref', 'fname', 'lname', 'name', 'address1', 'address2', 'postalcode', 'postalplace', 'country', 'comment', 'cellphone', 'email'].each(function(s, index) {
    if ($('pay_' + s) && $('delivery_' + s)) {
      if (overwrite || !$('pay_' + s).value) {
        $('pay_' + s).value = $('delivery_' + s).value;
      }
    }
  });
}



