/**************************************************************************
 * MeetingStarter Meeting Creation Javascript Code
 * Tim Su (timsu@stanfordalumni.org), July 2007
 **************************************************************************/

//<![CDATA[

var DEBUG = 0;
var HELPHEADER = "MeetingStarter Help:\n\n";
var mainTabber;

/**************************************************************************
 * General Page Layout Code
 **************************************************************************/

/* initPage
   Called when the page is loaded */
function initPage()
{
    // only load map when you switch to page 2
    var tabberOptions = {
        'onTabDisplay':function(argsObj)
        {
            //if(argsObj.index == 1 && typeof(gbrowerOn) != 'undefined')
            //    setTimeout("loadMap();",100);
            if(argsObj.index == 2)
                toggleAdvancedTabs(argsObj.tabber, true, 3);
            else if(argsObj.index == 7)
                toggleAdvancedTabs(argsObj.tabber, false, 0);
        }
    };
    mainTabber = tabberAutomatic(tabberOptions);
    toggleAdvancedTabs(mainTabber, false, 0);
    stripePageCommon();//found in utility.js
}

function toggleAdvancedTabs(tabber, toggle, newIndex)
{
    for(var i=0;i<tabber.tabs.length;i++)
    {
        if(tabber.tabs[i].hideOnAdvanced)
            tabber.tabs[i].li.style.display = (!toggle) ? "" : "none";
        else if(tabber.tabs[i].showOnAdvanced)
            tabber.tabs[i].li.style.display = (toggle) ? "" : "none";
    }
    if(!isNaN(newIndex))
        tabber.tabShow(newIndex);
}

function showAddress(address) {
      gGeocoder.getLocations(address, addAddressToMap);
    }

function addAddressToMap(response) {
  gMap.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("\"" + address + "\" not found");
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    marker = new GMarker(point);
    gMap.addOverlay(marker);
	addressName = document.mainform.eventLocationName.value;
    marker.openInfoWindowHtml('<b>' + addressName + '</b><br>' + place.address);
  }
}

function loadMap()
{
    if (GBrowserIsCompatible() && !gMap) {
        gMap = new GMap2(document.getElementById("locMap"));
        gMap.setCenter(new GLatLng(37.4419, -122.1419), 13);
        gGeocoder = new GClientGeocoder();
        gMap.addControl(new GSmallMapControl());
        gMap.addControl(new GMapTypeControl());
		
		address = document.mainform.eventLocation.value;
	  if(address!=""){
		showAddress(address);	  
	  }
    }

}

    function loadDirections() {
	  var directionsPanel;
	  var directions;
      directionsPanel = document.getElementById("route");
      directions = new GDirections(gMap, directionsPanel);
	  addressfrom = document.mainform.fromAddress.value;
      directions = directions.load(addressfrom + " to " + address);
	  document.mainform.directionsbutton.value= "update";
	  fillthescreen();
    }
	


function stripePage()
{
    stripe('placesTable', '#94b4d6', '#84a4c6');
    stripe('peopleTable', '#ffffe6', '#e7e7bf');
    stripe('friendTable', '#1f703c', '#2a7b43');
}

function suggestHelp()
{
    alert(HELPHEADER +
        'Checking this box allows others to suggest new options to everyone');
}

function clearDef(obj)
{
    if(!obj.cleared)
    {
        obj.value = "";
        obj.cleared = true;
    }
}

/**************************************************************************
 * Location Page
 **************************************************************************/

var myLocations = new Array();
var locationID = 0;
var gMap, gGeocoder;
var gLocalSearch;
var gSearchForm;
var gSmallIcon;
var gCurrentResults = [];

function CaptureForm(searchForm) {
    gLocalSearch.execute(searchForm.input.value);
    return false;
}

function clearSearchResults()
{
    var searchWell = document.getElementById("searchwell");

    // Clear the map and the old search well
    searchWell.innerHTML = "";
    for (var i = 0; i < gCurrentResults.length; i++) {
        if (!gCurrentResults[i].selected()) {
            gMap.removeOverlay(gCurrentResults[i].marker());
        }
    }
}

function OnLocalSearch() {
    if (!gLocalSearch.results) return;
    clearSearchResults();

    gCurrentResults = [];
    for (var i = 0; i < gLocalSearch.results.length; i++) {
        gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
    }

    var attribution = gLocalSearch.getAttribution();
    if (attribution) {
        document.getElementById("searchwell").appendChild(attribution);
    }
    
    if(gLocalSearch.results.length == 0)
        document.getElementById("searchwell").innerHTML =
            '<tr><td class="center">(No Search Results)</td></tr>';

    // move the map to the first result
    var first = gLocalSearch.results[0];
    var point = new GLatLng(parseFloat(first.lat), parseFloat(first.lng));
    gMap.panTo(point);
}

// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result) {
    this.result_ = result;
    this.resultNode_ = this.unselectedHtml();

    document.getElementById("searchwell").appendChild(this.resultNode_);
    gMap.addOverlay(this.marker(gSmallIcon));
}

// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function(opt_icon) {
    if (this.marker_) return this.marker_;
    var marker = new GMarker(new GLatLng(parseFloat(this.result_.lat),
                                        parseFloat(this.result_.lng)),
                             opt_icon);
    GEvent.bind(marker, "click", this, function() {
    marker.openInfoWindow(this.selected() ? this.selectedHtml() :
                                            this.markerHTML());
    });
    this.marker_ = marker;
    return marker;
}

// "Saves" this result if it has not already been saved
LocalResult.prototype.select = function() {
    if (!this.selected()) {
    this.selected_ = true;

    // Remove the old marker and add the new marker
    gMap.removeOverlay(this.marker());
    this.marker_ = null;

    // Remove the old search result from the search well
    this.resultNode_.parentNode.removeChild(this.resultNode_);

    setupLocation(this.result_.titleNoFormatting,
        this.result_.streetAddress + ", " + this.result_.city + " " +
        this.result_.region, true);
    }
}

// Returns the HTML we display for a marker
LocalResult.prototype.markerHTML = function() {
    var container = document.createElement("div");
    container.className = "locUnselected";
    container.appendChild(this.result_.html.cloneNode(true));
    var saveDiv = document.createElement("div");
    saveDiv.className = "localSelect";
    saveDiv.innerHTML = "Save this location";
    GEvent.bindDom(saveDiv, "click", this, function() {
        gMap.closeInfoWindow();
        this.select();
    });
    container.appendChild(saveDiv);
    return container;
}

// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.unselectedHtml = function() {
    var row = document.createElement("TR");
    if(this.result_.titleNoFormatting.indexOf("Starbucks") != -1)
        row.className = "locCool locUnselected";
    else
        row.className = "locUnselected";

    // title
    var td = document.createElement("TD");
    td.innerHTML = "<b>" + this.result_.titleNoFormatting + "</b>";
    GEvent.bindDom(td, "click", this, function() {
        this.marker().openInfoWindow(this.markerHTML());
    });
    row.appendChild(td);

    // address
    var td = document.createElement("TD");
    td.innerHTML = this.result_.streetAddress + "," +
        this.result_.city + ", " + this.result_.region;
    GEvent.bindDom(td, "click", this, function() {
        this.marker().openInfoWindow(this.markerHTML());
    });
    row.appendChild(td);

    // add button
    var td = document.createElement("TD");
    td.className = "localSelect";
    td.innerHTML="<img height='16' width='16' src='../common/icons/add.png' />";
    GEvent.bindDom(td, "click", this, function() {
        gMap.closeInfoWindow();
        this.select();
    });
    row.appendChild(td);

    return row;
}

// Returns the HTML we display for a result after it has been "saved"
LocalResult.prototype.selectedHtml = function() {
    return ""; //this.result_.html.cloneNode(true);
}

// Returns true if this result is currently "saved"
LocalResult.prototype.selected = function() {
    return this.selected_;
}

/* addLocation (isKey: 1 if keyboard initiated event)
   Called when user adds an entry to the location page */
function addLocation(isKey, event)
{
    /* reject keys that aren't enter */
    if(isKey == 1 && !bEnter(event))
        return true;

    if(document.createmeeting.locname.value.length < 1)
        return false;

    newLocation = setupLocation(document.createmeeting.locname.value,
        document.createmeeting.locaddr.value);

    document.createmeeting.locname.value = "";
    document.createmeeting.locaddr.value = "";

    clearSearchResults();

    return false;
}

/* setupLocation (name, address: location details)
   General Purpose Method to add a location to the array and table

    returns the location object */
function setupLocation(name, address, clipped )
{
    /* set up the location object in the array */
    var newLocation = new Object;
    newLocation.name = name;
    newLocation.address = address;
    newLocation.id = locationID;
    myLocations[locationID] = newLocation;

    /* create the table item */
    var tbody = getObj("placesTable").getElementsByTagName("TBODY")[0];
    var row = document.createElement("TR");
    row.id = 'location' + locationID;
    var td = document.createElement("TD");
    td.appendChild(document.createTextNode(newLocation.name));
    if(clipped)
        td.innerHTML += " (clipped from Google)";
    row.appendChild(td);
    td = document.createElement("TD")
    td.innerHTML = "<a title='Show Location' href='javascript:void(null)' " +
        "onclick='showLocation(" + locationID + ")'>" +
        newLocation.address + "</a>";
    row.appendChild(td);
    td = document.createElement("TD")
    td.innerHTML = "<a href='javascript:void(null)' tabindex='5' " +
        "onclick='removeLocation(0," + locationID + ")' onkeypress='" +
        "removeLocation(1," + locationID + ")'>" +
        "<img height='16' width='16' src='../common/icons/cross.png' /></a>";

    row.appendChild(td);
    tbody.appendChild(row);

    /* hide the <no location> entry */
    getObj("noLocation").style.display = 'none';

    /* scroll the map */
    if(newLocation.address.length > 0 && gGeocoder)
    {
        gGeocoder.getLatLng(newLocation.address,
        function(point) {
            if (!point && DEBUG) {
                alert("DEBUG: " + newLocation.address +
                    " not found on map");
                newLocation.point = null;
            } else {
                newLocation.point = point;
                gMap.panTo(point);
                newLocation.marker = new GMarker(point);
                gMap.addOverlay(newLocation.marker);
                newLocation.marker.openInfoWindowHtml(
                    generateMarkerText(newLocation));
                GEvent.bind(newLocation.marker, "click", this, function() {
                    newLocation.marker.openInfoWindow(generateMarkerText(
                        newLocation));
                });
            }
        });
    }

    stripePage(); // re-do the stripes
    locationID++;

    return newLocation;
}

function generateMarkerText(loc)
{
    return "<b>" + loc.name + "</b><br />" + loc.address;
}

/* showLocation (locationID: id to display)
   Moves map to show a particular address */
function showLocation(locationID)
{
    if(myLocations[locationID].point == null)
        return;
    //gMap.panTo(myLocations[locationID].point);
    myLocations[locationID].marker.openInfoWindowHtml(
        generateMarkerText(myLocations[locationID]));
};

/* removeLocation (isKey: 1 if keyboard initiated event, locationID: item id)
   Hides the address specified and removes it from locations array */
function removeLocation(isKey, locationID)
{
    /* reject keys that aren't enter */
    if(isKey == 1 && !bEnter())
        return true;

    // sanity check
    if(locationID >= myLocations.length)
        return false;

    // check if only one entry
    var entries = 0;
    for(var i=0;i<myLocations.length;i++)
        if(myLocations[i] != null)
            entries++;
    if(entries <= 1)
        getObj("noLocation").style.display = '';

    // now clear out the overlay & delete the object
    if(myLocations[locationID].marker)
    {
        gMap.removeOverlay(myLocations[locationID].marker);
        gMap.closeInfoWindow();
    }
    var soonDead = myLocations[locationID];
    myLocations[locationID] = null;
    getObj("location" + locationID).style.display = 'none';
    delete soonDead;

    stripePage(); // re-do the stripes
    return false;
}

/* locBar (barid: integer tab to display)
   This is a simple tab function that shows one tab and hides others */
function locBar(barid)
{
    // hide old bar element(s)
    for(var i=0;i<2;i++)
        if(i != barid)
        {
            getObj("locTab" + i).style.display = "none";
            getObj("locTabBar" + i).className = "locBarInactive";
        }

    getObj("locTab" + barid).style.display = "";
    getObj("locTabBar" + barid).className = "locBar";
}

/**************************************************************************
 * fill page
 **************************************************************************/

function windowHeight() {
    var alto= 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        alto= window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        alto= document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        alto= document.body.clientHeight;
    }
    return alto;
}

function fillthescreen() {
    winH = windowHeight(); //This returns the screen heigth
    heightNeeded=winH-285; //We need to substract the footer height
    if( typeof( window.innerWidth ) != 'number' ) { //Explorer doesn't recognize minHeight
        document.getElementById('bodycontent').style.height=heightNeeded+'px'; //So, we use height (and explorer bug)
    }
    document.getElementById('bodycontent').style.minHeight=heightNeeded+'px'; //For every other browser, we use minHeight
}

/**************************************************************************
 * Contacts Page
 **************************************************************************/

var myPeople = new Array();
var personID = 0;


function onABCommComplete() {
    addPeople(0);
}

function showImport(isKey)
{
    /* reject keys that aren't enter */
    if(isKey == 1 && !bEnter())
        return true;

    showPlaxoABChooser('addpeople', '/meetingstarter/addressBook.html');
    return false;
}

function addPeople(isKey)
{
    /* reject keys that aren't enter */
    if(isKey == 1 && !bEnter())
        return true;

    if(document.createmeeting.addpeople.value.length < 1)
        return false;

    /* strip all delimiters, get an array of words */
    var people = document.createmeeting.addpeople.value.split(/[ ,"<>\n\t]/);
    document.createmeeting.addpeople.value = "";

    var person = new Object; person.name = "";
    for(var i=0;i<people.length;i++)
    {
        if(people[i].length < 1)
            continue;
        if(people[i].indexOf("@") != -1) // found an e-mail - save this person
        {
            person.email = people[i];
            person.id = personID;

            // make sure we don't have duplicates
            var duplicated = false;
            for(var j=0;j<personID;j++)
                if(myPeople[j] != null && myPeople[j].email == person.email)
                {
                    delete person;
                    var person = new Object; person.name = "";
                    duplicated = true;
                    break;
                }
            if(duplicated)
                continue;

            myPeople[personID] = person;

    /* create the table item */
    var tbody = getObj("peopleTable").getElementsByTagName("TBODY")[0];
    var row = document.createElement("TR");
    row.id = 'person' + personID;
    var td = document.createElement("TD");
    if(person.name.length > 0)
    {
        td.appendChild(document.createTextNode(person.name));
        row.appendChild(td);
        td = document.createElement("TD")
    }
    else
        td.colSpan = "2";
    td.appendChild(document.createTextNode(person.email));
    row.appendChild(td);
    td = document.createElement("TD")
    td.innerHTML = "<a href='javascript:void(null)' tabindex='5' " +
        "onclick='removePerson(0,0," + personID + ")' onkeypress='" +
        "removePerson(1,0," + personID + ")'>" +
        "<img height='16' width='16' src='icons/cross.png' /></a>";
    row.appendChild(td);
    tbody.appendChild(row);

    /* hide the <no location> entry */
    getObj("noGuests").style.display = 'none';

            personID++;
            var person = new Object; person.name = "";
        }
        else
            person.name += " " + people[i];
    }

    stripePage(); // re-do the stripes

    // delete the last object that didn't get matched
    delete person;
}

/**
  removePerson (isKey: 1 if keyboard initiated event,
                isFriend: originated from friend list,
                friendID: item id)

  Hides the address specified and removes it from locations array
**/
function removePerson(isKey, isFriend, friendID)
{
    /* reject keys that aren't enter */
    if(isKey == 1 && !bEnter())
        return true;

    // sanity check
    if(friendID >= myPeople.length)
        return false;

    // check if only one entry
    var entries = 0;
    for(var i=0;i<myPeople.length;i++)
        if(myPeople[i] != null)
            entries++;
    if(entries <= 1)
        getObj("noGuests").style.display = '';

    var soonDead = myPeople[friendID];
    myPeople[friendID] = null;
    getObj("person" + friendID).style.display = 'none';
    delete soonDead;

    stripePage(); // re-do the stripes
    return false;
}

/**************************************************************************
 * Time/Date Page
 **************************************************************************/

var todayDate    = new Date();
var dates        = new Array();
var dateCalendar = null;
var selStart     = null;
var selEnd       = null;

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(val, fromIndex) {
        if (typeof(fromIndex) != 'number') fromIndex = 0;
        for (var index = fromIndex,len = this.length; index < len; index++)
            if (this[index] == val) return index;
        return -1;
    }
}

function dateToDays(date) {
    return Math.floor(date.getTime()/1000/3600/24)+1;
}

/**
  zeroPad (num: number to convert,
           width: number of characters to make)

  Add zeros to the number until width is reached
**/
function zeroPad(num, width) {
    num = num.toString();
    while(num.length < width)
        num = "0" + num;
    return num;
}

/**
  dateToString (date: date object to convert)

  m/d/yy date to string conversion
**/
function dateToString(date) {
    date = new Date(date*1000*3600*24);
    var y = zeroPad(date.getFullYear() - 2000, 2);
    var m = date.getMonth()+1;   // integer, 0..11
    var d = date.getDate();      // integer, 1..31
    return m + "/" + d + "/" + y;
}

/**
  generateDateString (dateList: the date list object to gen for)

  Take a list of active dates and create a string suitable for printing
**/
function generateDateString(dateList)
{
    dateList.sort();
    var string = "";
    var last = null;
    var consecutive = false;
    for (var i = 0; i < dateList.length; i++)
    {
        if(last == null)
            string += "," + dateToString(dateList[i]);
        else if(dateList[i] - last > 1) // not consecutive
        {
            if(consecutive)
                string += "-" + dateToString(last);
            string += ","  + dateToString(dateList[i]);
            consecutive = false;
        }
        else
            consecutive = true;
        last = dateList[i];
    }
    if(consecutive)
        string += "-" + dateToString(last);
    return string.slice(1);
}

function dateDragged(calendar, date1, date2) {
    if (!date2)
    {
        date2 = selEnd;
    }

    // swap if necessary
    if(date1 > date2)
    {
        var tmp = date2;
        date2 = date1;
        date1 = tmp;
    }

    var selFirst = null;
    var selectedNumber = 0;
    for(var i = dateToDays(date1); i <= dateToDays(date2); i++)
    {
        var dx = dates.indexOf(i);
        if(dx == -1)
        {
            selectedNumber = null;
            dates.push(i);
        }
        else
        {
            if(selFirst == null)
                selFirst = dx;
            if(selectedNumber != null)
                selectedNumber++;
        }
    }

    if(selectedNumber != null) // wanted to clear them, actually
    {
        dates.splice(selFirst, selectedNumber);
    }

    selStart = null;
    selEnd = null;
    calendar.refresh();
};

function dateDragMove(calendar, date1, date2) {
    selStart = date1;
    if (date2) {
        selEnd = date2;
    }

    calendar.refresh();
};

function dateStatus(date, y, m, d) {
    if(selStart < selEnd)
    {
        if ( date >= selStart &&  date <= selEnd )
            return "selecting";
    }
    else
    {
        if ( date <= selStart &&  date >= selEnd )
            return "selecting";
    }
    if ( dates.indexOf(dateToDays(date)) > -1 )
        return "special";
    return false;
};

function createCalendars()
{
    var today = dateToDays(new Date());
    for(var i = 0; i < 7; i++)
    {
        dates.push(today+i);
    }

    dateCalendar = new Calendar(0, null, null, null);
    dateCalendar.setDateStatusHandler(dateStatus);
    dateCalendar.weekNumbers = false;
    dateCalendar.dragUpHandler = dateDragged;
    dateCalendar.dragMoveHandler = dateDragMove;
    dateCalendar.create(getObj("datecal"));
    dateCalendar.refresh();
}

function clearDates()
{
    dates = new Array();
    dateCalendar.refresh();
}
 
/**************************************************************************
 * Submission
 **************************************************************************/
function eventActivate(){
    elem = document.getElementById('status');
    done = document.getElementById('done');
    if (elem.value == '3') {
        elem.value = '2';
        
    }
    else{
        elem.value='3';
    }
    done.value="listing.z";
    submitEvent(0);return false;
}
 
 
function escTrim(text) {
    var str = "";
    if(text)
        str = new String(text);
    return escape(str.replace(/^\s+|\s+$/g,""));
}

function submitEvent(isKey)
{
    /* reject keys that aren't enter */
    if (isKey == 1 && !bEnter()) {
		return true;
	}
	
	/*Stop submit if eventName is blank is found */
	if (document.mainform.eventName.value == "") {
		alert("Your event is missing a name.");
		return false;
	}
    /*Stop submit if paymentConfm != payment is blank is found */
    if (document.mainform.eventOnlinePaymentIDconfirm.value != document.mainform.eventOnlinePaymentID.value){
          alert("Your online payment Paypal email doesn't match the Paypal email confirmation. Go to the payments tab to fix this.");
        }

    /*Check that the time fields are valid */
        if (document.mainform.startTime.value!=""){
            if(IsValidTime(document.mainform.startTime.value, "Start Time")==false){
                return false;
            }
        }
        if (document.mainform.endTime.value!=""){
           if(IsValidTime(document.mainform.endTime.value, "End Time")==false){
				return false;
            } 
        }
        if (document.mainform.regTime.value!=""){
            if(IsValidTime(document.mainform.regTime.value, "Reg Time")==false){
                return false;
            } 
        }

        // from survey.js bring together custom questions
        bringTogetherQuestions();
    
    // build up the location info
    var tempStr = "";
    for(var i=0;i<myLocations.length;i++)
        if(myLocations[i] != null)
        {
            tempStr += escTrim(myLocations[i].id) + ",";
            tempStr += escTrim(myLocations[i].name) + ",";
            tempStr += escTrim(myLocations[i].address) + ";";
        }
		if(tempStr!=""){
    document.mainform.locations.value = tempStr;
	}
    updateLink(document.mainform.eventName);
    document.mainform.action='edit-update.z';
        
    if(LETSAUTH)
        auth_module.showLogin(function() {
            document.mainform.submit();
        });
    else
        document.mainform.submit();
        
    return false;

}



//]]>