$(document).ready(function() {
  $("#row_contacts_add").hide(); // messes up if set in css
  
  //IMPORT
  $("#btn_contacts_import").click(function () {
    $("#contacts_import").show("slow");
  });
  $("#btn_contacts_import_hide").click(function () {
    $("#contacts_import").hide("slow");
  });
  $("#form_contacts_import").submit(function() {
    return  (
			 validate_file("td_file_contacts_import", $("#file_contacts_import").val())
			 &&
			 validate_required("td_contacts_import_type", $("#contacts_import_type").val())
			 )
  });
  $("#import_contacts_cancel").click(function () {
    window.location="/contacts";
  });

  //ACCORDIAN
  //$("dd:not(:first)").hide();
  $("dd").hide();
  $("dt a").click(function(){
    $("dd:visible").slideUp("slow");
    $(this).parent().next().slideDown("slow");
    return false;
  });
  	
  //POPUP CALENDAR
  $("#select_date").datepicker({
    minDate: 0, 
    maxDate: '+2Y',
    dateFormat: 'D dd/mm/yy',
    altField: '#conference_date', 
    altFormat: 'yy-mm-dd'
  });

  // SELECT CONTACTS
  $('#add_conference_participants').click(function() {
    return !$('#select1 option:selected').remove().appendTo('#select2');
  });
  $('#remove_conference_participants').click(function() {
    return !$('#select2 option:selected').remove().appendTo('#select1');
  });
  
  // POPUP BOX
  $(".popup_box").dialog({
    autoOpen: false,
    modal: true,
    dialogClass: 'popup_box',
    width: '600px',
    resizable: false
  });
  
  // GOOGLE MAP
  $('.toggle-map').focus(function () {
    loadPopup('map1');
    loadGoogleMap('','',5);
  });
  $('#map_close').click(function () {
    $("#map1").dialog("close"); 
  });

});

var error_color = "#FF6666";
var isEditContact = false;
var isSortContact = '';
var animateSpeed = 'medium';
var rowBgColor = '';

function loadPopup(box) {
  $("#"+box).dialog("open"); 
}

function showhideconference(id) {

	if ($('#att' + id).css('display') == 'none') {
		$('#att' + id).slideDown("slow");
		$('#atts' + id).slideUp("slow");
		$('#but' + id).slideDown("slow") ;
		$('#buts' + id).slideUp("slow"); 
		$('#det' + id).slideDown("slow");
	} else {
		$('#att' + id).slideUp("slow");
		$('#atts' + id).slideDown("slow");
		$('#but' + id).slideUp("slow"); 
		$('#buts' + id).slideDown("slow") ;
		$('#det' + id).slideUp("slow");
	}

}

function loadGoogleMap(llat, llng, zoom) {
  if (GBrowserIsCompatible()) {

    // Add marker to the map
    function createGoogleMarker(lat, lng) {
      var marker = new GMarker(new GLatLng(lat, lng, false), {draggable: true, clickable: false});
	  GEvent.addListener(marker, 'dragend', function() {
		var pos = marker.getPoint();
        loadGoogleMap(pos.lat(),pos.lng(),map.getZoom());
													 });
		
      GEvent.addListener(map, "click", function(overlay, point){
        //map.clearOverlays();
        if (point) {
          /*
          map.addOverlay(new GMarker(point));
          map.panTo(point);
          $('#timezone_lat').val(point.lat()); 
          $('#timezone_lon').val(point.lng()); 
          $.post("/schedule-conference/gettimezonefromlonlat", { 
            lat: point.lat(),
            lon: point.lng() 
          },
          function(data){
            var location = data.split("|",2);
            $('#map_info').html(location[0]);
            $('#conference_location').val(location[0]);
            $('#conference_timezone').val(location[1]);
            updateParticipantLocationTimezone(location[0], location[1]);
          });
          */
          loadGoogleMap(point.lat(),point.lng(),map.getZoom());
        }
      });
      map.addOverlay(marker);
    }

    function searchGoogleMap(search) {
      if (search != '') {
        $("#map_search_results").html("");
        var geo = new GClientGeocoder();
        geo.getLocations(search, function (result) {
          if (result.Status.code == G_GEO_SUCCESS) {
            if (result.Placemark.length > 0) { 
              for (var i=0; i<result.Placemark.length; i++) {
                var p = result.Placemark[i];
                $("#map_search_results").append((i+1)+": <a href='javascript:loadGoogleMap(" +p.Point.coordinates[1]+","+p.Point.coordinates[0]+","+map.getZoom()+")'>"+p.address+"</a><br/>");
              }
              $("#map_search_results").append("<br/><input type=\"button\" onclick=\"javascript:clearGoogleSearch()\" value=\"Clear Search\" />");
            }
          }
        });
        $("#map_search_results").fadeIn();
      }
    }

    function SearchMapControl() {}
    SearchMapControl.prototype = new GControl();

    SearchMapControl.prototype.initialize = function(map) {
      var container = document.createElement("div");

      var searchInput = document.createElement("input");
      this.setInputStyle_(searchInput);
      container.appendChild(searchInput);

      var searchButton = document.createElement("button");
      this.setButtonStyle_(searchButton);
      container.appendChild(searchButton);
      searchButton.appendChild(document.createTextNode("Search"));
      GEvent.addDomListener(searchButton, "click", function() {
        searchGoogleMap(searchInput.value);
      });

      var searchResults = document.createElement("div");
      this.setDivStyle_(searchResults);
      searchResults.id = "map_search_results";
      container.appendChild(searchResults);

      map.getContainer().appendChild(container);
      return container;
    }

    SearchMapControl.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
    }

    SearchMapControl.prototype.setInputStyle_ = function(obj) {
      obj.style.padding = "2px";
      obj.style.marginRight = "3px";
      obj.style.textAlign = "left";
      obj.style.width = "12em";
      obj.style.float = "right";
    }

    SearchMapControl.prototype.setButtonStyle_ = function(obj) {
      obj.style.padding = "1px";
      obj.style.float = "right";
    }

    SearchMapControl.prototype.setDivStyle_ = function(obj) {
      obj.style.padding = "3px";
      obj.style.textAlign = "left";
      obj.style.marginTop = "3px";
      obj.style.width = "210px";
      obj.style.display = "none";
      obj.style.backgroundColor = "#fff";
      obj.style.border = "1px solid #7F9DB9";
    }
  
    // create the map
    var map = new GMap2(document.getElementById("map"));
    map.addControl(new SearchMapControl());
    map.addControl(new GLargeMapControl());
    
    if (llat!='' && llng!='') {
      map.setCenter(new GLatLng(llat, llng, false), zoom);
      createGoogleMarker(llat, llng);
      $('#timezone_lat').val(llat); 
      $('#timezone_lon').val(llng); 
      $.post("/schedule-conference/gettimezonefromlonlat", { 
        lat: llat,
        lon: llng,
		type: maptype
      },
      function(data){
        var location = data.split("|");
		if (location[0].indexOf('>')>0) {
			window.location.href = '/';
		}
        $('#map_info').html(location[1]);
        $('#conference_city_id').val(location[0]);
        $('#conference_location').val(location[1]);
        $('#conference_timezone').val(location[2]);
        updateParticipantLocationTimezone(location[2]);
        updateParticipantLocationDialinNumber(location[0]);
      });
    } else {
      var center = new GLatLng($('#timezone_lat').val(), $('#timezone_lon').val(), false);
      map.setCenter(center, zoom);
      createGoogleMarker($('#timezone_lat').val(), $('#timezone_lon').val());
    }
    
  }
}

function clearGoogleSearch() {
  $("#map_search_results").fadeOut();
}

function createMessagePopup(text) {
  $("#container_content").append('<div id="messagepopup"><span class="ui-icon ui-icon-circle-tick" style="float:left; margin:0 7px 50px 0;"></span>'+text+'</strong>');
  $("#messagepopup").dialog({    
    modal: true,
    resizable: false,
    dialogClass: 'popup_box',
    //dialogClass: 'ui-state-error',
    close: function() {
      $("#messagepopup").remove();
    }
  });
  loadPopup('messagepopup');
}

function createErrorPopup(text) {
  //$("#container_content").append('<div id="errorpopup"><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>'+text+'</div>');
  $("#container_content").append('<div id="errorpopup">'+text+'</div>');
  $("#errorpopup").dialog({    
    modal: true,
    resizable: false,
    dialogClass: 'popup_box',
    dialogClass: 'ui-state-error',
    close: function() {
      $("#errorpopup").remove();
    }
  });
  loadPopup('errorpopup');
}

function createAlertPopup(text) {
  $("#container_content").append('<div id="alertpopup"><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>'+text+'</div>');
  $("#alertpopup").dialog({    
    modal: true,
    resizable: false,
    dialogClass: 'popup_box',
    close: function() {
      $("#alertpopup").remove();
    }
  });
  loadPopup('alertpopup');
}

function createConfirmPopup(text, confirm, cancel) {
  var yes = $("#button_confirm_yes").html();
  var no = $("#button_confirm_no").html();
  $("#container_content").append('<div id="confirmpopup"><span class="ui-icon ui-icon-circle-arrow-e" style="float:left; margin:0 7px 50px 0;"></span>'+text+'</div>');
  $("#confirmpopup").dialog({    
    modal: true,
    resizable: false,
    dialogClass: 'popup_box',
    buttons: {
      no: function() {
        $("#confirmpopup").remove();
        eval(cancel);
      },
      yes: function() {
        $("#confirmpopup").remove();
        eval(confirm);
      }
    },
    close: function() {
      $("#confirmpopup").remove();
      eval(cancel);
    }
  });
  $('button').each(function() {
    if ($(this).html()=='yes') {
      $(this).html(yes);
    } else if ($(this).html()=='no') {
      $(this).html(no);
    }
  });
  loadPopup('confirmpopup');
}

function sortContact(name) {
  if (isSortContact != name) {
    $('#row_contact_list').fadeOut(animateSpeed);
    $.post("/contacts/sort", { id: name },
    function(data){
      updateContactRows(data);
      $('.sort').removeClass();
      $('#th_contacts_'+name).addClass('sort');
    });
    isSortContact = name;
  }
}

function sendSampleInviteEmail() {
  $('.errorCell').removeClass();
  var f_participants = false;
  $('#select2 option').each(function() {
    $(this).attr("selected", "selected");
    f_participants = $(this).val();
  });
  var f_subject = $('#conference_subject').val();
  if (validate_required("td_conference_subject", f_subject) 
    && validate_required("td_conference_participants", f_participants)) 
  {
	  t = $('input[name=conference_type]:checked').val();
	  if (!t) {
		  	t = 'voice';
	  }
    $.post("/schedule-conference/sendsampleemail", { 
      subject:	$('#conference_subject').val(),
      datetime:	$('#select_date').val()+' '+$('#conference_time').val(),     
      location:	$('#conference_location').val(),     
      chairpin:	$('#conference_host_pin').val(),     
      message:	$('#conference_message').val(),
	  city_id:	$('#conference_city_id').val(),
	  freefone: $('#show_freefone:checked').val()=='Y',
	  geographic:  $('#show_geographic:checked').val()=='Y',
	  type:		t
    },
    function(data){
      if (data>0) {
        createAlertPopup($('#text_sendsampleemail').html());
      } 
    });
  }
}

function sendInviteEmail(cid) {
  $.post("/conference-history/sendinviteemail", { id: cid },
  function(data){
    createAlertPopup($('#text_sendInviteEmail').html());
  });
}

function declineInvitation(cid) {
  window.location="/invite/decline/id/"+cid;
}

function prepareAddConference() {
  createConfirmPopup($('#text_scheduleConference').html(), 'validate_future()', '');
};

function doSubmitAddConference() {
  $('.errorCell').removeClass();
  var f_participants = false;
  $('#select2 option').each(function() {
    $(this).attr("selected", "selected");
    f_participants = $(this).val();
  });
  if ($('#conference_city_id').val() == '') {
	  $('#conference_location').val('');
  }
  if (v_future) {
	  if (
			validate_required("td_conference_subject", $('#conference_subject').val()) 
			&&
			validate_required("td_conference_participants", f_participants)
			&&
			validate_required("td_conference_location", $('#conference_location').val())
		) 
	  {
		$('#form_conference').submit();
	  }
  } else {
	  validate_future();
  }
};

function copyConference(cid) {
  window.location="/schedule-conference/copy/cid/"+cid;
}

function rescheduleConference(cid) {
  window.location="/schedule-conference/edit/cid/"+cid;
}

function prepareCancelConference(cid, text) {
  hilightRow(cid, false);
  createConfirmPopup(text, 'submitCancelConference("'+cid+'")', 'cancelDeleteConference("'+cid+'")');
}

function submitCancelConference(cid) {
  $('#row_contact_list').fadeOut(animateSpeed);
  $.post("/conference-history/cancel", { id: cid },
  function(data) {
    updateConferenceRows(data);
  });
}

function prepareDeleteConference(cid, text) {
  hilightRow(cid, false);
  createConfirmPopup(text, 'submitDeleteConference("'+cid+'")', 'cancelDeleteConference("'+cid+'")');
}

function submitDeleteConference(cid) {
  $('#row_contact_list').fadeOut(animateSpeed);
  $.post("/conference-history/delete", { id: cid },
  function(data) {
    updateConferenceRows(data);
  });
}

function cancelDeleteConference(cid) {
  $("#"+cid).css({"background-color":rowBgColor});
}

function prepareAddContact() {
  $("#row_contacts_add").fadeIn("slow");
}

function submitAddContact(page) {
  $('.errorCell').removeClass();
  var f_first_name = $('#add_first_name').val();
  var f_last_name = $('#add_last_name').val();
  var f_email = $('#add_email').val();
  if (validate_required("td_first_name", f_first_name) && 
    validate_required("td_last_name", f_last_name) && 
    validate_email("td_email", f_email)) 
  {
    $('#row_contact_list').fadeOut(animateSpeed);
    if (page == 'contact') {
      $.post("/contacts/add", 
        { 
          first_name: f_first_name, 
          last_name: f_last_name,
          email: f_email 
        },
        function(data){
          $("#row_contacts_add").hide();
          $('#add_first_name').val("");
          $('#add_last_name').val("");
          $('#add_email').val("");
          updateContactRows(data);
          hilightRow($("#affected_row").val(), true);
        }
      );
    } else if (page == 'conference') {
      $.post("/schedule-conference/addcontact", 
        { 
          first_name: f_first_name, 
          last_name: f_last_name,
          email: f_email 
        },
        function(data){
          $("#row_contacts_add").hide();
          $('#add_first_name').val("");
          $('#add_last_name').val("");
          $('#add_email').val("");
          $('#select2').append('<option value="'+data+'">'+f_first_name+' '+f_last_name+'</option>');
        }
      );
    }
  }
}

function cancelAddContact() {
  $("#row_contacts_add").fadeOut(animateSpeed);
}

function prepareEditContact(cid) {
  if (!isEditContact) {
    $('#btn_edit_contact'+cid).attr("disabled","disabled");
    isEditContact = true;
    $('#'+cid).fadeOut(animateSpeed, function() {
      var fn = $("#first_name"+cid).html();
      var ln = $("#last_name"+cid).html();
      var e = $("#email"+cid).html();
      var str = '<input type="text" id="edit_first_name'+cid+'" value="'+fn+'" maxlength="50"/>';
      $("#first_name"+cid).html(str);
      str = '<input type="text" id="edit_last_name'+cid+'" value="'+ln+'" maxlength="50"/>';
      $("#last_name"+cid).html(str);
      str = '<input type="text" id="edit_email'+cid+'" value="'+e+'" maxlength="100"/>';
      $("#email"+cid).html(str);
      str = '<input type="button" onclick="submitEditContact('+cid+')" value="Save" />';
      $("#btn_a"+cid).html(str);
      str = '<input type="button" onclick="cancelEditContact()" value="Cancel" />';
      $("#btn_x"+cid).html(str);
    }).fadeIn(animateSpeed);
  }
}

function submitEditContact(cid) {
  $('.errorCell').removeClass();
  var f_first_name = $('#edit_first_name'+cid).val();
  var f_last_name = $('#edit_last_name'+cid).val();
  var f_email = $('#edit_email'+cid).val();
  if (validate_required("first_name"+cid, f_first_name) && 
    validate_required("last_name"+cid, f_last_name) && 
    validate_email("email"+cid, f_email)) 
  {
    $('#row_contact_list').fadeOut(animateSpeed);
    $.post("/contacts/edit", { 
      id: cid, 
      first_name: f_first_name, 
      last_name: f_last_name,
      email: f_email
    },
    function(data){
      updateContactRows(data);
      hilightRow($("#affected_row").val(), true);
      isEditContact = false;
    });
  }
}

function cancelEditContact() {
  $('#row_contact_list').fadeOut(animateSpeed);
  $.post("/contacts/view", {},
  function(data){
    updateContactRows(data);
  });
  isEditContact = false;
}

function prepareDeleteContact(cid, text) {
  hilightRow(cid, false);
  createConfirmPopup(text, 'submitDeleteContact("'+cid+'")', 'cancelDeleteContact("'+cid+'")');
}

function submitDeleteContact(cid) {
  $('#row_contact_list').fadeOut(animateSpeed);
  $.post("/contacts/delete", { id: cid },
  function(data) {
    updateContactRows(data);
  });
}

function updateParticipantLocationTimezone(f_timezone) {
  $.post("/invite/getdatetime", { 
    timezone: f_timezone
  },
  function(data){
    $("#div_participant_startTime").html(data);
    $("#participant_startTime").val(data);
    hilightRow('td_participant_startTime', true);
  });
}

function updateParticipantLocationDialinNumber(city) {
  $.post("/invite/getdialinnumber", { 
    city_id: city,
	conference_id: $('#conference_id').val()
  },
  function(data){
    $("#div_participant_dialinNumber").html(data);
    $("#participant_dialinNumber").val(data);
    hilightRow('td_participant_dialinNumber', true);
  });
}

function cancelDeleteContact(cid) {
  $("#"+cid).css({"background-color":rowBgColor});
}

function validate_required(field, value) {
  if (value==null||value=="") {
    $('#'+field).addClass('errorCell');
    createErrorPopup($("#text_error_required").html());
    return false;
  }
  $('#'+field).removeClass('errorCell');
  return true;
}

var v_future = false;
function validate_future() {
	v_future = false;
	$.get("/schedule-conference/testfuture/date/"+escape($('#select_date').val()).replace(/\//g,'-')+"/time/"+$('#conference_time').val()+"/city/"+$('#conference_city_id').val(),
			function (reply) {
				if (reply == 'yes') {
					v_future = true;
					$('#select_date').removeClass('errorCell');
					doSubmitAddConference();
				} else {
					$('#select_date').addClass('errorCell');
					createErrorPopup('Please select a date and time at least 15 minutes in the future.');
				}
			});
	return false;
}

function validate_email(field, value) {
  regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  if (!regex.test(value)) {
    $('#'+field).addClass('errorCell');
    createErrorPopup($("#text_error_email").html());
    return false;
  }
  $('#'+field).removeClass('errorCell');
  return true;
}

function validate_file(field, value) {
  var ext=new RegExp("(csv|xls)$");
  if (!ext.test(value.toLowerCase())) {
    $('#'+field).addClass('errorCell');
    createErrorPopup($("#text_error_file").html());
    return false;
  }
  $('#'+field).removeClass('errorCell');
  return true;
}

function hilightRow(cid, animate) {
  rowBgColor = $("#"+cid).css("background-color");
  if (animate) {
    $("#"+cid).animate({backgroundColor:error_color}, 1000)
      .animate({backgroundColor:rowBgColor}, 2000);
  } else {
    $("#"+cid).css({"background-color":error_color});
  }
}

function updateContactRows(data) {
  $('#row_contact_list').html(data).fadeIn(animateSpeed);
  isEditContact = false;
}

function updateConferenceRows(data) {
  $('#row_conference_list').html(data).fadeIn(animateSpeed);
}

function checkpinfreegeo(pin) {
	var free = false;
	c = freefone.length;
	for (i=0;i<c;i++) {
		if (freefone[i] == pin) {
			free = true;
			break;
		}
	}
	
	if (free) {
		$('#show_freefone').attr("disabled", false);
	} else {
		$('#show_freefone').attr("checked", false);
		$('#show_freefone').attr("disabled", "disabled");
	}

	var geo = false;
	c = geographic.length;
	for (i=0;i<c;i++) {
		if (geographic[i] == pin) {
			geo = true;
			break;
		}
	}
	
	if (geo) {
		$('#show_geographic').attr("disabled", false);
	} else {
		$('#show_geographic').attr("checked", false);
		$('#show_geographic').attr("disabled", "disabled");
	}

	var web = false;
	c = webconf.length;
	for (i=0;i<c;i++) {
		if (webconf[i] == pin) {
			web = true;
			break;
		}
	}
	
	if (web) {
		$('input[name=conference_type]').attr("disabled", false);
	} else {
		$('#conference_type_voice').attr("checked", "checked");
		$('#conference_type_both').attr("checked", false);
		$('input[name=conference_type]').attr("disabled", "disabled");
	}
}