/**
 * @author Bumblebee
 * @required :
 * jquery_1-2-6
 * jquery.form
 * jquery.MetaData
 * jquery.MultiFile
 * 
 */
var marker = null;
var point = null;
var vAlert = "";
var opened = false;

function validate() {
	vAlert = '';
	if(document.getElementById("name").value == ""){
		vAlert = "Please enter the name ";
		return false;
	}else
	if (! isValidEmail(document.getElementById("your_email").value)) {
        vAlert = "Please enter a valid email address";
        return false;
    }
    else if(document.getElementById("title").value == ""){
		vAlert = "Please enter the title ";
		return false;
	}
	else if ($('.files:visible').length != 0 && $('.files input[type="file"]').length < 2)
	{
		vAlert = "Please select images you want to add to this location";
		return false;
	}
	else
    	return true;
  }
  
  
  function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}


  function objToString(o) {
    var s = '{';
    for (var p in o)
    s += '"' + p + '":"' + escape(o[p]) + '",';
    s = s.substr(0, s.length -1);
    return s + '}';
  }


var myinfowindow = '';
var mymarker = '';
function initialize() {

        var myOptions = {
            zoom: 2,
            center: new google.maps.LatLng(28.28125, 10.54681317351514),
            navigationControl: true,
            mapTypeControl:true,
            scaleControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            streetViewControl: false
          }     
        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
		    map.enableKeyDragZoom({
            visualEnabled: true,
            visualPosition: google.maps.ControlPosition.LEFT_TOP,
            visualPositionOffset: new google.maps.Size(35, 0),
            visualPositionIndex: null,
            visualSprite: "http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png",
            visualSize: new google.maps.Size(20, 20),
            visualTips: {
             off: "Turn on",
             on: "Turn off"
            }
         });
		/**
		 * Add marker (first step)
		 */
		google.maps.event.addDomListener(document.getElementById('add-marker-button'), 'click', function(event) {
      //place marker
      marker = null;
      marker = new google.maps.Marker({draggable:true, position: map.getCenter(), map: map});
      mymarker = marker; //to unbind click listener on third step
      var html ='<table class="g_table"> \
        <tr> \
          <td>Your Name:</td> \
          <td><input type="text" id="name" /></td> \
          <td>Your Email:</td> \
          <td><input type="text" id="your_email"/></td> \
        </tr> \
        <tr> \
          <td>Location name:</td> \
          <td><input type="text" id="title" /></td> \
          <td>Location type:</td> \
          <td> \
            <select id="type"> \
              <option value="graffiti" selected="selected">Graffiti</option> \
                <option value="stickers">Stickers</option> \
                <option value="stencil">Stencil</option> \
                <option value="painting">Painting</option> \
                <option value="sculpture">Sculpture</option> \
                <option value="installation">Installation</option> \
              <option value="gallery">Gallery</option> \
            </select> \
          </td> \
        </tr> \
        <tr> \
          <td>Description:</td> \
          <td colspan="3"> \
            <textarea name="description" cols="20" rows="3" id="description" style="width: 400px;height: 60px"></textarea> \
          </td> \
        </tr> \
        <tr> \
          <td> \
            <input type="hidden" id="photo" /> \
            <input type="hidden" value="100000" name="MAX_FILE_SIZE" /> \
            <input type="hidden" id="lonbox" /> \
            <input type="hidden" id="latbox" /> \
          </td> \
          <td colspan="3"> \
            <form name="uploadForm" id="uploadForm" enctype="multipart/form-data" method="post" action="http://www.streetartlocator.com/upload.php?1328765135" target="upload_frame"> \
              <p id="f1_upload_process" style="height: auto;">Loading...<br/><img src="http://www.streetartlocator.com/images/loader.gif" width="220px" height="19px" alt="loading" /></p> \
                <table id="f1_upload_form" style="height: auto;"> \
                  <tr> \
                    <td valign="top"> \
                      <label class="files">Add an image:<br /> \
                        <input class="multi" name="file[]" type="file" /> \
                      </label> \
                      <label class="video" style="display:none"> \
                        Add a Video:<br /> \
                        <input name="video" style="margin-bottom:10px;" type="text" value="" /> \
                      </label> \
                      <br />\
                      <label><a style="color:#000" href="#" rel="add_video">Add YouTube video</a></label> \
                    </td> \
                    <td valign="top"> \
                      <label style="float:left"><input style="width:130px; margin-top: 10px;" type="submit" name="submitBtn" class="sbtn" value="Save" onclick="return saveData();" /></label> \
                    </td> \
                  </tr> \
                </table> \
              <iframe id="upload_frame" name="upload_frame" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe> \
            </form> \
          </td> \
        </tr> \
        </table>';
        var infowindow = new google.maps.InfoWindow(
                { content: html,
                  disableAutoPan: false
                });
        myinfowindow = infowindow;
      //show step 2
      $('#steps ul li.step').hide();
      $('#steps ul li.second-step').show();
      //switch step circle
      $('#steps span.circle-step-active').removeClass('circle-step-active').addClass('circle-step');
      $('#steps span.step2').addClass('circle-step-active');
      //add listener for window opening
      google.maps.event.addListener(marker, 'mouseup', function()
      {
        infowindow.open(map,marker);
        point = marker.getPosition();
        var latLngStr = "Lat = " + point.lat() + ", Long = " + point.lng(); 
      });
      
      google.maps.event.addListener(infowindow, 'domready', function()
      { 
        opened = false;
        eval(initForms());
      });
      
      google.maps.event.addListener(infowindow, 'closeclick', function()
      {
        opened = false;
      });
            
      return false;
    });
    
    /**
     * Add another marker
     */
     google.maps.event.addDomListener(document.getElementById('add-another-marker-button'), 'click', function(event) {
        $('li.step').hide();
        $('li.first-step').show();
        $('#steps span.circle-step-active').removeClass('circle-step-active').addClass('circle-step');
        $('#steps span.step1').addClass('circle-step-active');
        marker.setMap(null);
     });
    
  /**
   * Reload page
   */
   google.maps.event.addDomListener(document.getElementById('reload-page'), 'click', function(event) {
     $('li.step').hide();
     $('li.first-step').show();
      $('#steps span.circle-step-active').removeClass('circle-step-active').addClass('circle-step');
      $('#steps span.step1').addClass('circle-step-active');
     marker.setMap(null);
     map.setCenter(new google.maps.LatLng(28.28125, 10.54681317351514));
     map.setZoom(2);
     //initialize();
   });
}
	
	  
	
	function initForms()
	{ 
		if (!opened)
		{
			opened = true;
		}
		else
		{
			return false;
		}
		$('a[rel="add_video"]').click(
			function ()
			{
				$('.g_table label.files').toggle();
				$('.g_table label.video').toggle();
				if ($('.g_table label.files').css('display') == 'none')
				{
					$(this).html('Add photos');
					$('#uploadForm').attr('enctype' , '');
				}else{
					$(this).html('Add YouTube video');
					$('#uploadForm').attr('enctype' , 'multipart/form-data');
				}
				return false;
			}
		);
		$('#uploadForm').ajaxForm({
				beforeSubmit: function(a,f,o) {
					o.dataType = 'json';
					$('label.video > input').val(escape($('label.video > input').val()));
					$('#f1_upload_process').show();
					$('#f1_upload_form').hide();
				},
				success: function(data) {
				
					var photos = [];
					for (var y=0; y < data.length; y++)
					{
						if (data[y].result == 1)
						{
							photos.push(data[y].new_name);
						}
						else
						{
							if (typeof(data[y].error) != 'undefined' )
							{
								if (data[y].error != '')
								{
									alert(data[y].error)
									$('label.video > input').val('');
									$('#f1_upload_process').hide();
									$('#f1_upload_form').show();
									
									return false;
								}
							}
						}
					}
					
					if (photos.length < 1)
					{
						jQuery.facebox('Can\'t upload file(s). Please try again.');
						myinfowindow.close();
					}
					
					var video = escape($('label.video > input').val());
					var name = escape(document.getElementById("name").value);
					var email = escape(document.getElementById("your_email").value);
					var type = document.getElementById("type").value;
					var title = escape(document.getElementById("title").value);
					var description = escape(document.getElementById("description").value);
					var myfile = objToString(photos);
					
					var lat = point.lat();
					var lng = point.lng();
					
					var url = "name=" + name + "&email=" + email + "&type=" + type + "&title=" + title + "&description=" + description + "&lat=" + lat + "&lng=" + lng + "&myfile=" + myfile + '&video=' + video; // photo;
					//console.log(url);
					
					$.ajax({
						type:"POST",
						url:"http://www.streetartlocator.com/putsql.php",
						data:url,
						success: function(data_resp)
						{
							//console.log(data_resp);
							myinfowindow.close();
			  				jQuery.facebox('Your location was added');
			  				$('#facebox').css('top', '220px');
						}
					});
					
				},error: function()
				{
					jQuery.facebox('Can\'t upload file. Please try again.');
					myinfowindow.close();
				}
			});
			
			
			$('.multi').MultiFile({ 
					accept:'gif|jpg|jpeg|png', 
					max:5, 
					STRING: { 
						remove:'Remove', 
						selected:'Selected: $file', 
						denied:'Please select $ext!', 
						duplicate:'You have selected duplicate:\n$file!' 
					} 
			});
			
			
	}
	
	function saveData()
	{
		if(validate())
		{
			$('#uploadForm').submit();
			//switch to third step
			$('#steps ul li.step').hide();
      $('#steps ul li.third-step').show();
      $('#steps span.circle-step-active').removeClass('circle-step-active').addClass('circle-step');
      $('#steps span.step3').addClass('circle-step-active');
			return false;
		}
		else if(vAlert != "")
		{
			jQuery.facebox(vAlert);
			return false;
		}
	}
