var events_mes_err = [ "Oops, nothing to show here yet. Try a nearby place above, or start adding events to see them here.",
               "Your search didn't match any TYPE_EVENT events.... yet.",
               "No forthcoming TYPE_EVENT events were found in location. Please visit our events homepage to search  for more events.",
               "Sorry, we have no TYPE_EVENT forthcoming events!",
               "No TYPE_EVENT forthcoming events found"
             ]

var img_music = "http://static.fizber.com/images/events/music.png";
var img_sport = "http://static.fizber.com/images/events/sport.png";
var img_art = "http://static.fizber.com/images/events/art.png";
var img_media = "http://static.fizber.com/images/events/media.png";
var img_social = "http://static.fizber.com/images/events/social.png";
var img_education = "http://static.fizber.com/images/events/education.png";
var img_commercial = "http://static.fizber.com/images/events/comercial.png";
var img_festival = "http://static.fizber.com/images/events/festival.png";
var img_others = "http://static.fizber.com/images/events/other.png";
var img_humor = "http://static.fizber.com/images/events/humor.png";
var img_politics = "http://static.fizber.com/images/events/politics.png";
var img_family = "http://static.fizber.com/images/events/family.png";

var baseIconStar = null;
// icons
var events_gHouse = null;
var events_house = "";
var events_gMap = null;
var caregory_id = null;

function onload_tab_events() {
         if (events_gMap!= null){
             events_gMap.checkResize();
             return;
         } 
         events_gMap = new GMap(document.getElementById("google_map_tab_events"));
         events_gMap.addControl(new GSmallMapControl());
         events_gMap.addControl(new GMapTypeControl());
         events_geocoder = new GClientGeocoder();
         events_gMap.setCenter(new GLatLng(37.4419, -105.1419), 3);
         
		 baseIconStar = new GIcon();
         baseIconStar.image = "http://www.fizber.com/static/images/drivescore/star2.gif";
         baseIconStar.iconSize = new GSize(24, 24);
         baseIconStar.iconAnchor = new GPoint(12, 23);
         baseIconStar.infoWindowAnchor = new GPoint(12, 2);
		    
         ev_ic = new GIcon();
         ev_ic.iconSize = new GSize(24, 26);
         ev_ic.iconAnchor = new GPoint(12, 26);
         ev_ic.infoWindowAnchor = new GPoint(12, 2);
         
         geocoder = new GClientGeocoder();
         if (zoom_city){
                if (zoom_city["iscoord"] == 1){
                   //alert(1);  
                   var point = new GLatLng(zoom_city["lat"],zoom_city["lng"]);
                   events_gMap.setCenter(point, 10);
                }
                 else if(state){
                    if (state["iscoord"] == 1){
                       var point = new GLatLng(state["lat"],state["lng"]);
                       events_gMap.setCenter(point, 6);
                    }
                    else
                         events_gMap.setCenter(new GLatLng(37.4419, -105.1419), 3);
                 }
         }
         else 
             if(state){
                if (state["iscoord"] == 1){
                   var point = new GLatLng(state["lat"],state["lng"]);
                   events_gMap.setCenter(point, 6);
                }
                else
                   events_gMap.setCenter(new GLatLng(37.4419, -105.1419), 3);
             }
             
         //gdir = new GDirections(gMap, parent.document.getElementById("directions_tab_map"));
         window.setTimeout(refreshEvents,2);
         window.setTimeout(starsView, 0);

        caregory_id = { 
                    "1":{"id":"1","name":"Music","description":"Concerts, nightlife, raves","gIcon":new GIcon(ev_ic,img_music),"t":"music"},
                    "2":{"id":"2","name":"Performing/Visual Arts","description":"Theatre, dance, opera, exhibitions","gIcon":new GIcon(ev_ic,img_art),"t":"art"},
                    "3":{"id":"3","name":"Media","description":"Film, book readings","gIcon":new GIcon(ev_ic,img_media),"t":"media"},
                    "4":{"id":"4","name":"Social","description":"Rallies, gatherings, user groups","gIcon":new GIcon(ev_ic,img_social),"t":"social"},
                    "5":{"id":"5","name":"Education","description":"Lectures, workshops","gIcon":new GIcon(ev_ic,img_education),"t":"education"},
                    "6":{"id":"6","name":"Commercial","description":"Conventions, expos, flea markets","gIcon":new GIcon(ev_ic,img_commercial),"t":"commercial"},
                    "7":{"id":"7","name":"Festivals","description":"Big events, often multiple days","gIcon":new GIcon(ev_ic,img_festival),"t":"festival"},
                    "8":{"id":"8","name":"Sports","description":"Sporting events, recreation","gIcon":new GIcon(ev_ic,img_sport),"t":"sport"},
                    "10":{"id":"10","name":"Other","description":"Who knows?","gIcon":new GIcon(ev_ic,img_others),"t":"other"},
                    "11":{"id":"11","name":"Comedy","description":"Stand-up, improv, comic theatre","gIcon":new GIcon(ev_ic,img_humor),"t":"humor"},
                    "12":{"id":"12","name":"Politics","description":"Rallies, fundraisers, meetings","gIcon":new GIcon(ev_ic,img_politics),"t":"politics"},
                    "13":{"id":"13","name":"Family","description":"Family/kid-oriented music, shows, theatre","gIcon":new GIcon(ev_ic,img_family),"t":"family"}
                }
         
}

function starsView(){

         if (stars==null)
            return;
         var c = stars.length;
         for (var i=0; i<c && i<4; i++)
         {    
              var point = new GLatLng(parseFloat(stars[i]["lat"]),
                  parseFloat(stars[i]["lng"]));
              marker = createMarkerStar(point,stars[i]) 
              stars[i]["marker"] = marker;
              events_gMap.addOverlay(marker);
         }
         

}

var f_showAllStars = false;
function showAllStars(){
         if (stars==null)
            return;
         if (f_showAllStars)
            return;
         f_showAllStars = true; 
         var c = stars.length;
         for (var i=4; i<c; i++)
         {    
              var point = new GLatLng(parseFloat(stars[i]["lat"]),
                  parseFloat(stars[i]["lng"]));
              marker = createMarkerStar(point,stars[i]) 
              stars[i]["marker"] = marker;
              events_gMap.addOverlay(marker);
         }
}

function showStarsInfo(i){
         stars[i]["marker"].openInfoWindowHtml(stars[i]["marker"].cont);
         
}


function createMarkerStar(point, obj) {
  var icon = new GIcon(baseIconStar);
  var marker = new GMarker(point,icon);
  var htmltext = "<div style='width:320px;hiegth:65px;' >" + obj["last_name"]  + " " + obj["first_name"] + "<br/>" +
  "Address: "+ obj['address']  + " </div> "// +
  marker.cont = htmltext;
  GEvent.addListener(marker, "click", function() {  marker.openInfoWindowHtml(marker.cont); } );
  return marker;
}

var list_events = [];
var list_markers = [];

function refreshEvents(){
	$('#events_lists').empty()
	$('#events_lists_error').empty()
	$('#form_edit_events input[@checked]').each(function (){
           getEvents(caregory_id[$(this).val()])
    	}
	);

}
    
function getEvents(el){
         GDownloadUrl("http://events.fizber.com/search_events_loc.html?loc="+loc+"&id_category="+ el["id"], 
                                        function (data) { (showEventsInfo(data, 
                                                        el["gIcon"] ,el["name"], el["t"])) });
    }

function eventsMarkerZIndex (marker,b) {
        return 20000000;//GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

function showEventsInfo(data, gIcon, event_name, id_div){
     var xml = GXml.parse(data);
     var evs = xml.documentElement.getElementsByTagName("event");
     if (evs.length==0){
        ht = ""
        rnd = Math.round(Math.random() * 4);
        //alert(rnd);
        mes = events_mes_err[rnd];
        mes = mes.replace(/TYPE_EVENT/g, event_name);
        mes = mes.replace(/LOC/g, loc);
        ht += "<b class='opt "+id_div+"' id='events_"+id_div+"'></b>  <b style='color:#3E7095;' >" + mes + " </b><br />"
        ht += "<br />" 
        $(ht).appendTo('#events_lists_error');
        return;
     }
     
     ht = ""
     ht += "<b class='opt " + id_div + "' id='events_"+id_div+"'> </b>  <b style='color:#3E7095;' >" + event_name+ "</b><br />"
     ht += "<table class='tbl3' style='width:680px;font-size:100%' >"
     ht += "<tr>"
     ht += "<th> Date </th>"
     ht += "<th> Time </th>" 
     ht += "<th> Events </th>"
     ht += "<th>&nbsp;</th>" 
     ht += "</tr>"
      
      
     for (var i=0; i<evs.length && i<6; i++){
        //alert("5 " + i);
        var dt = new Date(getDateFromFormat(evs[i].getAttribute("start_time") + " " +  evs[i].getAttribute("start_date"), "HH:mm:ss yyyy-MM-dd"));
        var marker = showMarkerEvents(evs[i], gIcon);
        events_gMap.addOverlay(marker);
        if (i%2!=0)
           ht +=  " <tr style='background:#EAF8FF;cursor:pointer; cursor:hand; '  onmouseout='{this.style.background=\"#EAF8FF\"}' onmouseover='{this.style.background=\"#ffc\"}' >"
        else
           ht +=  " <tr style='cursor:pointer; cursor:hand; ' onmouseout='{this.style.background=\"#FFFFFF\"}' onmouseover='{this.style.background=\"#ffc\"}'  >"
        ht += "<td nowrap='nowrap' onclick='viewEventsInfo("+ list_events.length +");events_showDescription("+  list_events.length +");return false;'> " + formatDate(dt,"dd NNN") + " </td>"
        ht += "<td  onclick='viewEventsInfo("+ list_events.length +");events_showDescription("+  list_events.length +");return false;'> " + formatDate(dt,"HH:mm") + " </td>"
        ht += "<td id='"+ list_events.length+"_event1' onclick='viewEventsInfo("+ list_events.length +");events_showDescription("+  list_events.length +");return false;'> <div   style='overflow:hidden;width:580px; height:16px;' ><b>" + evs[i].getAttribute("name") + " </b>"
        
        //alert(52)
        
        if (evs[i].getAttribute("description") != ""){
            ht += "<span  style='text-decoration:none;color:#999;'> - " + evs[i].getAttribute("description") + " </span>           </div> "
            
            ht += "<div id='"+ list_events.length+"_event' style='display:none' colspan='3' width='560px;'><br/>" + evs[i].getAttribute("description") + "</div>"
            ht += "</td>"
        }
        else
            {
            ht += "<span style='text-decoration:none;color:#999;'> " + evs[i].getAttribute("description") + " </span> </div>"   
            ht += "<div id='"+ list_events.length+"_event' style='display:none' colspan='3' width='560px;'>" + evs[i].getAttribute("description") + "</div>"
            ht += "</td>"
            }
        ht += "<td nowrap='nowrap' style='font-size:85%'><a href='#events_map_' onclick='viewEventsInfo("+list_events.length +");'>Map It</a></td>"     
        ht += "</tr>"
        list_markers.push(marker)
        list_events.push(evs[i]);
      }
      ht +=  "</table><br/>"
      $(ht).appendTo('#events_lists');
    }

function events_showDescription(i){
    try{   
      el  =  $("#"+i+"_event")
      el1 =  $("#"+i+"_event1")
      if (el.style.display == 'none'){
         el.style.display = 'block';
         el1.innerHTML = "<div   style='overflow:hidden;width:580px; height:16px;' ><b>" + list_events[i].getAttribute("name") + " </b>"
         if (list_events[i].getAttribute("description") != ""){
           el1.innerHTML +=  "</div> "
            el1.innerHTML += "<div id='"+ i+"_event' style='display:block' colspan='3' width='560px;'><br/>" + list_events[i].getAttribute("description") + "</div>"

         }

         }
      else {
         el.style.display = 'none';
          ht = "<div   style='overflow:hidden;width:580px; height:16px;' ><b>" + list_events[i].getAttribute("name") + " </b>"
         if (list_events[i].getAttribute("description") != ""){
           ht += "<span  style='text-decoration:none;color:#999;'> - " + list_events[i].getAttribute("description") + " </span>           </div> "
            
            ht += "<div id='"+ i+"_event' style='display:none' colspan='3' width='560px;'><br/>" + list_events[i].getAttribute("description") + "</div>"
            el1.innerHTML = ht;
         }
      }
   } catch(e){}
      
    }

function viewEventsInfo(i){
    if (list_markers[i]){{
      list_markers[i].openInfoWindowHtml(list_markers[i]["cont"]);
        }}
    }
    

function showMarkerEvents(obj, gIcon){
  var point = new GLatLng(obj.getAttribute("latitude"),
                              obj.getAttribute("longitude"));
   var icon = new GIcon(gIcon);                       
  var events_marker = new GMarker(point,{"icon":icon,'zIndexProcess': eventsMarkerZIndex });
  var htmlText = "<div style='width:375px;'> " + obj.getAttribute("name") + "</div>";
  GEvent.addListener(events_marker, "click", function() {  events_marker.openInfoWindowHtml(htmlText); } );
  events_marker.cont = htmlText;
  return events_marker;
}

 
function setEventCoockie(){
    var m = new Array();
    var l = document.getElementById('form_edit_events').l_events;
    for (var i = 0; i < l.length; i++) {
        if (l[i].checked) 
            m.push(l[i].value);
    }
    //alert(m); 
    SetCookie('list_events', m.toString(), '/', '/');
}

//$(document).ready(onload_tab_events); 

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
    format=format+"";
    var result="";
    var i_format=0;
    var c="";
    var token="";
    var y=date.getYear()+"";
    var M=date.getMonth()+1;
    var d=date.getDate();
    var E=date.getDay();
    var H=date.getHours();
    var m=date.getMinutes();
    var s=date.getSeconds();
    var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
    // Convert real date parts into formatted versions
    var value=new Object();
    if (y.length < 4) {y=""+(y-0+1900);}
    value["y"]=""+y;
    value["yyyy"]=y;
    value["yy"]=y.substring(2,4);
    value["M"]=M;
    value["MM"]=LZ(M);
    value["MMM"]=MONTH_NAMES[M-1];
    value["NNN"]=MONTH_NAMES[M+11];
    value["d"]=d;
    value["dd"]=LZ(d);
    value["E"]=DAY_NAMES[E+7];
    value["EE"]=DAY_NAMES[E];
    value["H"]=H;
    value["HH"]=LZ(H);
    if (H==0){value["h"]=12;}
    else if (H>12){value["h"]=H-12;}
    else {value["h"]=H;}
    value["hh"]=LZ(value["h"]);
    if (H>11){value["K"]=H-12;} else {value["K"]=H;}
    value["k"]=H+1;
    value["KK"]=LZ(value["K"]);
    value["kk"]=LZ(value["k"]);
    if (H > 11) { value["a"]="PM"; }
    else { value["a"]="AM"; }
    value["m"]=m;
    value["mm"]=LZ(m);
    value["s"]=s;
    value["ss"]=LZ(s);
    while (i_format < format.length) {
        c=format.charAt(i_format);
        token="";
        while ((format.charAt(i_format)==c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
            }
        if (value[token] != null) { result=result + value[token]; }
        else { result=result + token; }
        }
    return result;
    }
    
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
    var digits="1234567890";
    for (var i=0; i < val.length; i++) {
        if (digits.indexOf(val.charAt(i))==-1) { return false; }
        }
    return true;
    }
function _getInt(str,i,minlength,maxlength) {
    for (var x=maxlength; x>=minlength; x--) {
        var token=str.substring(i,i+x);
        if (token.length < minlength) { return null; }
        if (_isInteger(token)) { return token; }
        }
    return null;
    }
    
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
    val=val+"";
    format=format+"";
    var i_val=0;
    var i_format=0;
    var c="";
    var token="";
    var token2="";
    var x,y;
    var now=new Date();
    var year=now.getYear();
    var month=now.getMonth()+1;
    var date=1;
    var hh=now.getHours();
    var mm=now.getMinutes();
    var ss=now.getSeconds();
    var ampm="";
    
    while (i_format < format.length) {
        // Get next token from format string
        c=format.charAt(i_format);
        token="";
        while ((format.charAt(i_format)==c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
            }
        // Extract contents of value based on format token
        if (token=="yyyy" || token=="yy" || token=="y") {
            if (token=="yyyy") { x=4;y=4; }
            if (token=="yy")   { x=2;y=2; }
            if (token=="y")    { x=2;y=4; }
            year=_getInt(val,i_val,x,y);
            if (year==null) { return 0; }
            i_val += year.length;
            if (year.length==2) {
                if (year > 70) { year=1900+(year-0); }
                else { year=2000+(year-0); }
                }
            }
        else if (token=="MMM"||token=="NNN"){
            month=0;
            for (var i=0; i<MONTH_NAMES.length; i++) {
                var month_name=MONTH_NAMES[i];
                if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
                    if (token=="MMM"||(token=="NNN"&&i>11)) {
                        month=i+1;
                        if (month>12) { month -= 12; }
                        i_val += month_name.length;
                        break;
                        }
                    }
                }
            if ((month < 1)||(month>12)){return 0;}
            }
        else if (token=="EE"||token=="E"){
            for (var i=0; i<DAY_NAMES.length; i++) {
                var day_name=DAY_NAMES[i];
                if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
                    i_val += day_name.length;
                    break;
                    }
                }
            }
        else if (token=="MM"||token=="M") {
            month=_getInt(val,i_val,token.length,2);
            if(month==null||(month<1)||(month>12)){return 0;}
            i_val+=month.length;}
        else if (token=="dd"||token=="d") {
            date=_getInt(val,i_val,token.length,2);
            if(date==null||(date<1)||(date>31)){return 0;}
            i_val+=date.length;}
        else if (token=="hh"||token=="h") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<1)||(hh>12)){return 0;}
            i_val+=hh.length;}
        else if (token=="HH"||token=="H") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<0)||(hh>23)){return 0;}
            i_val+=hh.length;}
        else if (token=="KK"||token=="K") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<0)||(hh>11)){return 0;}
            i_val+=hh.length;}
        else if (token=="kk"||token=="k") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<1)||(hh>24)){return 0;}
            i_val+=hh.length;hh--;}
        else if (token=="mm"||token=="m") {
            mm=_getInt(val,i_val,token.length,2);
            if(mm==null||(mm<0)||(mm>59)){return 0;}
            i_val+=mm.length;}
        else if (token=="ss"||token=="s") {
            ss=_getInt(val,i_val,token.length,2);
            if(ss==null||(ss<0)||(ss>59)){return 0;}
            i_val+=ss.length;}
        else if (token=="a") {
            if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
            else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
            else {return 0;}
            i_val+=2;}
        else {
            if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
            else {i_val+=token.length;}
            }
        }
    // If there are any trailing characters left in the value, it doesn't match
    if (i_val != val.length) { return 0; }
    // Is date valid for month?
    if (month==2) {
        // Check for leap year
        if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
            if (date > 29){ return 0; }
            }
        else { if (date > 28) { return 0; } }
        }
    if ((month==4)||(month==6)||(month==9)||(month==11)) {
        if (date > 30) { return 0; }
        }
    // Correct hours value
    if (hh<12 && ampm=="PM") { hh=hh-0+12; }
    else if (hh>11 && ampm=="AM") { hh-=12; }
    var newdate=new Date(year,month-1,date,hh,mm,ss);
    return newdate.getTime();
    }
    
function parseDate(val) {
    var preferEuro=(arguments.length==2)?arguments[1]:false;
    generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
    monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
    dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
    var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
    var d=null;
    for (var i=0; i<checkList.length; i++) {
        var l=window[checkList[i]];
        for (var j=0; j<l.length; j++) {
            d=getDateFromFormat(val,l[j]);
            if (d!=0) { return new Date(d); }
            }
        }
    return null;
    }
    
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

