/**
 * @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 initialize() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(28.28125, 10.54681317351514), 2);
		
		map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		
		GEvent.addListener(map, "click", function(overlay, latlng)
		{
			if (latlng)
			{
				marker = new GMarker(latlng, {draggable:true});
				map.addOverlay(marker);
			}
			
			GEvent.addListener(marker, 'mouseup', function()
			{
				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="26" rows="4" id="description" style="width: 430px;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?1231270331" target="upload_frame"> \
							<p id="f1_upload_process" style="height: auto;">Loading...<br/><img src="http://www.streetartlocator.com/images/loader.gif" /></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="Add New Location" 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 html ='<table class="g_table"> \
				<tr> \
					<td>Your Name:</td> \
					<td><input type="text" id="name" /></td> \
					<td>What can be found there:</td> \
				</tr> \
				<tr> \
					<td>Your Email:</td> \
					<td><input type="text" id="your_email"/></td> \
					<td rowspan="3"> \
						<textarea name="description" cols="26" rows="4" id="description" style="width: 170px;"></textarea> \
					</td> \
				</tr> \
				<tr> \
					<td>Location is:</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>Give it a name:</td> \
					<td><input type="text" id="title" /></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="2"> \
						<form name="uploadForm" id="uploadForm" enctype="multipart/form-data" method="post" action="http://www.streetartlocator.com/upload.php?1231270331" target="upload_frame"> \
							<p id="f1_upload_process" style="height: auto;">Loading...<br/><img src="http://www.streetartlocator.com/images/loader.gif" /></p> \
							<p id="f1_upload_form" align="left" style="padding-bottom: 35px; margin: 0px;"> \
								<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> \
								<label style="float:left"><input style="width:130px; margin-top: 10px;" type="submit" name="submitBtn" class="sbtn" value="Add New Location" onclick="return saveData();" /></label> \
							</p> \
							<iframe id="upload_frame" name="upload_frame" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe> \
						</form> \
					</td> \
				</tr> \
				</table>';*/
				
				marker.openInfoWindow(html);
				point = marker.getLatLng();
				var latLngStr = "Lat = " + point.lat() + ", Long = " + point.lng();
			});
			
			GEvent.addListener(marker, 'infowindowopen', function()
			{
				initForms();
			});
			
			GEvent.addListener(marker, 'infowindowclose', function()
			{
				opened = false;
			});
		});
	}
}
	
	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.');
						marker.closeInfoWindow();
					}
					
					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);
							marker.closeInfoWindow();
			  				jQuery.facebox('Your location was added');
						}
					});
					
				},error: function()
				{
					jQuery.facebox('Can\'t upload file. Please try again.');
					marker.closeInfoWindow();
				}
			});
			
			$('.multi').MultiFile({ 
					accept:'gif|jpg|jpeg', 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();
			return false;
		}
		else if(vAlert != "")
		{
			jQuery.facebox(vAlert);
			return false;
		}
	}