/**
 * @author Bumblebee
 */
$(document).ready(function(){
var idx_img = 0;
var tmman = null;
var BmapPointsAll = [];
var g_type = '';

var d_href = window.location.href;

if (d_href.substr(7, 3) != 'www')
{
  window.location.href = d_href.replace('http://', 'http://www.');
}

if (typeof(console) == 'undefined')
{
  console = function(){
    this.log = function(asd)
    {
    }
  }
}

// getPageScroll() by quirksmode.com
function getPageScroll() {
  var xScroll, yScroll;
  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
    xScroll = self.pageXOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {   // Explorer 6 Strict
    yScroll = document.documentElement.scrollTop;
    xScroll = document.documentElement.scrollLeft;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
    xScroll = document.body.scrollLeft;  
  }
  return new Array(xScroll,yScroll) 
}

// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
  var windowHeight
  if (self.innerHeight) {  // all except Explorer
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowHeight = document.body.clientHeight;
  }  
  return windowHeight
}

var cssFix = function(){

  var u = navigator.userAgent.toLowerCase(),

  is = function(t){return (u.indexOf(t)!=-1)};

  $("html").addClass([
    (!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)
      :is('firefox/2')?'gecko ff2'
      :is('firefox/3')?'gecko ff3'
      :is('gecko/')?'gecko'
      :is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
      :is('konqueror')?'konqueror'
      :is('applewebkit/')?'webkit safari'
      :is('mozilla/')?'gecko':'',
    (is('x11')||is('linux'))?' linux'
      :is('mac')?' mac'
      :is('win')?' win':''
  ].join(''));
}();

$(document).ready
(
  function()
  {
    if ($('.add_unmapped_location').length != 0) {
      $('.add_unmapped_location input').title();
      $('.add_unmapped_location textarea').title();
    }
    
    $('a[rel="faceboxx"]').click(function(){
      var url = $(this).attr('href');
      url = url.replace('http://www.streetartlocator.com', '');
      jQuery.facebox('<iframe src="http://www.streetartlocator.com/' + url + '" height="430" width="430" frameborder="0"></iframe>');
      return false;
    });
    
    // if we in lost password page
    if ($('#lost_password').length != 0)
    {
      var loader = jQuery('<div id="loader" style="visibility: inherit;"><img src="images/loader.gif" width="220px" height="19px" alt="Loading..." style="float:left" /></div>')
      .css({position: "relative", top: ($('#email_restore').height()/2 - 10) + "px", left: ($('#email_restore').width()/2 - 30) + "px", 'z-index':"300"})
      .hide()
      .appendTo("#email_restore");
    
      $.validator.setDefaults({
        submitHandler: 
        function ()
        {
          loader.show();
          $.ajax({
                type:"POST",
                url:"lostpass.php",
                data:'email=' + $('#email_restore').val(),
                success: function(data)
                {
                  loader.hide();
                  $('#lost_password').html('<span>You will receive password soon</span>');
                }
          });
          return false;
        }
      });

      $("#lost_password").validate({
        rules: {
            email_restore: {
              required: true,
              email: true
            }
          },
        messages: {
            email_restore: "Please enter a valid email address"
          }
      });
    }
    
    // if we have login menu
    if ($("#loginscreen").length != 0)
    {
      $("#loginscreen > div > input").title();
      $("#control-container input[name='search_string']").title();
      
      $("#loginscreen > button.not-existing-class-login").livequery('click', 
      
        function ()
        {
          if ($(this).prev().find("input[name=password]").val() != "password"
            && $(this).prev().find("input[name=password]").val() != "" 
            && $(this).prev().find("input[name=email]").valid_email())
          {
            $(this).css('background', 'url(images/ajax_loader_login.gif) center center no-repeat');
            obj = $(this);
            var rem = '';
            if ($('#loginscreen input[name="remember_me"]').length != 0)
            {
              if ($('#loginscreen input[name="remember_me"]').attr('checked'))
              {
                rem = '&remember=';
              }
            }
            $.ajax({
                type:"POST",
                url:"login.php",
                data:'email=' + $(this).prev().find("input[name=email]").val() + rem + '&password=' + $(this).prev().find("input[name=password]").val(),
                success: function(data)
                {
                  data = jQuery.trim(data);
                  if (data != "100")
                  {
                    /*obj.prev().find("input[name=password]").hide();
                    obj.prev().find("input[name=email]").hide();
                    if ($('#loginscreen input[name="remember_me"]').length != 0)
                    {
                      $('#loginscreen input[name="remember_me"]').hide();
                    }*/
                    //obj.prev().find("input[name=password]").after('<a href="userpage.php">Edit your locations</a><a href="profile.php">Profile</a>');
                    obj.prev().find("input[name=password]").after('<a href="profile.php">Profile &amp; locations</a><a rel="logout" href="#">Logout</a>');
                    obj.parent().addClass('logged');
                    obj.removeClass('login');
                    obj.addClass('logged');
                    obj.attr('style','');
                    obj.attr('title', '');
                    
                    if ($("#markItUp").length != 0)
                    {
                      $('.comment_form').show();
                      $("#submit_comment").removeAttr('disabled');
                      $("#submit_comment").parent().next().remove();
                      $('.comment_form').show();
                      $('.comment > .quote').show();
                    }
                  }
                  else
                  {
                    alert ("Please enter valid email and/or pasword.\nYou can get a new password from the link at the bottom of the page");
                    obj.attr('style','');
                  }
                  
                }
            });
          }
          else
          {
            alert("Please enter valid email and/or pasword.\nYou can get a new password from the link at the bottom of the page");
            
          }
        }
      );
      
      $("#loginscreen > button.register").livequery('click', 
        function ()
        {
          $('#add-location > a.register').click();
        }
      );
      
      $("#loginscreen > button.logged").livequery('click', 
      
        function ()
        {
          
        }
      );
      logoutLinkClick = function(obj) {
          var link = $(obj);
          $(obj).css('background', 'url(images/ajax_loader_login.gif) center center no-repeat');
          obj = $("#loginscreen > button.logged");
                    
          $.ajax({
                type:"POST",
                url:"logout.php",
                data:'logout=true',
                async: false,
		timeout: 1000,
                success: function(data) {
				  //console.log('logged out from the site');
                  /*window.location = '/index.php';
                  data = jQuery.trim(data);
                  obj.prev().find("a").remove();
                  obj.removeClass('logged');
                  obj.addClass('login');
                  obj.attr('title', '');
                  obj.parent().removeClass('logged');
                                  
                  if ($("#markItUp").length != 0)
                  {
                    $("#submit_comment").attr('disabled', 'disabled');
                    $("#submit_comment").parent().after('<div class="comment">Please login to post comments</div>');
                    $('.comment_form').hide();
                    $('.comment > .quote').hide();
                  }
                  if ($('#profile').length != 0 || $('#edit_location').length != 0)
                  {
                    document.location.href = 'index.php';
                  }
                  obj.attr('style','');
                  */
                },
                error: function(data)
                {
                  obj.attr('style','');  
                }
            });
          FB.logout(function(response) {
	        //console.log('logged out from FB');
	    window.location = '/index.php';
	  });
          
          return false;
}      
      
    }
    
    // if we have instructions options
    /*if ($("#instructions").length != 0 || $("#tips").length != 0)
    {
      $("#control-container > div.icon > a").facebox();
      $("#control-container > div.icon > a[href*=instructions]").click();
    }*/
    
    // if we have lostpassword facebox
    if ($("#lostpass").length != 0)
    {
      $("a[rel=facebox]").facebox();
      
      $("#email a[rel=facebox]").click(
        function()
        {
          var loader = $('#facebox #lostpass > div.loader');
          $('#facebox form.lost_password .sbtn').click(
            function (){
              $('#facebox form.lost_password').submit();
              return false;
            }
          );
          $.validator.setDefaults({
            submitHandler: 
            function ()
            {
              loader.show();
              $.ajax({
                    type:"POST",
                    url:"lostpass.php",
                    data:'email=' + $('#facebox form.lost_password input[name=email_restore]').val(),
                    success: function(data)
                    {
                      loader.hide();
                      $('#facebox form.lost_password').html('<span>You will receive password soon</span>');
                    }
              });
              return false;
            }
          });
    
          $("#facebox form.lost_password").validate({
            rules: {
                email_restore: {
                  required: true,
                  email: true
                }
              },
            messages: {
                email_restore: "Please enter a valid email address"
              }
          });
        }
      )
    }
    /*
    $('#key_long > .key-cell > .g_graffiti').click(
      function()
      {
        changeTypeMarkers('graffiti');
      }
    );
    
    $('#key_long > .key-cell > .g_gallery').click(
      function()
      {
        changeTypeMarkers('gallery');
      }
    );
    
    $('#key_long > .key-cell > .g_painting').click(
      function()
      {
        changeTypeMarkers('painting');
      }
    );
    
    $('#key_long > .key-cell > .g_stickers').click(
      function()
      {
        changeTypeMarkers('stickers');
      }
    );
    
    $('#key_long > .key-cell > .g_stencil').click(
      function()
      {
        changeTypeMarkers('stencil');
      }
    );
    
    $('#key_long > .key-cell > .g_sculpture').click(
      function()
      {
        changeTypeMarkers('sculpture');
      }
    );
    
    $('#key_long > .key-cell > .g_installation').click(
      function()
      {
        changeTypeMarkers('installation');
      }
    );
    
    $('#key_long > .key-cell > span:hidden').click(
      function()
      {
        BmapPoints = [];
        BmapPoints = BmapPoints.concat(BmapPointsAll);
        mgr.clearMarkers();
        mgr.addMarkers(getStreetArtMarkers(1), 1);
        mgr.addMarkers(getStreetArtMarkers(2), 2);
        mgr.addMarkers(getStreetArtMarkers(3), 3);
        mgr.addMarkers(getStreetArtMarkers(4), 4);
        mgr.refresh();
        $(this).hide();
        $(this).prev().show();
        $(this).prev().prev().show();
      }
    );
    
    $('#key_long > .key-cell > span').hover(
      function()
      {
        $(this).css('text-decoration', 'underline');
      },
      function()
      {
        $(this).css('text-decoration', 'none');
      }
    );
    
    if ( $('#key_long > .key-cell').length != 0 )
    {
      BmapPointsAll = [];
      BmapPointsAll = BmapPointsAll.concat(BmapPoints);
    }
    */
    // CAROUSEL
    /*if ($("#imagecarousel").length != 0)
    {
      $("#imagecarousel > ul").html('');
      
      jQuery('#imagecarousel').jcarousel({
        
        itemLoadCallback: mycarousel_itemLoadCallback,
        scroll: 8,
        visible: 8
      });
    }*/
    
    if ($("#markItUp").length != 0)
    {
      // Add markItUp! to your textarea in one line
      $('#markItUp').markItUp(mySettings);
       
      // You can add content from anywhere in your page
      $('.quote > .add').click(function() {
        obj = $(this);
        text = '[quote="' + comments[$(this).attr('href').replace("#_","")].text +'"]';
        text+= $(this).next().html();
        text+= '[\/quote]';
         $.markItUp( {   openWith:'[quote="' + comments[$(this).attr('href').replace("#_","")].name +'"]',
                closeWith:'[\/quote]',
                placeHolder: comments[$(this).attr('href').replace("#_","")].text
              }
            );
         return false;
      });
      
      // And you can add/remove markItUp! whenever you want
      $('.toggle').click(function() {
        if ($("#markItUp.markItUpEditor").length === 1) {
           $("#markItUp").markItUpRemove();
          $("span", this).text("get markItUp! back");
        } else {
          $('#markItUp').markItUp(mySettings);
          $("span", this).text("remove markItUp!");
        }
         return false;
      });
    }
    
    if ($('#comment-section').length != 0)
    {
      setTimeout(changeImage , 6000);
      
      if ($('embed').length != 0)
      {
        $('.icon_send_to_friend > a').click(function(){
          window.location.href = '#a';
        });
        $('.icon_save_favorites > a').click(function(){
          window.location.href = '#a';
        });
      }
    }
    
    if ($("#submit_comment").length != 0)
    {
      $("#submit_comment").click(
        function ()
        {
          var button = $(this);
          button.css('background', 'url(images/ajax_loader_login.gif) center center no-repeat');
          button.attr('disabled', 'disabled');
          var url='data=';
          if ($("#markItUp").length != 0)
          {
            //var dd = new Object();
            //dd.data = $("#markItUp").val();
            //dd.data = escape(dd.data);
            //dd.data = $.toJSON(dd.data);
            //dd.location_id = $("#loc_id").val();
            url += escape($("#markItUp").val());
            url += '&location_id=' + $("#loc_id").val();
          }else
          if ($("body > .postbody").length != 0)
          {
            window.top.window.document.getElementById('submit_comment').click();
            return false;
          }
          
          $.ajax({
            type:"POST",
            url:"comment.php",
            data: url,
            success: function(data)
            {
              data = jQuery.trim(data);
              $(".markItUpPreviewFrame").remove();
              $("#markItUp").val("");
              if ($('#comment-section > div.comment:last').length != 0)
              {
                $('#comment-section > div.comment:last').after(data);
              }
              else
              {
                $('#comment-section > div.section_title').after(data);
              }
              button.attr('style', '');
              button.removeAttr('disabled');
            }
          });
        }
      );
    }
    
    $('.add_walk_btn').click(
      function()
      {
        document.location.href = 'add_route.php';
      }
    );
    
    if ($("#profile").length != 0 || $('#edit_location').length != 0 || $('#route').length != 0)
    {
      if (user_editable)
      {
        $("#image-info > div.user_name").editable("update_user.php", {
          indicator : "<img src='images/ajax_loader_login.gif' alet='' />",
          tooltip : "Click to edit...",
          event : "mouseover",
          style : "inherit",
          //id   : 'user_name',
          name : 'user_name'
        });
        $("#image-info > div.user_location").editable("update_user.php", {
          indicator : "<img src='images/ajax_loader_login.gif' alet='' />",
          tooltip : "Click to edit...",
          event : "mouseover",
          style : "inherit",
          //id   : 'user_location',
          name : 'user_location'
        });
        
        $('.add_location').click(
          function()
          {
            document.location.href = 'add_location.php';
          }
        );
        
        $('.add_location_btn').click(
          function()
          {
            document.location.href = 'add_location.php';
          }
        );
        
        
        
        $('.my_profile_btn').click(
          function()
          {
            document.location.href = 'profile.php';
          }
        );
        
        
        
        //$('a.show_add_location').click(
        	//function()
        if ($('.add_unmapped_location').length != 0)
          {
            /*if ($('body > .add_unmapped_location').length == 0)
            {
              var obbj = $('.add_unmapped_location');
              $('.add_unmapped_location').clone(true).appendTo('body');
              obbj.remove();
            }
            
            $('.add_unmapped_location').css({
                  top:  getPageScroll()[1] + (getPageHeight() / 10),
                  left:  385.5,
              'text-align': 'left'
                }).show().css('left', $(window).width() / 2 - ($('.add_unmapped_location').width() / 2));
            if ($('facebox_overlay').length == 0) 
              $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
            
            $('#facebox_overlay').hide().addClass("facebox_overlayBG")
              .css('opacity', $.facebox.settings.opacity)
              .click(function() { $(document).trigger('close.facebox') })
              .fadeIn(200);
              */
            $('#uploadForm').ajaxForm({
              beforeSubmit: function(a,f,o) {
                /*if ($('#type').val() != '' && $('#title').val() != '' && $('#description').val() != '' &&
                  $('#title').val() != $('#title').attr('title') && $('#description').val() != $('#description').attr('title'))
                {*/
                  o.dataType = 'json';
                  $('#f1_upload_process').show();
                  $('#uploadForm').hide();
                /*}
                else
                {
                  alert('Please fill all fields!');
                  return false;
                }*/
              },
              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)
                        $('#f1_upload_process').hide();
                        return false;
                      }
                    }
                  }
                }
                
                $('#uploadForm').hide();
                $('#uploadForm').after('<span style="font-size: 11px;">Files uploaded successfully</span>');
                
                var video = '';
                var name = escape(document.getElementById("name").value);
                var email = escape(document.getElementById("your_email").value);
                var type = 'graffiti';
                var title = '';
                var description = '';
                var myfile = objToString(photos);
                var lat = 0;
                var lng = 0;
                
                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_separate.php",
                  data:url,
                  dataType: 'json',
                  success: function(data_resp)
                  {
                    $('#f1_upload_process').hide();
                    $('#uploadForm').show();
                    $('#uploadForm').html('<input class="multi" name="file[]" type="file" size="11" />');
                    //$('#type').val('');
                    //$('#title').val('');
                    //$('#description').val('');
                    
                    $('#uploadForm .multi').MultiFile({ 
                        accept:'gif|jpg|jpeg', STRING: { 
                        remove:'Remove', 
                        selected:'Selected: $file', 
                        denied:'Please select $ext!', 
                        duplicate:'You have selected duplicate:\n$file!' 
                      } 
                    });
                    
                    /*var loc_html = '\
                    <div class="locations_container"> \
                        <a href="comment.php?location=' + data_resp.location_id + '" title="' + unescape(title) + '"> \
                          <img id="img-' + data_resp.location_id + '" src="' + basepath + 'thumb/' + photos.pop() + '" alt="' + unescape(title) + '" title="' + unescape(title) + '" /> \
                          <div class="location_options"> \
                            <div class="item"> \
                              <span>Unpublish</span> \
                            </div> \
                          </div> \
                        </a> \
                      </div>';*/
                    if ($("#profile").length != 0)
                    {
                      for (var t = 0; t < data_resp.location_id.length; t++) {
                        var point = new Object();
                        point.description = unescape(description);
                        point.embed = "";
                        point.id = data_resp.location_id[t];
                        point.lat = 0.0;
                        point.lng = 0.0;
                        point.on_wall = 1;
                        
                        var ph = new Object();
                        ph.photo = basepath + 'thumb/r' + data_resp.photos[t];
                        point.photos = [ph];
                        point.published = 0;
                        point.title = '';
                        point.type = 'graffiti';
                        
                        BmapPoints.push(point);
                      }
                      changePageMyLocations(currentPage);
                    }
                    
                    //$('.tagged_photos').before(loc_html);
                    //$('.unmapped_photos').show();
                    //console.log(data_resp);
                    //marker.closeInfoWindow();
                    //$('.add_unmapped_location').hide();
                    $('#uploadForm').next('span').remove();
                      jQuery.facebox('Your photo(s) was added!');
                  }
                });
              }
            });
            
            $('#uploadForm .multi').MultiFile({ 
                accept:'gif|jpg|jpeg', STRING: { 
                remove:'Remove', 
                selected:'Selected: $file', 
                denied:'Please select $ext!', 
                duplicate:'You have selected duplicate:\n$file!' 
              } 
            });
            //return false;
          }
        //);
        
        
        
        //$("a[rel=facebox]").facebox();
      }
    }
    
    if ($('#edit_location').length != 0)
    $('#edit_location .location_info > .form_line > button.sbtn').click(
      function()
      {
        var type = $('#type_loc').val();
        var title = $('#title_loc').val();
        var description = $('#description_loc').val();
        var published = 1;
        if ($('#published_loc').attr('checked'))
        {
          published = 1;
        }
        else
        {
          published = 0;
        }
        
        if (type == '')
        {
          jQuery.facebox('Please select type of location');
          return false;
        }
        
        if (title == '')
        {
          jQuery.facebox('Please enter title of location');
          return false;
        }
        
        title = escape(title);
        description = escape(description);
        
        var url = 'type=' + type + '&title=' + title + '&description=' + description + '&id=' + BmapPoints[0].id + '&published=' + published;
        
        $.ajax({
          type:"POST",
          url:"update_sql.php",
          data:url,
          success: function(data)
          {
            data = jQuery.trim(data);
            if (data != "100")
            {
              jQuery.facebox('Changes saved');
              BmapPoints[0].type = $('#type_loc').val();
              BmapPoints[0].title = unescape(title);
              BmapPoints[0].description = unescape(description);
              map.clearOverlays();
              createMarker(new GLatLng(BmapPoints[0].lat, BmapPoints[0].lng), BmapPoints[0], 0);
            }
            else
            {
              jQuery.facebox('Changes NOT saved');
              $('#type_loc').val(BmapPoints[0].type);
              $('#title_loc').val(BmapPoints[0].title);
              $('#description_loc').val(BmapPoints[0].description);
            }
          },
          error: function()
          {
            jQuery.facebox('Changes NOT saved');
            $('#type_loc').val(BmapPoints[0].type);
            $('#title_loc').val(BmapPoints[0].title);
            $('#description_loc').val(BmapPoints[0].description);
          }
        });
      }
    );
    
    if ($('#edit_location').length != 0)
    $('#edit_location .my_locations > .image_container > .loc_options > .item > .img_opts_delete').livequery('click', function(){
      if (confirm('You are about to delete image!')) {
        var block = $(this).parent().parent().parent();
        
        var img_id = block.find('img').attr('id');
        img_id = img_id.replace('img-', '');
        
        var img_src = block.find('img').attr('src');
        
        var del = [];
        del.push(parseInt(img_id));
        
        var url = 'id=asd987987asd9879asdfsdakjf&op=delete_files&delete_files=' + jQuery.toJSON(del);
        
        $.ajax({
          type: "POST",
          url: "update_sql.php",
          data: url,
          success: function(data)
          {
            data = jQuery.trim(data);
            
            if (data != "100")
            {
              for (var i = 0; i < BmapPoints[0].photos.length; i++)
              {
                if (BmapPoints[0].photos[i].photo == img_src)
                {
                  BmapPoints[0].photos.splice(i, 1);
                  break;
                }
              }
            
              block.toggle("slide",
                {
                  direction: "down"
                }, 2000,
                function(){
                  block.remove();
                }
              );
            }
            else
            {
              jQuery.facebox('Changes NOT saved');
            }
          },
          error: function(){
            jQuery.facebox('Changes NOT saved');
          }
        });
      }
    });
    
    if ($('#edit_location').length != 0)
    $('#edit_location #uploadMoreForm').ajaxForm({
      beforeSubmit: function(a,f,o) {
        if ($('#uploadMoreForm input[type="file"]').length < 2)
        {
          jQuery.facebox('Please select photos you want to add to this location.');
          return false;
        }
        o.dataType = 'json';
        $('#upload_more_process').show();
        $('#uploadMoreForm').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)
                $('#upload_more_process').hide();
                return false;
              }
            }
          }
        }
        
        $('#uploadMoreForm').hide();
        $('#uploadMoreForm').after('<span>Files uploaded successfully</span>');
        
        var myfile = objToString(photos);
        
        var url = "embed=&new_files=" + myfile + '&id=' + BmapPoints[0].id;
        
        $.ajax({
          type:"POST",
          url:"http://www.streetartlocator.com/update_sql.php",
          data:url,
          dataType: 'json',
          success: function(data_resp)
          {
            $('#upload_more_process').hide();
            $('#uploadMoreForm').show();
            $('#uploadMoreForm').html('<input class="multifile" name="file[]" type="file" size="12" /><input style="width:130px;" type="submit" name="submitBtn" class="sbtn" value="Add New Image" />');
            
            $('#uploadMoreForm .multifile').MultiFile({ 
                accept:'gif|jpg|jpeg', STRING: { 
                remove:'Remove', 
                selected:'Selected: $file', 
                denied:'Please select $ext!', 
                duplicate:'You have selected duplicate:\n$file!' 
              } 
            });
            
            BmapPoints[0].photos = BmapPoints[0].photos.concat(data_resp);
            
            for (var i=0; i< data_resp.length; i++)
            {
              var loc_html = '\
              <div class="image_container" style="display:none"> \
                  <div class="image"> \
                    <img id="img-' + data_resp[i].photo_id + '" src="' + data_resp[i].photo + '" alt="" title="" /> \
                  </div> \
                  <div class="loc_options clear-block"> \
                    <div class="item"> \
                      <span class="img_opts_delete">Delete</span> \
                    </div> \
                  </div> \
                </div>';
              
              $('#edit_location .my_locations > .image_container:last').after(loc_html);
            }
            
            $('#edit_location .my_locations > .image_container:hidden').toggle("slide",
              {
                direction: "up"
              }, 2000
            );
            
              jQuery.facebox('Your photo(s) was added<br />Note, that images may not appear while you don\'t reload page.');
            
            $('#uploadMoreForm').next('span').remove();
          }
        });
      }
    });
    
    $('#edit_location .sym_tabs > .sym_tab_photos').click(
      function(){
        $('#edit_location .add_location_image > .form_line').hide();
        $('#edit_location .add_location_image > .sym_tab_photos').show();
        
        $('#edit_location .sym_tabs > .sym_tab').removeClass('sym_tab_active');
        $('#edit_location .sym_tabs > .sym_tab_photos').addClass('sym_tab_active');
      }
    );
    
    $('#edit_location .sym_tabs > .sym_tab_youtube').click(
      function(){
        $('#edit_location .add_location_image > .form_line').hide();
        $('#edit_location .add_location_image > .sym_tab_youtube').show();
        
        $('#edit_location .sym_tabs > .sym_tab').removeClass('sym_tab_active');
        $('#edit_location .sym_tabs > .sym_tab_youtube').addClass('sym_tab_active');
      }
    );
    
    $('#edit_location .sym_tabs > .sym_tab_flickr').click(
      function(){
        $('#edit_location .add_location_image > .form_line').hide();
        $('#edit_location .add_location_image > .sym_tab_flickr').show();
        
        $('#edit_location .sym_tabs > .sym_tab').removeClass('sym_tab_active');
        $('#edit_location .sym_tabs > .sym_tab_flickr').addClass('sym_tab_active');
      }
    );
    
    
    if ($('#edit_location').length != 0)
    $('#edit_location .add_location_image > .form_line > #uploadYouTube').ajaxForm({
      beforeSubmit: function(a,f,o) {
        o.dataType = 'json';
        $('#f1_yt_upload_process').show();
        $('#uploadYouTube').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)
                $('#f1_upload_process').hide();
                return false;
              }
            }
          }
        }
        
        $('#uploadYouTube').hide();
        $('#uploadYouTube').after('<span>Files uploaded successfully</span>');
        
        var myfile = objToString(photos);
        var embed = escape($('#uploadYouTube > input[name="video"]').val());
        
        var del_ph = [];
        for (var j=0; j<BmapPoints[0].photos.length; j++)
        {
          del_ph.push(BmapPoints[0].photos[j].photo_id);
        }
        
        var del = jQuery.toJSON(del_ph);
        
        var url = "embed=" + embed + "&new_files=" + myfile + '&id=' + BmapPoints[0].id + '&delete_files=' + del;
        
        
        $.ajax({
          type:"POST",
          url:"http://www.streetartlocator.com/update_sql.php",
          data:url,
          dataType: 'json',
          success: function(data_resp)
          {
            BmapPoints[0].photos = [];
            $('#f1_yt_upload_process').hide();
            $('#uploadYouTube').show();
            $('#uploadYouTube').html('<input name="video" style="margin-bottom:10px;" type="text" size="52" /><input style="width:130px;" type="submit" name="submitBtn" class="sbtn" value="Add New Image" />');
                        
            BmapPoints[0].photos = BmapPoints[0].photos.concat(data_resp);
            
            $('#edit_location .my_locations > .image_container').remove();
            
            var loc_html = '\
            <div class="image_container"> \
                <div class="image"> \
                  <img id="img-' + data_resp[0].photo_id + '" src="' + data_resp[0].photo + '" alt="" title="" /> \
                </div> \
                <div class="loc_options clear-block"> \
                  <div class="item"> \
                    <span class="img_opts_delete">Delete</span> \
                  </div> \
                </div> \
              </div>';
            
            $('#edit_location .my_locations').prepend(loc_html);
            
            $('#uploadYouTube > input[name="video"]').val('');
            
              jQuery.facebox('Your photo(s) was added<br />Note, that images may not appear while you don\'t reload page.');
            
            $('#uploadYouTube').next('span').remove();
          }
        });
      }
    });
    
    if ($('#edit_location #uploadMoreForm').length != 0)
    {
      $('#uploadMoreForm > .multifile').MultiFile({ 
          accept:'gif|jpg|jpeg', STRING: { 
          remove:'Remove', 
          selected:'Selected: $file', 
          denied:'Please select $ext!', 
          duplicate:'You have selected duplicate:\n$file!' 
        } 
      });
    }
    
    if ($(".vertical_return_home").length != 0)
    {
      //ie hack
      html = "<div class=\"vertical_return_home\">" + $(".vertical_return_home").html() + "</div>";
      obj = $(".vertical_return_home");
      obj.before(html);
      obj.remove();
      $(".vertical_return_home").css('left', '-40px');
      if ($('#edit_location').length != 0)
        $(".vertical_return_home").css('top', '90px');
      $(".vertical_return_home").click(
        function ()
        {
          document.location.href = 'index.php';
        }
      );
    }
    
    if ($("#profile > .profile_locations > div > .locations_container > a > .location_options > .item > span").length != 0)
    $('#profile > .profile_locations > div > .locations_container > a > .location_options > .item > span').livequery('click',
    
      function (e)
      {
        var obj = $(this);
        var img = obj.parent().parent().parent().find('img');
        var img_id = img.attr('id');
        img_id = img_id.replace('img-','');
        
        if ($(this).html() == 'Unpublish')
        {
          //console.log("published=0&id="+img_id);
          $.ajax({
            type:"POST",
            url:"update_sql.php",
            data: "published=0&id="+img_id,
            success: function(data)
            {
              img.toggleClass('unpublished');
              obj.html('Publish');
              //console.log(data);
            }
          });
        }
        
        if ($(this).html() == 'Publish')
        {
          //console.log("published=1&id="+img_id);
          $.ajax({
            type:"POST",
            url:"update_sql.php",
            data: "published=1&id="+img_id,
            success: function(data)
            {
              img.toggleClass('unpublished');
              obj.html('Unpublish');
              //console.log(data);
              return false;
            }
          });
        }
        
        if ($(this).html() == 'Untag It')
        {
          if (confirm('You are about to delete tag of location'))
          {
            $.ajax({
              type: "POST",
              url: "tag_photo.php",
              data: 'delete=true&location_id=' + img_id,
              success: function(data){
                data = jQuery.trim(data);
                if (data != "") {
                  jQuery.facebox(data);
                  $('#img-' + img_id).parent().parent().remove();
                }
                return false;
              }
            });
          }
        }
        return false;
      }
    );
    
    if ($(".location_container > .loc_options > .item > span.publish_opts").length != 0)
    $('.location_container > .loc_options > .item > span.publish_opts').livequery('click',
    
      function(e){
        var obj = $(this);
        var img = obj.parent().parent().parent().find('img');
        var img_id = img.attr('id');
        img_id = img_id.replace('img-', '');
        
        if ($(this).html() == 'Hide') {
          $.ajax({
            type: "POST",
            url: "update_sql.php",
            data: "published=0&id=" + img_id,
            success: function(data){
              img.toggleClass('unpublished');
              obj.html('Show');
              obj.removeClass('show');
              obj.removeClass('hide');
              obj.addClass('show');
              img_id = parseInt(img_id);
              for (var i = 0; i< BmapPoints.length; i++)
              {
                if (BmapPoints[i].id == img_id)
                {
                  BmapPoints[i].published = 0;
                  break;
                }
              }
            }
          });
        }
        
        if ($(this).html() == 'Show') {
          $.ajax({
            type: "POST",
            url: "update_sql.php",
            data: "published=1&id=" + img_id,
            success: function(data){
              img.toggleClass('unpublished');
              obj.html('Hide');
              obj.removeClass('show');
              obj.removeClass('hide');
              obj.addClass('hide');
              for (var i = 0; i< BmapPoints.length; i++)
              {
                if (BmapPoints[i].id == img_id)
                {
                  BmapPoints[i].published = 1;
                  break;
                }
              }
              return false;
            }
          });
        }
        
        return false;
      }
      );
      
    if ($(".location_container > .loc_options > .item > span.untag").length != 0)
    $('.location_container > .loc_options > .item > span.untag').livequery('click',
      
      function(e){
        var obj = $(this);
        var img = obj.parent().parent().parent().find('img');
        var img_id = img.attr('id');
        img_id = img_id.replace('img-', '');
        
        if ($(this).html() == 'Remove')
        {
          if (confirm('You are about to delete tag of location'))
          {
            $.ajax({
              type: "POST",
              url: "tag_photo.php",
              data: 'delete=true&location_id=' + img_id,
              success: function(data){
                data = jQuery.trim(data);
                if (data != "") {
                  jQuery.facebox(data);
                  $('#img-' + img_id).parent().parent().remove();
                }
                return false;
              }
            });
          }
        }
        return false;
      }
    );
    
    //if ($(".location_container > .loc_options > .item > span.map_it").length != 0)
    $('.location_container > .loc_options > .item > span.map_it').livequery('click',
      
      function(e){
        var obj = $(this);
        var img = obj.parent().parent().parent().find('img');
        var img_id = img.attr('id');
        img_id = parseInt(img_id.replace('img-', ''));
        
        for (var i = 0; i < BmapPoints.length; i++) {
          if (BmapPoints[i].id == img_id) {
            createMarker(map.getCenter(), BmapPoints[i], i);
            currentIndex = i;
	    marker = new google.maps.Marker({position: map.getCenter(), map: map});
            //savePosInDB(new GMarker(map.getCenter()), BmapPoints[i].id + '_-1');
            savePosInDB(marker, BmapPoints[i].id + '_-1');
            obj.parent().remove();
            break;
          }
        }
        
        return false;
      }
    );
    
    $('a[rel="tag_it"]').click(
      function()
      {
        addTag($('#loc_id').val());
        return false;
      }
    );
    
    $('a[rel="send_to_frnd"]').click(
      function()
      {
        sendToFriend($(this).next().attr('href'));
        return false;
      }
    );
    
    $('a[rel="on_wall"]').click(
      function()
      {
        var loc = $('#loc_id').val();
        var on_wall = $(this).attr('href');
        on_wall = on_wall.replace('#', '');
        var obj = $(this);
        $.ajax({
          type:"POST",
          url:"on_the_wall.php",
          data:'location_id=' + loc + '&on_wall=' + on_wall,
          success: function(data)
          {
            if (data != "")
            {
              //console.log(data);
            }else{
              if (parseInt(on_wall) == 1)
              {
                $('.location_street_status > img').attr('src', 'images/icon_still_on_street.png');
              }else{
                $('.location_street_status > img').attr('src', 'images/icon_no_longer_street.png');
              }
            }
          }
        });
        return false;
      }
    );
    
    $('.add_route_btn').click(function(){
      var data = [];
      for (var t=0; t<waypoints.length; t++)
      {
        if (typeof(waypoints[t].title) == 'undefined' || waypoints[t].title == 'undefined')
        {
          waypoints[t].title = '';
        }
        data.push({'lat': waypoints[t].getPoint().lat(), 'lng': waypoints[t].getPoint().lng(), 'description': waypoints[t].title});
      }
      var route = {};
      route.name = $('#route_form #route_title').val();
      route.description = $('#route_form #route_description').val();
      route.lat = map.getCenter().lat();
      route.lng = map.getCenter().lng();
      route.zoom = map.getZoom();
      
      var uri = 'data=' + $.toJSON(data) + '&route=' + $.toJSON(route) + '&a=add_path';
      $.ajax({
        type:"POST",
        url:"controller.php",
        data:uri,
        dataType:'json',
        success: function(data_resp)
        {
          if (data_resp.status)
          {
            jQuery.facebox(data_resp.message);
          }else{
            jQuery.facebox(data_resp.message);
          }
        },
        error: function()
        {
          jQuery.facebox('Sorry, service is busy now. Please try later');
        }
      });
      return false;
    });
    
    $('.edit_route_btn').click(function(){
      var data = [];
      for (var t=0; t<waypoints.length; t++)
      {
        if (typeof(waypoints[t].title) == 'undefined' || waypoints[t].title == 'undefined')
        {
          waypoints[t].title = '';
        }
        data.push({'lat': waypoints[t].getPoint().lat(), 'lng': waypoints[t].getPoint().lng(), 'description': waypoints[t].title});
      }
      var route = {};
      route.id = $('#rid').val();
      route.name = $('#route_form #route_title').val();
      route.description = $('#route_form #route_description').val();
      route.lat = map.getCenter().lat();
      route.lng = map.getCenter().lng();
      route.zoom = map.getZoom();
      
      var uri = 'data=' + $.toJSON(data) + '&route=' + $.toJSON(route) + '&a=edit_path';
      $.ajax({
        type:"POST",
        url:"controller.php",
        data:uri,
        dataType:'json',
        success: function(data_resp)
        {
          if (data_resp.status)
          {
            jQuery.facebox(data_resp.message);
          }else{
            jQuery.facebox(data_resp.message);
          }
        },
        error: function()
        {
          jQuery.facebox('Sorry, service is busy now. Please try later');
        }
      });
      return false;
    });
    
    $('.show_direct').click(function(){
      var obj = $(this);
      var id = $(this).attr('id');
      id = id.replace('route-', '');
      
      $.ajax({
        type:"POST",
        url:"controller.php",
        data:'a=show_path&id=' + id,
        dataType:'json',
        success: function(data_resp)
        {
          if (data_resp.status)
          {
            stored_waypoints = [];
            stored_waypoints = stored_waypoints.concat(data_resp.route.points);
            
            map.setCenter(new GLatLng(data_resp.route.lat, data_resp.route.lng), data_resp.route.zoom);
            createRoute__();
          }
        },
        error: function()
        {
          jQuery.facebox('Sorry, service is busy now. Please try later');
        }
      });
      return false;
    });
    
    if ($('html').hasClass('ie6'))
    {
      $(document).pngFix();
    }
    
    $("a[rel=popup]").click(
      function()
      {
        var uri = $(this).attr('href');
        window.open(uri, 'StreetArtLocator V2', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=800');
        return false;
      }
    );
    
    jQuery.each(jQuery.browser, function(i, val) {
        if(i=="msie" && val && jQuery.browser.version.substr(0,1)=="6")
      {
        $('#add_our > ul').css('margin-left', '25px');
        $('#add_our > ul > li').css('list-style-position', 'outside');
           alert("To get the best out of our site we recommend you upgrade your browser");
      }
    }); 
  }
);

changeTypeMarkers = function(type)
{
  if (g_type != '')
  {
    $('span.g_' + g_type).prev().show();
    $('span.g_' + g_type).show();
    $('span.g_' + g_type).next().hide();
  }
  g_type = type;
  $.ajax({
    type:"POST",
    url:"scripts/get_type_markers.php",
    data:'type=' + type,
    dataType: 'json',
    success: function(data)
    {
      $('#black-bg span.key-type_long').show();
      $('#black-bg img').show();
      $('#black-bg span.show_none').hide();
      if (data.length > 0)
      {
        BmapPoints = [];
        BmapPoints = BmapPoints.concat(data);
        mgr.clearMarkers();
        mgr.addMarkers(getStreetArtMarkers(1), 1);
        mgr.addMarkers(getStreetArtMarkers(2), 2);
        mgr.addMarkers(getStreetArtMarkers(3), 3);
        mgr.addMarkers(getStreetArtMarkers(4), 4);
        mgr.refresh();
        $('span.g_' + type).prev().hide();
        $('span.g_' + type).hide();
        $('span.g_' + type).next().show();
      }
    }
  });
};

sendToFriend = function(href)
{
  $.ajax({
    type:"POST",
    url:href,
    success: function(data)
    {
      data = jQuery.trim(data);
      if (data != "")
      {
        jQuery.facebox(data);
      }
    }
  });
};

addTag = function(loc)
{
  $.ajax({
    type:"POST",
    url:"tag_photo.php",
    data:'location_id=' + loc,
    success: function(data)
    {
      data = jQuery.trim(data);
      if (data != "")
      {
        jQuery.facebox(data);
      }
    }
  });
};

removeTag = function(loc)
{
  $.ajax({
    type:"POST",
    url:"tag_photo.php",
    data:'delete=true&location_id=' + loc,
    success: function(data)
    {
      data = jQuery.trim(data);
      if (data != "")
      {
        jQuery.facebox(data);
      }
    }
  });
};

chimage = function (id)
{
  /*$("#img_" + id).parent().parent().find('div:gt(0)').toggle("slide", 
    {
      direction: "right"
    }, 2000);*/
  $("#img_" + id).parent().parent().siblings().fadeOut('slow', function(){$("#img_" + id).parent().parent().css('width', '100%');});
  //$("#img_" + id).parent().css('width', '100%');
  $("#img_"+id).hide();
  $('.location_options').css('display', 'none');
  $("#img_"+id).parent().next().find("#f1_upload_form_"+id).show();
};

saveimage = function (id, image_id)
{
  if ($("#title_"+image_id).val() == "")
  {
    alert("Please enter the title ");
    return false;
  }
  $("#f1_upload_form_"+id).hide();
  $("#f1_upload_process_"+id).show();
  $("form[name=aForm" + id + "]").submit();
  return true;
};

savedata = function (id, index)
{
  var type = $("#type_"+id).val();
  var title = escape($("#title_"+id).val());
  var description = escape($("#description_"+id).val());
  
  var url = "type=" + type + "&title=" + title + "&description=" + description + "&id=" + id; // photo;
  
  $.ajax({
    type:"POST",
    url:"update_sql.php",
    data:url,
    success: function(data)
    {
      data = jQuery.trim(data);
      if (data != "100")
      {
        BmapPoints[index].type = $("#type_"+id).val();
        BmapPoints[index].title = $("#title_"+id).val();
        BmapPoints[index].description = $("#description_"+id).val();
        currentMarker.closeInfoWindow();
        map.removeOverlay(currentMarker);
        createMarker(new GLatLng(BmapPoints[index].lat, BmapPoints[index].lng), BmapPoints[index], index);
        jQuery.facebox('Changes saved');
      }
      else
      {
        jQuery.facebox('Please log in to change location');
      }
    }
  });
};

cancel_change_image = function(idz)
{
  $("#img_" + idz).parent().parent().css('width', '');
  //$("#img_" + idz).parent().parent().find('div:gt(0)').fadeIn('slow');
  $("#img_" + idz).parent().parent().siblings().fadeIn('slow');
  $('.location_options').css('display', '');
  /*toggle("slide", 
    {
      direction: "right"
    }, 2000);*/
  $("#f1_upload_form_"+idz).hide();
  $("#img_"+idz).show();
  return false;
};

/*
function mycarousel_itemLoadCallback(carousel, state)
{
  // Check if the requested items already exist
  if (carousel.has(carousel.first, carousel.last)) {
    return;
  }

  jQuery.get(
    'dynamic_image.php',
    {
      first: carousel.first,
      last: carousel.last
    },
    function(xml) {
      mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, xml);
    },
    'xml'
  );
};

function mycarousel_itemAddCallback(carousel, first, last, xml)
{
  // Set the size of the carousel
  carousel.size(parseInt(jQuery('total', xml).text()));

  jQuery('image', xml).each(function(i) {
    carousel.add(first + i, mycarousel_getItemHTML(jQuery(this).text()));
  });
};

function mycarousel_getItemHTML(url)
{
  var array;
  array = url.split(';;;');
  return '<a href="comment.php?location=' + array[0] + '"><img src="' + array[1] + '" width="75" height="75" alt="Latest street art" /></a>';
} */

saveavatar = function ()
{
  $("#upload_form").hide();
  $("#upload_process").show();
  $("form[name=aForm]").submit();
  return true;
};

savepassword = function ()
{
  $("#facebox #change_password_box").css('position' , 'relative');
  var loader = jQuery('<div id="loader" style="visibility: inherit;"><img src="images/loader.gif" alt="Loading..." style="float:left" /></div>')
  .css({position: "absolute", top: ($('#change_password_box').height()/2 - 10) + "px", left: ($('#change_password_box').width()/2 - 30) + "px", 'z-index':"300"})
  .hide()
  .appendTo("#facebox #change_password_box");
  newpass = $("#facebox #change_password_box > div > input[name=new_password]").val();
  if (newpass != $("#facebox #change_password_box > div > input[name=compare_password]").val())
  {
    alert ("New Password and Repeat new password entries do not match");
    return false;
  }
  if (newpass == '' || $("#facebox #change_password_box > div > input[name=compare_password]").val() == '')
  {
    alert ("Please enter new password and it's confirmation");
    return false;
  }
  loader.show();
  $.ajax({
    type:"POST",
    url:"update_user.php",
    data:"user_password=" + escape(newpass) + "&oldpass=" + escape($("#facebox #change_password_box > div > input[name=password]").val()),
    success: function(data)
    {
      data = jQuery.trim(data);
      if (data != "100" && data != "200")
      {
        //$("#facebox a.close").click();
        jQuery.facebox('New password has been saved successfully!');
      }
      else
      if (data == "200")
      {
        jQuery.facebox('Please enter correct old password');
      }
      else
      {
        //$("#facebox a.close").click();
        jQuery.facebox('Please log in to change password');
      }
      loader.remove();
    }
  });
  return true;
};

send_to_friend = function ()
{
  $("#facebox .send_box .response").html('');
  if ($("#facebox .send_box input[name='emails']").val() == '' ||
    $("#facebox .send_box input[name='emails']").val() == 'enter email or emails separated by comma')
  {
    $("#facebox .send_box .response").html('<span style="color:red">Please enter at least one email</span>');
    return false;
  }
  var width = $("#facebox .send_box form").width();
  var height = $("#facebox .send_box form").height();
  $("#facebox .send_box form").hide();
  $("#facebox .send_box").css({'background': 'url(images/loader.gif) no-repeat center center', 'width': width + 'px', 'height': height + 'px'});
  var url = 'emails=' + escape($("#facebox .send_box input[name='emails']").val());
  url += '&message=' + escape($("#facebox .send_box textarea[name='text']").val());
  if ($("#facebox .send_box input[name='location_id']").length != 0)
  {
    url += '&loc_id=' + escape($("#facebox .send_box input[name='location_id']").val());
  }
  $.ajax({
    type:"POST",
    url:"send_to_friend.php",
    data:url,
    success: function(data)
    {
      data = jQuery.trim(data);
      if (data != "100")
      {
        //$("#facebox a.close").click();
        jQuery.facebox('Your email was sent');
      }
      $("#facebox .send_box").css({'background': ''});
    }
  });
  return false;
};

changeImage = function() {
  if (point_photos && point_photos.length > 1)
  {
    idx_img++;
    if (idx_img >= point_photos.length)
    {
      idx_img = 0;
    }
    $('#image-container > a > .comment-image').animate( { opacity: "0.4" }, { queue:false, duration:2000 } )
    .animate( { width: point_photos[idx_img].width + "px", height: point_photos[idx_img].height + "px" }, { queue:false, duration:1500 } )
    .parent().parent().animate( { width: point_photos[idx_img].width + "px", height: point_photos[idx_img].height + "px" }, { duration:1500 } )
    .find('img').attr('src', point_photos[idx_img].photo)
    .animate( { opacity: "1" }, {  duration:2000 } );
    //$('#image-container > .comment-image').attr('src', point_photos[idx_img].photo);
    setTimeout(changeImage, 6000);
  }else{
    if ($('#image-container > object').length != 0)
    {
      $('#image-container > object').width($('#image-container').width() + 'px');
      $('#image-container > object').height($('#image-container').height() + 'px');
      $('#image-container > object > embed').width($('#image-container').width() + 'px');
      $('#image-container > object > embed').height($('#image-container').height() + 'px');
    }
    $('#image-container > a > .comment-image').attr('src', point_photos[0].photo);
  }
  var offset = 0;
  offset += parseInt($('#image-info').height());
  offset += parseInt($('#map-container').height());
  offset += parseInt($('#map-container').css('margin-top'));
  offset += parseInt($('#map-container').next().height());
  offset += parseInt($('#map-container').next().css('margin-top'));
  offset += parseInt($('#map-container').next().next().height());
  offset += parseInt($('#map-container').next().next().css('margin-top'));
  offset += parseInt($('#map-container').next().next().next().height());
  offset += parseInt($('#map-container').next().next().next().css('margin-top'));
  var img_height = parseInt($('#image-container').height());
  
  $('#image-container').css('margin-bottom', '0px');
  if (img_height < offset)
  {
    $('#image-container').css('margin-bottom', (offset - img_height) + 'px');
  }
  
  $('#image-container').css('background', '');
};

changeImageGMap = function() {
  if (tmman)
  {
    clearTimeout(tmman);
  }
  if ($('.map_bubble > .img_section > a').length > 1)
  {
    idx_img++;
    if (idx_img >= $('.map_bubble > .img_section > a').length)
    {
      idx_img = 0;
    }
    
    $('.map_bubble > .img_section > a').each(
      function()
      {
        $(this).hide();
      }
    );
    
    $('.map_bubble > .img_section > a:eq(' + idx_img + ')').show();
    tmman = setTimeout(changeImageGMap, 6000);
  }
};

regFaceboxProc = function()
{
  $("#facebox .err_ms").remove();
  
  if ($("#facebox #reg_email").valid_email() && $("#facebox #reg_email_2").valid_email())
  {
    if ($("#facebox .reg_inline > .input_line > input[name='reg_email_2']").val() != $("#facebox .reg_inline > .input_line > input[name='reg_email']").val())
    {
      error = jQuery('<div class="err_ms">Please check you have repeated same email address</div>')
      .css({'color': 'red', 'text-align': 'center'});
      $("#facebox .button").before(error);
      return false;
    }
    var button_text = $("#facebox .button > button").text();
    $("#facebox .button > button").html('');
    $("#facebox .button > button").css('background', '#000 url(images/ajax_loader_login.gif) center center no-repeat');
    $("#facebox .button > button").attr('disabled', 'disabled');
    var url = 'email=' + escape($("#facebox .reg_inline > .input_line > input[name='reg_email']").val());
    url += '&name=' + escape($("#facebox .reg_inline > .input_line > input[name='reg_name']").val());
    url += '&email_r=' + escape($("#facebox .reg_inline > .input_line > input[name='reg_email_2']").val());
    $.ajax({
      type: "POST",
      url: "register.php",
      data: url,
      cache: false,
      dataType: 'json',
      success: function(data)
      {
        if (data.error)
        {
          error = jQuery('<div class="err_ms">' + data.message + '</div>')
          .css({'color': 'red', 'text-align': 'center'});
          $("#facebox .button").before(error);
        }
        else
        {
          jQuery.facebox('You will receive email soon. \
          <img height="1" width="1" border="0" src="http://www.googleadservices.com/pagead/conversion/1062161569/?label=d6Q6CP2dbxChmb36Aw&amp;script=0"/>');
        }
        $("#facebox .button > button").attr('style', '');
        $("#facebox .button > button").html(button_text);
        $("#facebox .button > button").attr('disabled', '');
      }
    });
    //alert( $("#facebox .reg_inline > .input_line > input[name='reg_name']").val() + "  " + $("#facebox .reg_inline > .input_line > input[name='reg_email']").val() );
  }
  else
  {
    error = jQuery('<div class="err_ms">Please enter valid email adress</div>')
    .css({'color': 'red', 'text-align': 'center'});
    $("#facebox .button").before(error);
  }
  return false;
};

changePageMyLocations = function(arg)
{
  $(".pagination").pagination(BmapPoints.length, {
    items_per_page:8,
    current_page: arg,
    callback:function(argv)
    {
      currentPage = argv;
      changePageMyLocations(argv);
      return false;
    }
  });
            
  var page_photos = [];
  var del = 1;
  if (arg < 1)
  {
    del = 0;
  }
  page_photos = page_photos.concat(BmapPoints);
  page_photos = page_photos.slice( (arg * 8) , (arg * 8) + 8 );
  
  if (user_editable) {
    
  }  
    
  $('.my_locations > .location_container').remove();
  for (var i=0;i < page_photos.length;i++)
  {
    if (user_editable)
    if (page_photos[i].lat != 0 && page_photos[i].lng != 0)
    {
      createMarker(new google.maps.LatLng(page_photos[i].lat, page_photos[i].lng), page_photos[i], i);
    }
      var htm = ' \
      <div class="location_container"> \
        <div class="image"> \
            <a href="comment.php?location=' + page_photos[i].id + '" title="' + page_photos[i].title + '"> \
              <img id="img-' + page_photos[i].id + '" src="' + page_photos[i].photos[0].photo + '" alt="' + page_photos[i].title + '" title="' + page_photos[i].title + '" ' + ((page_photos[i].published)?'':'class="unpublished"') + ' /> \
            </a> \
          </div>';
        if (user_editable)
        {
          htm += '\
        <div class="loc_options clear-block"> \
          <div class="item"> \
            <span class="publish_opts ' + ((page_photos[i].published) ? 'hide' : 'show') + '">' + ((page_photos[i].published) ? 'Hide' : 'Show') + '</span> \
          </div> \
          <div class="item"> \
            <span class="edit"><a style="display:block;" href="edit_location.php?location_id=' + page_photos[i].id +'">Edit</a></span> \
          </div>';
          if (page_photos[i].lat == 0 && page_photos[i].lng == 0) {
            htm += '<div class="item"> \
            <span class="map_it">Map</span> \
          </div>';
          }
          htm += '</div>';
        }
        htm += '\
      </div>';
      
      if ($('.my_locations > .location_container').length == 0)
      {
        $('.my_locations').prepend(htm);
      }
      else
      {
        $('.my_locations > .location_container:last').after(htm);
      }
  }
};

/*searchLocation = function(address)
{
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          jQuery.facebox(address + " not found");
        } else {
          map.setCenter(point, 13);
        }
      }
    );
  }
  return false;
};*/

searchLocation = function(address)
{
	//var address = document.getElementById("search_str").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var listener = google.maps.event.addListener(map, "idle", function() { 
        	  if (map.getZoom() < 11) map.setZoom(12); 
        	  google.maps.event.removeListener(listener); 
        	});
        /*var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });*/
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    })
};

searchLocationText = function(text)
{
  var obj = {};
  obj.search = text;
  $.ajax({
    type:"POST",
    url:"controller.php",
    data:'a=search_text&search=' + $.toJSON(obj),
    dataType:'json',
    success: function(data_resp)
    {
      if (data_resp.status && data_resp.results.length > 0)
      {
    	  var myOptions = {
  			    zoom: 2,
  			    center: new google.maps.LatLng(18.28125, 7.54681317351514),
  			    navigationControl: true,
  			    mapTypeControl:true,
  			    scaleControl: true,
  			    navigationControlOptions: {
  			        style: google.maps.NavigationControlStyle.SMALL
  			      },
  			    mapTypeId: google.maps.MapTypeId.ROADMAP
  			  }
    	  map.enableKeyDragZoom({
	            visualEnabled: true,
	            visualPosition: google.maps.ControlPosition.LEFT_TOP,
	            visualPositionOffset: new google.maps.Size(12, 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"
	            }
	         });
			geocoder = new google.maps.Geocoder();
    	  
    	map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
    	BmapPoints = [];
        BmapPoints = BmapPoints.concat(data_resp.results);

		var mcOptions = {gridSize: 50, maxZoom: 15};
	    var markerCluster = new MarkerClusterer(map, getStreetArtMarkers(4), mcOptions);   
      }
    },
    error: function()
    {
      jQuery.facebox('Sorry, service is busy now. Please try later');
    }
  });
};

searchInit = function(el)
{
  var search_str = $(el).find('input[name="search_string"]').val();
  
  if (search_str == $(el).find('input[name="search_string"]').attr('title'))
  {
    jQuery.facebox('Please select type of search');
    return false;
  }
  
  if ($(el).find(':checked').val() == 'location')
  {
    searchLocation(search_str);
  }
  else
  if ($(el).find(':checked').val() == 'description')
  {
    searchLocationText(search_str);
  }
  else
  {
    jQuery.facebox('Please select type of search');
  }
  return false;
};

clearSearch = function(el)
{
	  var myOptions = {
			    zoom: 2,
			    center: new google.maps.LatLng(18.28125, 7.54681317351514),
			    navigationControl: true,
			    mapTypeControl:true,
			    scaleControl: true,
			    navigationControlOptions: {
			        style: google.maps.NavigationControlStyle.SMALL
			      },
			    mapTypeId: google.maps.MapTypeId.ROADMAP
			  }
  	  map.enableKeyDragZoom({
	            visualEnabled: true,
	            visualPosition: google.maps.ControlPosition.LEFT_TOP,
	            visualPositionOffset: new google.maps.Size(12, 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"
	            }
	         });
			geocoder = new google.maps.Geocoder();
	  
			map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
			//BmapPoints = [];
			//BmapPoints = BmapPoints.concat(BmapPointsAll);
			var mcOptions = {gridSize: 50, maxZoom: 15};
			var markerCluster = new MarkerClusterer(map, getStreetArtMarkers(4), mcOptions);
  
  $('#black-bg span.key-type_long').show();
  $('#black-bg img').show();
  $('#black-bg span.show_none').hide();
  
  $(el).parent().find('input[name="search_string"]').val('');
};


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

// helper
function elementToString(n, useRefs) {
  var attr = "", nest = "", a = n.attributes;
  for (var i=0; a && i < a.length; i++)
    attr += ' ' + a[i].nodeName + '="' + a[i].nodeValue + '"';
  
  if (n.hasChildNodes == false)
    return "<" + n.nodeName + "\/>";

  for (var i=0; i < n.childNodes.length; i++) {
    var c = n.childNodes.item(i);
    if (c.nodeType == 1) nest += elementToString(c);
    else if (c.nodeType == 2) attr += " " + c.nodeName + "=\"" + c.nodeValue + "\" ";
    else if (c.nodeType == 3) nest += c.nodeValue;
  }
  var s = "<" + n.nodeName + attr + ">" + nest + "<\/" + n.nodeName + ">";
  
  return useRefs ? s.replace(/</g,'&lt;').replace(/>/g,'&gt;') : s;
}

loginFaceboxClick = function(obj) {
    var link = $(obj);
    if ($(link).prev().find("input[name=password]").val() != "password"
      && $(link).prev().find("input[name=password]").val() != "" 
      && $(link).prev().find("input[name=email]").valid_email())
    {
      $('#login-link').css('background', 'url(images/ajax_loader_login.gif) center center no-repeat');
      obj = $(link);
      var rem = '';
      if ($('#loginscreen input[name="remember_me"]').length != 0)
      {
        if ($('#loginscreen input[name="remember_me"]').attr('checked'))
        {
          rem = '&remember=';
        }
      }
      $.ajax({
          type:"POST",
          url:"login.php",
          data:'email=' + $(link).prev().find("input[name=email]").val() + rem + '&password=' + $(link).prev().find("input[name=password]").val(),
          success: function(data)
          {
            data = jQuery.trim(data);
            if (data != "100")
            {
              /*obj.prev().find("input[name=password]").hide();
              obj.prev().find("input[name=email]").hide();
              if ($('#loginscreen input[name="remember_me"]').length != 0)
              {
                $('#loginscreen input[name="remember_me"]').hide();
              }*/
              //obj.prev().find("input[name=password]").after('<a href="userpage.php">Edit your locations</a><a href="profile.php">Profile</a>');
              //obj.prev().find("input[name=password]").after('<a href="profile.php">Profile &amp; locations</a><a rel="logout" href="#">Logout</a>');
              obj.parent().addClass('logged');
              obj.removeClass('login');
              obj.addClass('logged');
              obj.attr('style','');
              obj.attr('title', '');
              $.facebox.close();
              window.location.reload(true);
              
              if ($("#markItUp").length != 0)
              {
                $('.comment_form').show();
                $("#submit_comment").removeAttr('disabled');
                $("#submit_comment").parent().next().remove();
                $('.comment_form').show();
                $('.comment > .quote').show();
              }
            }
            else
            {
              alert ("Please enter valid email and/or pasword.\nYou can get a new password from the link at the bottom of the page");
              obj.attr('style','');
            }
            
          }
      });
    }
    else
    {
      alert("Please enter valid email and/or pasword.\nYou can get a new password from the link at the bottom of the page");
      
    }
    return false;
}

   /*FB.init({
       appId  : "181288081888479",
       status : true, // check login status
       cookie : true, // enable cookies to allow the server to access the session
       xfbml  : true  // parse XFBML
     });*/
  $('#loginscreen .login').click(function(){
    jQuery.facebox({div:'#login-facebox'});
  });
    $('#loginscreen .register').click(function(){
    jQuery.facebox({div:'#register_steps'});
  });
});

function showLoading() {
	$("#loading").show();
}

function hideLoading() {
	$("#loading").hide();
}

