Event.observe(window, 'load', function() {
	//highlightSearchTerms('CO');
	prepare_requests();
	prepareonce_requests();
	if (!window.count)  count = 1;
	if (!window.numpart) numpart = 1;
	if ($('loadingdiv')) new Effect.Fade($('loadingdiv'));
});

Ajax.Responders.register({
  onComplete: function() {
    prepare_requests();
  }
});
function prepare_requests () {
  
  if (noajax == undefined)
    {
      if (document.getElementsByTagName) {
	var links = $$('a[class="ajax_process"]');
	for (var i=0; i < links.length; i++) {
	  if (links[i].className.match("ajax_process")) {
	    links[i].onclick = function() {
	     process_request(this.getAttribute("href"),"script_process",this.getAttribute("confirm_dlg"));
	      return false;
	    };
	  }
	}
	var forms = document.getElementsByTagName("form");
	for (var i=0; i < forms.length; i++) {
	  if (forms[i].className.match("ajax_process")) {
	    forms[i].onsubmit = function() {
	     process_form(this.getAttribute("action"),"script_process",this.getAttribute("data_url"),this);
	      return false;
	    };
	  }
	}
      }
    }
}
function prepareonce_requests () {
  if (noajax == undefined)
    {
      if (document.getElementsByTagName) {
	var divs = $$('div[class="autocomplete"]');
	for (var i=0; i < divs.length; i++) {
	  if (divs[i].className.match("autocomplete")) {
		    if (divs[i].getAttribute("field")=="companyname") {
			    new Ajax.Autocompleter(divs[i].getAttribute("field"), divs[i].getAttribute("id"), divs[i].getAttribute("function"),  {afterUpdateElement : updateFields });
		    } else if (divs[i].getAttribute("field")=="companyname2") {
			    new Ajax.Autocompleter("companyname", divs[i].getAttribute("id"), divs[i].getAttribute("function"),  {afterUpdateElement : updateFields2 });
		    } else if (divs[i].getAttribute("field")=="companyname_2") {
			    new Ajax.Autocompleter("companyname_2", divs[i].getAttribute("id"), divs[i].getAttribute("function"),  {afterUpdateElement : updateFields3 });
		    } else if (divs[i].getAttribute("afterupdate")=="updateFieldsMeeting") {
			    new Ajax.Autocompleter(divs[i].getAttribute("field"), divs[i].getAttribute("id"), divs[i].getAttribute("function"),
			    {afterUpdateElement : updateFieldsMeeting, callback: function(element, entry) { return Form.serialize('meeting') + "&" + entry; } });
		    } else if (divs[i].getAttribute("field")=="searchfield") {
			    new Ajax.Autocompleter(divs[i].getAttribute("field"), divs[i].getAttribute("id"), divs[i].getAttribute("function"),  {afterUpdateElement : updateFieldsAdmin });
		    } else if (divs[i].getAttribute("afterupdate")=="product_selected") {
			    new Ajax.Autocompleter(divs[i].getAttribute("field"), divs[i].getAttribute("id"), divs[i].getAttribute("function"),
			    {afterUpdateElement : product_selected});
		    } else if (divs[i].getAttribute("afterupdate")=="updateFieldGiven") {
			    new Ajax.Autocompleter(divs[i].getAttribute("field"), divs[i].getAttribute("id"), divs[i].getAttribute("function"),
			    {afterUpdateElement : updateFieldGiven});
		    } else {
			    new Ajax.Autocompleter(divs[i].getAttribute("field"), divs[i].getAttribute("id"), divs[i].getAttribute("function"),
			    {});
		    }
	    }
	}
	    eventspans();
      }
    }
}

function process_request(href,aff_div,confirm_dlg){
	var check_dlg = true;
	if (confirm_dlg)	{
		check_dlg = process_confirm();
	}
	if (check_dlg) {
          try {
            tinyMCE.execCommand('mceRemoveControl', false, "memo_text");
            $F("memo_text").hide();
          }
          catch (err) {
          }

	if ($('loadingdiv'))
        {
          $('loadingdiv').show();
        }
		opacitydown(aff_div);
		
		new Ajax.Request (href, {onComplete: function() {opacityup(aff_div); if ($('loadingdiv')) { new Effect.Fade($('loadingdiv'));}}, evalscript:true});
	}
	return false;
}
function process_request2(href,aff_div,confirm_dlg){
	var check_dlg = true;
	if (confirm_dlg)	{
		check_dlg = process_confirm();
	}
	if (check_dlg) {
          try {
            tinyMCE.execCommand('mceRemoveControl', false, "memo_text");
            $F("memo_text").hide();
          }
          catch (err) {
          }

	if ($('loadingdiv'))
        {
          $('loadingdiv').show();
        }
		opacitydown(aff_div);
		
		new Ajax.Request (href, {onComplete: function() {opacityup(aff_div); if ($('loadingdiv')) { new Effect.Fade($('loadingdiv'));}}, evalscript:true});
	}
	//return false;	
}

function process_form(href,aff_div,data_url,thisForm){
  try {
        if ($('loadingdiv'))
        {
          $('loadingdiv').show();
        }
        if (tinyMCE) {
          tinyMCE.triggerSave();
        }
        parameters=Form.serialize(thisForm);
	opacitydown(aff_div);
	new Ajax.Request (href, {onComplete: function() {
          opacityup(aff_div);
          if ($('loadingdiv')) {
            new Effect.Fade($('loadingdiv'));
          }
	}
	,method:'post', postBody:parameters, evalscript:true});
	if ($F('memo_text'))
        {
          try {
            tinyMCE.execCommand('mceRemoveControl', false, "memo_text");
            $F("memo_text").hide();
          }
          catch (err) {
          }
        }
	return false;
  }
  catch (err) {
    return false;
   }
}
function process_confirm(){
	if (confirm('Please confirm')) {return true;} else {return false;}
}

function updateFields(text,li) {
	//document.getElementById("company_id").value=li.id;
	//here we will populate other fields kkokoko
	new Ajax.Updater ("company_data",base_url+"invoice/loadcompanydata",{method:'post', postBody:'id=' + li.id});
}
function updateFields2(text,li) {
	//document.getElementById("company_id").value=li.id;
	//here we will populate other fields kkokoko
	new Ajax.Updater ("company_data",base_url+"company/loadlogodata",{method:'post', postBody:'id=' + li.id});
}
function updateFields3(text,li) {
	document.getElementById("Company2ID").value=li.id;
	//here we will populate other fields kkokoko
	//new Ajax.Updater ("company_data",base_url+"invoice/loadcompanydata",{method:'post', postBody:'id=' + li.id});
}
function updateFieldsAdmin(text,li) {
	//document.getElementById("company_id").value=li.id;
	//here we will populate other fields kkokoko
	new Ajax.Updater ("data_form",base_url+"contact/add_admin",{method:'post', postBody:'id=' + li.id});
}
function updateFieldsMeeting(text,li) {

	error=0;
	for (i=2;i<=numpart;i++) {
		fieldid = "participant["+i+"]";
		if ($(fieldid).value == li.id) error=1;
	}

	if (error==0)
	{


	opacitydown('timetable');

    count+=1;
	numpart+=1;
    var all_companies = document.getElementById('participants');

    var newdiv = document.createElement('div');

    var divIdName = "new_participant"+count;

    newdiv.setAttribute('id',divIdName);

    newdiv.setAttribute('class',"new_participant");

    newdiv.setAttribute('style',"{display:none}");

    newdiv.innerHTML = " <a href='javascript:cleandiv(\""+divIdName+"\")'><img src=\"/images/icons/delete.png\" class=\"icon\"></a><input type=hidden id=participant["+count+"] name=participant["+count+"] size=30 value='"+li.id+"' />"+li.innerHTML;

    all_companies.appendChild(newdiv);

    new Effect.SlideDown("new_participant"+count,{});


/*	if (numpart==2) {
		$("submitparticipants").enable();
		new Effect.Appear($("submitdiv"),{});
	}
	$('timetable').innerHTML="";
*/
		new Ajax.Updater ('timetable', base_url+"meetings/gettimetable", { onComplete: function() {
			opacityup('timetable');
		},
		method:'post', parameters:Form.serialize($("meeting")), evalscript:true});
	$('meetingdetailsform').update("");
	}
	$('meeting_participant').value="";
}
function addparticipant(part_id,part_name) {
	count=2;
	numpart=2;
	var all_companies = document.getElementById('participants');

	var newdiv = document.createElement('div');

	var divIdName = "new_participant"+count;

	newdiv.setAttribute('id',divIdName);

	newdiv.setAttribute('class',"new_participant");

	newdiv.innerHTML = " <a href='javascript:cleandiv(\""+divIdName+"\")'><img src=\"/images/icons/delete.png\" class=\"icon\"></a><input type=hidden id=participant["+count+"] name=participant["+count+"] size=30 value='"+part_id+"' />"+part_name;
	all_companies.appendChild(newdiv);
}
function cleandiv(id)
{
	numpart-=1;
	var div_to_clean = document.getElementById(id);

	opacitydown('timetable');

	new Effect.SlideUp(div_to_clean, { afterFinish: function() {
		Element.remove( div_to_clean );
		new Ajax.Updater ('timetable', base_url+"meetings/gettimetable", { onComplete: function() {
			opacityup('timetable');
		},
		method:'post', parameters:Form.serialize($("meeting")), evalscript:true});
	}});
/*	if (numpart==1)  {
		$("submitparticipants").disable();
		new Effect.Fade($("submitdiv"),{});

	}
	$('timetable').innerHTML="";
*/
	$('meetingdetailsform').update("");



}

function opacitydown(element) {
	if($('loadingdiv')){
		$('loadingdiv').show();
	}
  	new Effect.Opacity(element, {
		duration: 0.5,
		transition: Effect.Transitions.linear,
		from: 1.0, to: 0.4 });
}

function opacityup(element) {
	if($('loadingdiv')){
		new Effect.Fade($('loadingdiv'));
	}
	new Effect.Opacity(element, {
		duration: 0.5,
		transition: Effect.Transitions.linear,
		from: 0.4, to: 1 });

}

function gettimetable()
{
	new Ajax.Updater ('timetable', base_url+"meetings/gettimetable", {method:'post', parameters:Form.serialize($("meeting")), evalscript:true});
	return false;
}
function confirmMeeting(meeting_id)
{
	opacitydown('timetable');
	new Ajax.Updater ('timetable', base_url+"meetings/confirm", { onComplete: function() {
		opacityup('timetable');
		eventspans();
		}, method:'post', parameters:Form.serialize($("meeting"))+"&meeting_id="+meeting_id, evalscript:true});

}
function eventspans()
{
    var spans = document.getElementsByTagName("span");
    for (var i=0; i < spans.length; i++) {
	    if (spans[i].className.match("eventinfo")) {
		spanname =spans[i].id;
		
		new Ajax.Updater (spans[i],"/ci/meetings/display_count/" + spans[i].getAttribute("event_id"),{onComplete:function(){ new Effect.Pulsate("event41",{ pulses: 3, duration: 1.5 });}});
	    }
    }

}
function cancelMeeting(meeting_id)
{
	opacitydown('timetable');
	new Ajax.Updater ('timetable', base_url+"meetings/cancel", { onComplete: function() {
		opacityup('timetable');
		eventspans();
		}, method:'post', parameters:Form.serialize($("meeting"))+"&meeting_id="+meeting_id, evalscript:true});

}
function saveNewMessage(meeting_id)
{
	new Ajax.Updater ('timetable', base_url+"meetings/saveNewMessage", { method:'post', parameters:Form.serialize($("formnewmessage"+meeting_id))+"&"+Form.serialize($("meeting")), evalscript:true});

}
function removeCountryFromGroup(country_id,countrygroup_id)
{

	new Ajax.Updater ('country'+country_id, base_url+"country/groupRemoveCountry/"+country_id+"/"+countrygroup_id, {evalscript:true});
}

function addCountryToGroup(country_id,countrygroup_id)
{

	new Ajax.Updater ('country'+country_id, base_url+"country/groupAddCountry/"+country_id+"/"+countrygroup_id, {evalscript:true});
}
function ScheduleMeeting(meettime)
{
	opacitydown('meetingdetailsform');

	new Ajax.Updater ('meetingdetailsform', base_url+"meetings/DisplayScheduleForm", { onComplete: function() {
		opacityup('meetingdetailsform');
		new Effect.ScrollTo('meetingdetailsform');
		}, method:'post', parameters:Form.serialize($("meeting"))+"&meettime="+meettime, evalscript:true});
}

function product_selected(text, li) {
// Include all 3 values in ID and split values here in javascript: find text functions for javascript to split values example: id="1|100.00|2"
        var myText = li.id
        var mySplitResult = myText.split("|");
	$('product_id').value=mySplitResult[0];
	$('unit_price').value=mySplitResult[1];
	$('vat_id').value=mySplitResult[2];
	vat_selected();
	$('qty').value=1;
	$('qty').focus();
}
function vat_selected() {
	new Ajax.Request(base_url+"vat/getvat",{method:'post', postBody:'id=' + $('vat_id').value, onSuccess: function(transport){
      $('vat_rate').value = transport.responseText ;
    }},{asynchronous:true});
}

function isset( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true

    var i = 0, argc = arguments.length, argv = arguments, set=true;

    for (i = 0; i< argc; i++){
        if( argv[i] == undefined ){
            set = false;
            break;
        }
    }

    return set;
}
function ProcessMeetingsFormCheck()
{
	if ($('MeetingFormSubmitButton')) {
		return true;
	} else {
		return false;
	}
}

function ProcessMeetingsForm()
{
	alert("Yo!");
}
function submitform()
{
    return false;
}
function saveScrollPos(div,store){
    $(store).value = $(div).scrollTop;
    
}
function setScrollPos(div,store){
    $(div).scrollTop = $(store).value;
}
function updateFieldGiven(text,li) {
	fieldname = text.id;
	fieldname = fieldname.replace('_text' , '_id');
	$(fieldname).value = li.id;
}

