var facebook_friends = false;
var view_marker = [];

function validate(groups, cssclass, scrolling)
{
   var first, flag = validators.isValid(groups);
   for (var cid in validators.results)
   {
      if ($type(validators.results[cid]) != 'number') continue;
      if (validators.results[cid]) $(cid).removeClass(cssclass);
      else
      {
         if (!first) first = $(cid);
         $(cid).addClass(cssclass);
      }
   }
   //if (first) first.focus();
   if (first && scrolling) scroll.toElement(first);
   return flag;
}

function popup(text, width)
{
  if (!width)
      width = 365;
  $('popup_window').style.width=width+'px';
  if(messageBox){messageBox.close()};
  $('messageBoxButtons').display('none');
  $('messageBoxContent').innerHTML=text;
  messageBox = new Popup(null, {windowId: 'messageBoxPanel'});
  jQuery('#messageBoxContent').width((width-85));
}

function resizeIFrame(el)
{
   var ifh = el.height;
   var bh = document.body.scrollHeight;
   var dh = document.documentElement.scrollHeight;
   if (bh > 0 && dh > 0) el.height = (bh != ifh) ? bh : dh;
}

function parseSiteURL( strURL )
{
   if ( strURL == '#' ) return strURL;
   var s = strURL.replace(/[^a-zA-Z0-9-\.]/g,'-');
   return s.toLowerCase();
}

function setCookie(name, value, expires, path, domain, secure)
{
  expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(+(new Date) + expires * 1e3)).toGMTString());
  var r = [name + '=' + escape(value)], s, i;
  for(i in s = {expires: expires, path: path, domain: domain})
    s[i] && r.push(i + '=' + s[i]);
  return secure && r.push('secure'), document.cookie = r.join(';'), true;
}

function getCookie(name)
{
  var cookie = " " + document.cookie;
  var search = " " + name + "=";
  var setStr = null;
  var offset = 0;
  var end = 0;
  if (cookie.length > 0)
  {
    offset = cookie.indexOf(search);
    if (offset != -1)
    {
      offset += search.length;
      end = cookie.indexOf(";", offset)
      if (end == -1)
        end = cookie.length;
      setStr = unescape(cookie.substring(offset, end));
    }
  }
  return(setStr);
}

function trim(str, charlist)
{
  charlist = !charlist ? ' \s\xA0' : charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
  var re = new RegExp('^[' + charlist + ']+|[' + charlist + ']+$', 'g');
  return str.replace(re, '');
}

function intval( mixed_var, base )
{
  var tmp;
  if( typeof( mixed_var ) == 'string' )
  {
    tmp = parseInt(mixed_var);
    if(isNaN(tmp))
      return 0;
    else
      return tmp.toString(base || 10);
  }
  else if( typeof( mixed_var ) == 'number' )
    return Math.floor(mixed_var);
  else
    return 0;
}

function selectAll(id, classname, parent)
{
  // Tree
  $$('input').each(function(item){
    if (item.className == (classname + id))
    	item.checked = $(parent + id).checked;
  });
}
function expandData(id, parent, child)
{
  if ($(child + id)) $(child + id).display();
  if ($(parent + id)) $(parent + id).toggleClass('ButtonRound2Right');
}

function expandActivities(id, parent, child)
{
  $(parent + id).toggleClass('ButtonRound2Right');
  $$('ul').each(function(item){
    if ((item.className.substr(7)) == (child + id))
      item.display();
  });
}

function expandActivities2(parent, child)
{
  $(parent).toggleClass('ButtonRound2Right');
  $$('ul').each(function(item){
    if ((item.className.substr(7)) == (child))
      item.display();
  });
}

var isIE = (document.all) ? 1 : 0;
function keyFilter(e, strPattern)
{
  var chr = (isIE) ? e.keyCode : e.which;
  var ch = String.fromCharCode(chr);
  if (chr != 13 && chr != 8 && chr != 0)
  {
    var re = new RegExp(strPattern);
    if (ch.search(re) == -1)
    {
      if(isIE)
        e.returnValue = false;
      else
        e.preventDefault();
    }
  }
}

function getAbsolutePos(el)
{
  var r = {x: el.offsetLeft, y: el.offsetTop};
  if (el.offsetParent)
  {
    var tmp = getAbsolutePos(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
}

function myRound (val, precision)
{
  return parseFloat(val).toFixed(precision);
}

function convCtoF(tC)
{
  return myRound(tC * 9 / 5 + 32, 0);
}

function convFtoC(tF)
{
  return myRound((tF - 32) * 5 / 9, 0);
}

function convINtoMM(vIN)
{
  return myRound(vIN * 25.4, 2);
}

function convMMtoIN(vMM)
{
  return myRound(vMM / 25.4, 2);
}

function changeTemperature(id)
{
  for (i = 1; i <= 12; i++)
  {
    $(id + '_high_' + i).display();
    $(id + '_highf_' + i).display();
    $(id + '_low_' + i).display();
    $(id + '_lowf_' + i).display();
  }
  $(id + '_c').toggleClass('bold');
  $(id + '_f').toggleClass('bold');
}
function changeRain(id)
{
  for (i = 1; i <= 12; i++)
  {
    $(id + '_rain_' + i).display();
    $(id + '_rainm_' + i).display();
  }
  $(id + '_in').toggleClass('bold');
  $(id + '_mm').toggleClass('bold');
}


/********************************
 * Facebook Integration Functions
 *
 ********************************/
function reloadPageWithParam(param){
    var location = new String(window.location);
    /* aded by LcC in order to remove hash mark in the query string*/var poundMark = location.indexOf('#');if (poundMark > 0){location = location.substring(0,poundMark);}
    
    if (location.indexOf('?') != -1) {
        window.location = location + '&' + param;
    } 
    else {
        window.location = location + '?' + param;
    }
    
    
}
function loginFacebook() {
    FB.login(
        function(response){
            if (response.session) {
                reloadPageWithParam('fblogin=1');
            }
        }, {perms:'email,publish_stream'});
}

function fbShareDialog(trip_title)
{
    html = '<div id="facebook-share-block">';
    html+= '<div id="ShareFacebook"><a href="#" onclick="fbShareToFriendsList();return false;">Share to friends</a></div>';
    html+= '<textarea id="fb-share" name="fb-share" style="width:235px;height: 80px;">Check out this adventure of a lifetime: '+trip_title+'</textarea>';
    html+= '<a href="#" onclick="fbSharePost();return false;" style="float:right;"><img src="/i/frontend/facebook-share-button.jpg" /></a>';
    html+= '<div class="Clear"></div>';
    html+= '</div>';
    popup(html);

}

function fbShareToFriendsList()
{
    jQuery('#ShareFacebook a').remove();
    jQuery('#ShareFacebook').append(jQuery('<img src="/i/frontend/ajax-loader.gif" />'));
    if (!facebook_friends) {
        getFacebookFriendsCallback = function (friends){
            facebook_friends = friends;
            jQuery('#ShareFacebook img').remove();
            jQuery('#ShareFacebook').append(jQuery('<select id="ShareFacebook-FriendInput" name="ShareFacebook-FriendInput"></select>'));
            jQuery('#ShareFacebook-FriendInput').append(jQuery('<option value="0"></option>'));
            friends.data.each(function(item, index){
                jQuery('#ShareFacebook-FriendInput').append(jQuery('<option value="'+item.id+'">'+item.name+'</option>'));
            });
            jQuery('#ShareFacebook-FriendInput').fcbkcomplete({
                    height: 2
            });
        }
        ajax.doit('User::getFacebookFriends');
    } else {
        getFacebookFriendsCallback(facebook_friends);
    }
}

jQuery.fn.shareToFacebookFriends = function(options){
    return this.each(function(){
        jQuery(this).children('a').remove()
        jQuery(this).append(jQuery('<img src="/i/frontend/ajax-loader.gif" />'));
        facebook_friend_element = this;
        if (!facebook_friends) {
            getFacebookFriendsCallback = function (friends){
                facebook_friends = friends;
                jQuery(facebook_friend_element).children('img').remove();
                jQuery(facebook_friend_element).append(jQuery('<select class="ShareFacebook-FriendInput" name="ShareFacebook-FriendInput"></select>'));
                jQuery(facebook_friend_element).children('.ShareFacebook-FriendInput').append(jQuery('<option value="0"></option>'));
                friends.data.each(function(item, index){
                    jQuery(facebook_friend_element).children('.ShareFacebook-FriendInput').append(jQuery('<option value="'+item.id+'">'+item.name+'</option>'));
                });
                jQuery(facebook_friend_element).children('.ShareFacebook-FriendInput').fcbkcomplete({
                        height: 3
                });
            }
            ajax.doit('User::getFacebookFriends');
        } else {
            getFacebookFriendsCallback(facebook_friends);
        }
    })
};

function fbSharePost()
{
    if (jQuery('#ShareFacebook-FriendInput').length != 0 && jQuery('#ShareFacebook-FriendInput').val() != 0) {
        res = new String(jQuery('#ShareFacebook-FriendInput').val());
        res.split(',').each(function(item, index){
            if (item != '0'){
                FB.api('/'+item+'/feed', 'post', {message: document.getElementById('fb-share').value});
            }
        });
        messageBox.close();
    } else {
        FB.api('/me/feed', 'post', {message: document.getElementById('fb-share').value}, function(response){
            messageBox.close();
        });
    }
}


function fbInviteFriendsDialog()
{
    html = '<h3>Invite People to Join Avidtrips</h3>';
    html += '<ul id="InviteFacebookList" style="list-style: none;">';
    getFacebookFriendsCallback = function (friends){
        friends.data.each(function(item, index){
            html += '<li><div style="float:left;padding-right: 5px;"><fb:profile-pic uid="'+item.id+'" linked="false" /></div> '+item.name+'<a href="javascript:FB.ui({method: \'apprequests\', to: \''+item.id+'\', message: \'A request especially for one person.\', data: \'tracking information for the user\'});" class="fb-invite">Invite</a><div style="clear:both">&nbsp;</div></li>';
        });
        html += '</ul>';
        popup(html);
        //FB.XFBML.Host.parseDomElement(document.getElementById('InviteFacebookList'));
        FB.XFBML.parse(document.getElementById('InviteFacebookList'));
    }
    ajax.doit('User::getFacebookFriends');
}

function fbDisconnect()
{
    html = '<h3>Are you sure?</h3>';
    html+= 'Are you sure you want to disconnect your<br/>';
    html+= 'Facebook and TripAdvisor accounts?<br/><br/>';
    html+= '<a id="fb-disconnect-button" href="#" style=""float:left;">Disconnect</a> <a href="javascript:messageBox.close();" style="float:right;">Cancel</a>';
    popup(html);
    jQuery('#fb-disconnect-button').click(function(){
        ajax.doit('::fbDisconnect');
    });
}

function fbLikeTrip(response, trip_id)
{
    ajax.call('::fbLike', trip_id);
}

function getRelevantTripsQuery(obj)
{
    if (typeof call_get_relevant != 'undefined') {
        clearTimeout(call_get_relevant);
    }
    call_get_relevant = setTimeout('getRelevantTrips()', 1000);
}

function getRelevantTrips()
{
    var title = jQuery('#post-title').val();
    jQuery('#likeContentID .auto-selected').removeClass('auto-selected').attr('selected','');
    ajax.call('::getRelevantTrips', title);
}

/*************************
 * Save fb user activities
 * Step 2 of Registration Flow
 *
 *************************/
function showActivitiesDialog()
{
    /*
    html = '<h2 style="margin-bottom:15px;">I\'m avid about:</h2>';
    html+= '<table id="activities_list">';
    activities_list = [
        {id:'1', name:'Air Sports'},
        {id:'27', name:'Hiking / Trekking'},
        {id:'44', name:'Winter Sports'},
        {id:'66', name:'Cycling'},
        {id:'28', name:'Riding'},
        {id:'61', name:'Water Sports'},
        {id:'9', name:'Climbing'},
        {id:'50', name:'Photography'},
        {id:'71', name:'Cultural'},
        {id:'15', name:'Culinary'},
        {id:'51', name:'Wildlife Viewing'}];
    for (var i=0; i<activities_list.length; i++) {
        if (i%3 == 0){
            html+= '<tr>';
        }
        html+='<td><input type="checkbox" name="activities" value="' + activities_list[i].id + '" />&nbsp;' + activities_list[i].name + '</td>';
        if ((i+1)%3 == 0) {
            html+= '</tr>';
        }
    }
    html+= '</table>';
    html+= '<div class="spacer">&nbsp;</div>';
    html+= '<div style="text-align:center;"><div class="buttons" style="text-align:center;padding-top:30px;"><a href="javascript:saveActivitiesDialog();" class="button blue border3d no-shadow">Continue</a></div>';
    popup(html, 450);
    */
    displayAvidAboutBox();
}

function saveActivitiesDialog()
{
    var activities = new Array();
    jQuery('#avidabout-box input').each(function(key, item) {
        if (jQuery(this).attr('checked')){
            activities.push(jQuery(this).val());
        }
    });
    ajax.call('::saveActivities', activities);
    avidAboutBox.close();
    addPlacesDialog();
}


/********************
 * Google Map feaures
 * Create Adventure Map
 * Step 3 of Registration Flow
 *
 ********************/

function googleMapCenterByCountry(map, address){
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( {'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        map.fitBounds(results[0].geometry.bounds);
      }
    });
}

function googleMapInit()
{
    var latlng = new google.maps.LatLng(0,0);
    var myOptions = {
      zoom: 1,
      zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE
        },
      panControl: false,
      streetViewControl: false,
      mapTypeControl: false,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    google_map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    //event = new google.maps.MapsEventListener();
    google.maps.event.addListener(google_map, 'drag', function() {
        if (jQuery('#search_place').val() == ''){
            jQuery('#search_place').css('color','#aaa').val('Where was your adventure?').blur();
        }
        // Perform the check and return if OK
        var maxY = 85;
        var minY = -85;
        /*
        if (allowedBounds.contains(google_map.getCenter())) {
            return;
        }        // It`s not OK, so find the nearest allowed point and move there
        */
        var C = google_map.getBounds();
        var x = google_map.getCenter().lng();
        var x2 = C.getNorthEast().lng();
        var x1 = C.getSouthWest().lng();
        var y1 = C.getNorthEast().lat();
        var y2 = C.getSouthWest().lat();
        //var D = new google.maps.LatLngBounds(new google.maps.LatLng(y2,x1), new google.maps.LatLng(y1,x2));
        //console.log(D.getCenter().lat() + ' ' + D.getCenter().lng() + ' : ' + google_map.getCenter().lat() + ' ' + google_map.getCenter().lng());
        var h = y1 - y2;
        if (y2 < minY){
            y2 = minY;
            y1 = y2 + h;
            var B = new google.maps.LatLngBounds(new google.maps.LatLng(y2,x1), new google.maps.LatLng(y1,x2));
            google_map.panTo(B.getCenter());
            //console.log('1 : ' + google_map.getBounds().getNorthEast().lng() + ', ' + google_map.getBounds().getNorthEast().lat() + ' - ' + google_map.getBounds().getSouthWest().lng() + ', ' + google_map.getBounds().getSouthWest().lat());
            //console.log('s : ' + x2 + ', ' + y1 + ' - ' + x1 + ', ' + y2);
            //google_map.panToBounds(new google.maps.LatLngBounds(new google.maps.LatLng(y2,x1), new google.maps.LatLng(y1,x2)));
            //console.log('2 : ' + google_map.getBounds().getNorthEast().lng() + ', ' + google_map.getBounds().getNorthEast().lat() + ' - ' + google_map.getBounds().getSouthWest().lng() + ', ' + google_map.getBounds().getSouthWest().lat());
        }
        if (y1 > maxY) {
            y1 = maxY;
            y2 = y1 - h;
            var B = new google.maps.LatLngBounds(new google.maps.LatLng(y2,x1), new google.maps.LatLng(y1,x2));
            google_map.panTo(B.getCenter());
            //console.log('1 : ' + google_map.getBounds().getNorthEast().lng() + ', ' + google_map.getBounds().getNorthEast().lat() + ' - ' + google_map.getBounds().getSouthWest().lng() + ', ' + google_map.getBounds().getSouthWest().lat());
            //console.log('s : ' + x2 + ', ' + y1 + ' - ' + x1 + ', ' + y2);
            // google_map.setCenter(new google.maps.LatLng((y1-h)/2,x));
            //google_map.panToBounds(new google.maps.LatLngBounds(new google.maps.LatLng(y2,x1), new google.maps.LatLng(y1,x2)));
            //console.log('2 : ' + google_map.getBounds().getNorthEast().lng() + ', ' + google_map.getBounds().getNorthEast().lat() + ' - ' + google_map.getBounds().getSouthWest().lng() + ', ' + google_map.getBounds().getSouthWest().lat());
        }

        /*
        var X = C.lng();
        var Y = C.lat();
        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();
        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        //alert ("Restricting "+Y+" "+X);
        google_map.setCenter(new google.maps.LatLng(Y,X));
        */
    });
    activity_id = 0;
}

function googleSearchPlace(place, map)
{
    if (typeof place == 'undefined') {
        var address = document.getElementById('search_place').value;
    } else {
        var address = place;
    }

    google_geocoder.geocode( {'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (typeof search_marker == 'undefined' || !search_marker){
                if (typeof map != 'undefined') {
                    search_marker = new google.maps.Marker({
                            map: map,
                            position: results[0].geometry.location
                    });
                } else {
                    search_marker = new google.maps.Marker({
                            map: google_map,
                            position: results[0].geometry.location
                    });
                }
            } else {
                search_marker.setPosition(results[0].geometry.location);
            }
            if (typeof map != 'undefined') {
                map.setCenter(results[0].geometry.location);
                map.setZoom(10);
            } else {
                google_map.setCenter(results[0].geometry.location);
                google_map.setZoom(10);
            }
        }
    });
}

function addPlacesDialog()
{
    displayAdventureMapBox();
    googleMapInit();
    var activitiesList = ({
        'id_01':  'Air Sports',
        'id_09':  'Climbing',
        'id_66': 'Cycling',
        'id_23': 'Fishing',
        'id_72': 'Food / Wine',
        'id_27': 'Hiking / Trekking',
        'id_28': 'Horseback Riding',
        'id_50': 'Photography',
        'id_59': 'Sailing',
        'id_38': 'Scuba Diving',
        'id_44': 'Snow Sports',
        'id_60': 'Voluntourism',
        'id_61': 'Water Sports',
        'id_51': 'Wildlife Viewing',
        'id_18': 'World Culture'
    });

    search_map_control = document.getElementById('search_map_control');
    google_map.controls[google.maps.ControlPosition.TOP_LEFT].push(search_map_control);

    getFacebookFriendsCallback = function (friends){
        facebook_friends = friends;
        jQuery('#ShareFacebook img').remove();
        jQuery('#ShareFacebook').append(jQuery('<select id="ShareFacebook-FriendInput" name="ShareFacebook-FriendInput"></select>'));
        jQuery('#ShareFacebook-FriendInput').append(jQuery('<option value="0"></option>'));
        friends.data.each(function(item, index){
            jQuery('#ShareFacebook-FriendInput').append(jQuery('<option value="'+item.id+'">'+item.name+'</option>'));
        });
        jQuery('#ShareFacebook-FriendInput').fcbkcomplete({
                height: 2
        });
    }
    FB.getLoginStatus(function(response) {
        if (response.session) {
            ajax.doit('User::getFacebookFriends');
        } else {
            facebook_friends = {};
        }
    });

    jQuery('#search_place').focusin(function(){
        if (jQuery(this).css('color') == 'rgb(170, 170, 170)' || jQuery(this).css('color') == '#aaa') {
            jQuery(this).val('').css('color','#111111');
        }
    });
    jQuery('#search_place').focusout(function(){
        if (jQuery(this).val() == ''){
            jQuery(this).css('color','#aaa').val('Where was your adventure?');
        }
    });
    google.maps.event.addListener(google_map, 'click', function(){
        if (jQuery('#search_place').val() == ''){
            jQuery('#search_place').css('color','#aaa').val('Where was your adventure?').blur();
        }
    });
    if (!jQuery('#place_activity option').length) {
        jQuery.each(activitiesList, function(key, item){
            jQuery('#place_activity').append(jQuery('<option value="'+key+'">'+item+'</option>'));
        });
    }
    if (!jQuery('.sports-list .item').length) {
        var activitiesHtml = '';
        var listCount = 0;
        jQuery.each(activitiesList, function(key, item){
            if (listCount % 4 == 0) {
                activitiesHtml += '<div style="width:135px;float:left;">';
            }
            var sID = new String(key);
            id = sID.substr(3) * 1;
            activitiesHtml += '<div class="item highlight-sport" id="activity-item-'+id+'" style="cursor:pointer;background-image:url(\'/images/sports/icon-off-'+id+'.png\');width:135px;"><input type="checkbox" class="check chk_9" style="display:none;" value="'+id+'" /><div class="name" style="padding-left:33px;">'+item+'</div></div>';
            if (listCount % 4 == 3) {
                activitiesHtml += '<div class="spacer">&nbsp;</div></div>';
            }
            listCount++;
            //jQuery('.sports-list').append(jQuery('<div class="item" id="activity-item-'+key+'" style="cursor:pointer;background-image:url(\'/images/sports/icon-off-'+key+'.png\');width:135px;"><input type="checkbox" class="check chk_9" style="display:none;" value="'+key+'" /><div class="name" style="padding-left:29px;">'+item+'</div></div>'));
        });
        if (listCount % 4 != 0) {
                activitiesHtml += '<div class="spacer">&nbsp;</div></div>';
        }
        jQuery('.sports-list').append(jQuery(activitiesHtml));
        jQuery('.highlight-sport').hover(function(){
                    var background_image = new String(jQuery(this).css('backgroundImage'));
                    if (background_image == background_image.replace(/-off/, '')) {
                        jQuery(this).css('backgroundImage', "url('/images/sports/icon-off-" + jQuery(this).find('input').val() + ".png')");
                    } else {
                        jQuery(this).css('backgroundImage', background_image.replace(/-off/, ''));
                    }
        });
        jQuery('.sports-list .item').draggable({
            helper : 'clone',
            opacity : 0.5,
            start: function(event, ui){
                activity_id = jQuery(this).children('.check').val();
            },
            stop: function(event, ui){
                mouse_over = google.maps.event.addListener(google_map, 'mouseover', function(event) {
                    if (activity_id){
                        addNewPlace(event.latLng, activity_id);
                        activity_id = 0;
                    }
                    google.maps.event.removeListener(mouse_over);
                });
            }
        });
    }

    jQuery('#adventuremap-box .photo-input').change(function(){
        jQuery(this).parents('.photo-form').submit();
        jQuery('#adventuremap-box .photo-add').hide();
        jQuery('#adventuremap-box .photo-image').show();
    });
    jQuery('#adventuremap-box .photo-image').children('a').click(function(){
        jQuery('#adventuremap-box .photo-image').children('img').attr('src', '');
        jQuery('#adventuremap-box .photo-image').hide();
        jQuery('#adventuremap-box .photo-add').show();
        return false;
    })
    jQuery('#adventuremap-box .photo-form').submit(function(){
        jQuery(this).ajaxSubmit({
            success:function(data){
                jQuery('#adventuremap-box .photo-image').children('img').attr('src', '/images/users_places/'+data);
            }
        });
        return false;
    });

    blockAdventureMap = false;
    google_geocoder = new google.maps.Geocoder();
    pushpin_red = new google.maps.MarkerImage('/images/pushpin_red.png');
    pushpin_yellow = new google.maps.MarkerImage('/images/pushpin_yellow.png');
    fb_places = new Array();
    fb_place_markers = new Array();
    fb_current_place = -1;
    marker_index = -1;
    search_marker = false;
}

function addNewPlace(latlng, activity)
{
    if (fb_current_place != -1) {
        fb_place_markers[fb_current_place].setIcon(fb_place_markers[fb_current_place].notActiveIcon);
        fb_place_markers[fb_current_place].setDraggable(false);
        blockAdventureMap = false;
    }
    if (!latlng) {
        latlng = google_map.getCenter();
    }
    if (!activity) {
        activity = 0;
    }

    var marker = new google.maps.Marker({
        map: google_map,
        draggable: false,
        position: latlng
    });
    marker_index++;
    fb_place_markers[marker_index] = marker;

    var activePushpin = new google.maps.MarkerImage('/images/sports/icon-'+activity+'.png');
    var notActivePushpin = new google.maps.MarkerImage('/images/sports/icon-off-'+activity+'.png');
    fb_place_markers[marker_index].setIcon(activePushpin);
    fb_place_markers[marker_index].index = marker_index;
    fb_place_markers[marker_index].notActiveIcon = notActivePushpin;
    fb_place_markers[marker_index].activeIcon = activePushpin;
    fb_places[marker_index] = {name: '', comment: '', friends: jQuery('<a href="#"  onclick="fbShareToFriendsList();return false;">Add friends</a>'), 'activity': activity, 'photo':''};

    google.maps.event.addListener(fb_place_markers[marker_index], 'click', function(){
        getPlace(this.index);
    });

    google.maps.event.addListener(fb_place_markers[marker_index], 'dragend', function(){
        var marker = this;
        if (marker.index != fb_current_place) {
            return false;
        } else {
            blockAdventureMap = false;
        }
        google_geocoder.geocode({'latLng': this.getPosition()}, function(results, status){
            if (status == google.maps.GeocoderStatus.OK) {
                var place_name = '';
                var city_exist = false;
                var type_priority = {'street_address':0, 'locality':1, 'administrative_area_level_3':2, 'administrative_area_level_2':3, 'administrative_area_level_1':4};
                var priority = 10;
                var address = '';
                jQuery(results).each(function(k, result){
                    if (typeof type_priority[result.types[0]] != "undefined" && type_priority[result.types[0]]<priority) {
                        priority = type_priority[result.types[0]];
                        address = result.address_components;
                    }
                });
                jQuery(address).each(function(key, item){
                    if (item.types[0] == 'country'){
                        place_name += item.long_name + ', ';
                    } else if ((item.types[0] == 'administrative_area_level_3' || item.types[0] == 'locality') && !city_exist) {
                        city_exist = true;
                        place_name += item.long_name + ', ';
                    } else if (item.types[0] == 'administrative_area_level_1'){
                        place_name += item.short_name + ', ';
                    }
                });
                place_name = new String(place_name);
                if (place_name.length) {
                    place_name = place_name.substr(0, place_name.length - 2);
                }
                fb_places[marker_index].name = place_name;
                getPlace(marker.index, true);
            }
        });
    });

    google_geocoder.geocode({'latLng': latlng}, function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            var place_name = '';
            var city_exist = false;
            var type_priority = {'street_address':0, 'locality':1, 'administrative_area_level_3':2, 'administrative_area_level_2':3, 'administrative_area_level_1':4};
            var priority = 10;
            var address = '';
            jQuery(results).each(function(k, result){
                if (typeof type_priority[result.types[0]] != "undefined" && type_priority[result.types[0]]<priority) {
                    priority = type_priority[result.types[0]];
                    address = result.address_components;
                }
            });
            jQuery(address).each(function(key, item){
                if (item.types[0] == 'country'){
                    place_name += item.long_name + ', ';
                } else if ((item.types[0] == 'administrative_area_level_3' || item.types[0] == 'locality') && !city_exist) {
                    city_exist = true;
                    place_name += item.long_name + ', ';
                } else if (item.types[0] == 'administrative_area_level_1'){
                    place_name += item.short_name + ', ';
                }
            });
            place_name = new String(place_name);
            if (place_name.length) {
                place_name = place_name.substr(0, place_name.length - 2);
            }
            fb_places[marker_index].name = place_name;
        }
        getPlace(marker_index);
    });
    jQuery('#place_options').fadeIn();
}

function saveCurrentPlace()
{
    fb_places[fb_current_place].name = jQuery('#place_name').val();
    fb_places[fb_current_place].comment = jQuery('#place_comment').val();
    fb_places[fb_current_place].photo = jQuery('#adventuremap-box .photo-image').children('img').attr('src');
    if (jQuery('#ShareFacebook-FriendInput').length) {
        fb_places[fb_current_place].friends = jQuery('#ShareFacebook').children('#ShareFacebook-FriendInput');
    } else {
        fb_places[fb_current_place].friends = jQuery('#ShareFacebook').children();
    }
    fb_place_markers[fb_current_place].setIcon(fb_place_markers[fb_current_place].notActiveIcon);
    fb_place_markers[fb_current_place].setDraggable(false);
    fb_current_place = -1;
    blockAdventureMap = false;
}

function deleteCurrentPlace()
{
    activity = fb_places[fb_current_place].activity;
    jQuery('#activity-item-'+activity).css('backgroundImage', "url('/images/sports/icon-off-"+activity+".png')");
    fb_places[fb_current_place] = null;
    fb_place_markers[fb_current_place].setMap(null);
    fb_place_markers[fb_current_place] = null;
    if (fb_current_place>0){
        fb_current_place--;
    }
    blockAdventureMap = false;
    jQuery('#place_options').fadeOut();
    fb_current_place = -1;
}

function sendPlaces()
{
    if (fb_place_markers != null && fb_place_markers.length > 0){
        if (fb_current_place != -1) {
            saveCurrentPlace();
        }
        jQuery(fb_places).each(function(key, item) {
           fb_places[key].lng = fb_place_markers[key].getPosition().lng();
           fb_places[key].lat = fb_place_markers[key].getPosition().lat();
           fb_places[key].friends = fb_places[key].friends.val();
        });
    }
    ajax.call('::savePlaces', fb_places);
}

function getPlace(id, flag)
{
    if (fb_current_place != -1 && !flag){
        fb_place_markers[fb_current_place].setIcon(fb_place_markers[fb_current_place].notActiveIcon);
        fb_place_markers[fb_current_place].setDraggable(false);
        blockAdventureMap = false;
        if (fb_current_place == id) {
            jQuery('#place_options').fadeOut();
            fb_current_place = -1;
            return false;
        }
    }
    if (blockAdventureMap){
        return false;
    }
    if (!arguments.length){
        fb_current_place++;
    } else if (id == '-1'){
        fb_current_place--;
    } else {
        fb_current_place = id;
    }
    jQuery('#place_options').show();
    jQuery('#place_name').val(fb_places[fb_current_place].name);
    jQuery('#place_comment').val(fb_places[fb_current_place].comment);
    jQuery('#place_activity').val(fb_places[fb_current_place].activity);
    jQuery('#ShareFacebook').html('');
    jQuery('#ShareFacebook').prepend(fb_places[fb_current_place].friends);

    if (jQuery('#ShareFacebook a').length){
        fbShareToFriendsList();
    } else if (jQuery('#ShareFacebook-FriendInput').length){
        jQuery('#ShareFacebook-FriendInput').fcbkcomplete({
                height: 2
        });
    }
    //var mapWidth = google_map.getBounds().getNorthEast().lng() - google_map.getBounds().getSouthWest().lng();
    //google_map.setCenter(new google.maps.LatLng(fb_place_markers[fb_current_place].getPosition().lat(), mapWidth*0.34));
    google_map.setCenter(fb_place_markers[fb_current_place].getPosition());
    fb_place_markers[fb_current_place].setIcon(fb_place_markers[fb_current_place].activeIcon);
    fb_place_markers[fb_current_place].setDraggable(true);

    if (!fb_places[fb_current_place+1]) {
        jQuery('#place_next').css('display', 'none');
    } else {
        jQuery('#place_next').css('display', 'inline');
    }

    if (!fb_places[fb_current_place-1]) {
        jQuery('#place_previous').css('display', 'none');
    } else {
        jQuery('#place_previous').css('display', 'inline');
    }
    if (jQuery('#place_options').css('display') == 'none') {
        jQuery('#place_options').fadeIn();
    }

    if (fb_places[fb_current_place].photo) {
        jQuery('#adventuremap-box .photo-add').hide();
        jQuery('#adventuremap-box .photo-image').children('img').attr('src', fb_places[fb_current_place].photo);
        jQuery('#adventuremap-box .photo-image').show();
    } else {
        jQuery('#adventuremap-box .photo-image').hide();
        jQuery('#adventuremap-box .photo-image').children('img').attr('src', '');
        jQuery('#adventuremap-box .photo-add').show();
    }

    blockAdventureMap = true;
}

/*******************************
 * Congratulation Window
 * Step 5 of Registration Flow
 *
 *******************************/
function registrationFlowCongratulation()
{
    jQuery('#congratulation-box').css('opacity', '0');
    congratulationBox = new Popup(null, {windowId: 'congratulation-box'});
    jQuery('#congratulation-box').fadeIn();
}

/************************
 * Flickr API functional
 *
 ************************/
function flickrGetImageByTag(tag, counter)
{
    if (counter < 2) {
        jQuery('#slide-prev').css('visibility', 'hidden');
    } else {
        jQuery('#slide-prev').css('visibility', 'visible');
    }
    jQuery('#flickr-image').fadeOut('500');

    jQuery.get('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=c5dc74cef64eebdd264938d98f36bbf0&tags='+tag+'&format=json', function(data){
        data = eval(data.substr(13, data.length-13));
        photo = data.photos.photo[counter];
        if (counter-1 == photo.length){
            alert(photo.length);
            jQuery('#slide-next').css('visibility', 'hidden');
        } else
            jQuery('#slide-next').css('visibility', 'visible');
        jQuery('#flickr-image').attr('src', 'http://farm' + photo['farm'] + '.static.flickr.com/' + photo['server'] + '/' + photo['id'] + '_' + photo['secret'] + '.jpg');
        jQuery('#flickr-image').load(function(){jQuery('#flickr-image').fadeIn('500')});
    });
}
/****************************
 * Login and Signup Dialog
 *
 ***************************/
var signup_required_from_login = false;
function displayLoginBox(required)
{
    if (typeof required != 'undefined' && required) {
        jQuery('#login-box-close').remove();
        signup_required_from_login = true;
    }
    //if(loginBox){loginBox.close()};
    jQuery('#login-box').css('opacity', '0');
    loginBox = new Popup(null, {windowId: 'login-box'});
    jQuery('.novalidmsg').hide();
    jQuery('#login-box').css('top','50px');
    jQuery('#login-box').fadeIn();
}

function displaySignupBox(required)
{
    //if(signupBox){signupBox.close()};
    pageTracker._trackPageview('/reg_start.html');
    if (typeof required != 'undefined' && required) {
        jQuery('#tellus-box-close').remove();
    }
    jQuery('#signup-box').css('opacity', '0');
    signupBox = new Popup(null, {windowId: 'signup-box'});
    jQuery('#signup-box').css('top', '50px');
    jQuery('#signup-box').fadeIn();
}






function displayAdventureMapBox()
{
    jQuery('#adventuremap-box').css('opacity', '0');
    adventureMapBox = new Popup(null, {windowId: 'adventuremap-box'});
    jQuery('#adventuremap-box').fadeIn();
}

function displayAvidAboutBox()
{
    jQuery('#avidabout-box').css('opacity', '0');
    avidAboutBox = new Popup(null, {windowId: 'avidabout-box'});
    jQuery('#avidabout-box').fadeIn();
}

    jQuery('#signup-box input').each(function(el){
        el.addEvent('keypress', function(e){
            ee = (window.event | e);
            if (ee.keyCode == 13)
              return false;
          });
    });
    var currentSel = '';
    var openFl = 0;
    var currentLevel = 0;
    var changeFl = 0;

    function removePad(obj, currentSel)
    {
      var curElement = obj.options[currentSel].innerHTML;
      var tmp = curElement;
      curElement = curElement.replace(/&nbsp;/g, '').trim();
      if(tmp.length == curElement.length) currentLevel = 0;
      else currentLevel = 1;
      obj.options[currentSel].innerHTML = curElement;
    }

    function addPad(obj, currentSel)
    {
      var curElement = obj.options[currentSel].innerHTML;
      var str = '';
      if (Browser.Engine.trident)
      {
        if (currentLevel==1) str='  ';
        curElement = str+curElement.replace(/&nbsp;/g, '').trim();
        obj.options[currentSel].text = curElement;
      }
      else
      {
        if (currentLevel==1) str = '&nbsp;&nbsp;';
        curElement = str+curElement.replace(/&nbsp;/g, '').trim();
        obj.options[currentSel].innerHTML = curElement;
      }
    }

    function change(id)
    {
        id = id.split('__interests')[1];
        var objId = 'activity__interests' + id;
        obj = $(objId);
        removePad(obj, obj.selectedIndex);
        openFl = 0;
        //changeFl = 1;
    }

    function mousedown(id)
    {
        id = id.split('__interests')[1];
        var objId = 'activity__interests' + id;
        obj = $(objId);

        if (openFl==1)
        openFl = 0;
        else
        {
          openFl = 1;
          //changeFl = 0;
          addPad(obj, obj.selectedIndex);
        }
    }

    function blur(id)
    {
        id = id.split('__interests')[1];
        var objId = 'activity__interests' + id;
        obj = $(objId);

        openFl = 0;
        removePad(obj, obj.selectedIndex);
    }

    function myvalidate()
    {
        $('passwordconf').display('none');

        if($('password').value != $('password2').value)
        {
          $('passwordconf').display('');
          validate();
          return false;
        }
        return validate();
    }


function openUploadImageDialog(place_id, uplace_id){
  jQuery('#place').html(place_id);
  jQuery('#uplace').html(uplace_id);
  jQuery('#upload_dialog').css('display','');
  //ajax.doit('::Print_user_photo',uplace_id);
  jQuery('#upload_dialog00').dialog({
					autoOpen: true,
					width: 500,
					height:300
				});

    // Dialog Link
    jQuery('#dialog_link').click(function(){
            $('#add_photo').dialog('open');
            return false;
    });



}


function displaySavedTripsBox2()
{
    jQuery('#dialog-saved-trips').css('opacity', '0');
    savedTripsBox = new Popup(null, {windowId: 'dialog-saved-trips'});
    ajax.doit('::getUserSavedTrips2');
    jQuery('#dialog-saved-trips').fadeIn();
}

function deleteSavedTrip2(trip_id)
{
    ajax.call('::deleteSavedTrip', trip_id);
}


jQuery(document).ready(function($){


  $('.ava-form').submit(function(){
    jQuery(this).ajaxSubmit({
      success:function(data){
        var uid=$('#user_uid').html();
        $('#up_ava').attr('src', '/images/users/'+uid+'/'+data);

      }
    });
    return false;
  });


    $("#locations_sel").change(function () {
      var selec = $("#locations_sel option:selected").val();
        ajax.doit('::update_trip_location', selec);
    });


    jQuery('#searchBoxText').css('color','#aaa').val('Find trips by destination or activity');
    jQuery('#searchBoxText').focusin(function(){
        if (jQuery(this).css('color') == 'rgb(170, 170, 170)') {
            jQuery(this).val('').css('color','#222');
        }
    });
    jQuery('#searchBoxText').focusout(function(){
        if (jQuery(this).val() == ''){
            jQuery(this).css('color','#aaa').val('Find trips by destination or activity');
        }
    });


    // Custom.init();
    if (typeof(custom) !== 'undefined') custom.init();
    cchsckbox_styled();
    cdropbox_styled();

    $('#login_email').keypress(function(event) {
        if (event.which == '13') {
            event.preventDefault();
            $('#login_password').focus();
        }
    });

    $('#login_password').keypress(function(event) {
        if (event.which == '13') {
            event.preventDefault();
            ajax.doit('::login', '');
        }
    });
	if (jQuery('#num_opers').attr('id') == 'num_opers') {
		var num = jQuery('#num_opers').html();
		function getTickerHtml(num) {
			var $html = "";
			while (num != 0) {
				$m = num % 10;
				num = parseInt(num / 10);
				$html = '<img src="/images/number-ticker/'+$m+'.png" alt="'+$m+'" />'+$html;
			}
			return $html;
		}
		jQuery('#num_opers').html(getTickerHtml(num));
	}


});

function cchsckbox_styled()
{
    jQuery('.ccheckbox').each(function(){
        if (!jQuery(this).parent().is('label.ccheckbox-styled')) {
            $label = jQuery('<label class="ccheckbox-styled" />');
            jQuery(this).wrap($label);
            $label = jQuery(this).closest('label');
            if ($label.children('input').attr('checked')) {
                $label.addClass('active');
            } else {
                $label.removeClass('active');
            }
            $label.click(function() {
                if (jQuery(this).children('input').attr('checked')) {
                    jQuery(this).addClass('active');
                } else {
                    jQuery(this).removeClass('active');
                }
            })
        }
    });
}
function cdropbox_styled()
{
    jQuery('.cdropbox').each(function(){

        $elm = jQuery(this);
        if(!$elm.parent().is('label.cdropbox-styled')){
            $elm.wrap('<label class="cdropbox-styled"></label>');
            val = $elm.find('option:selected').html();
            $elm.before('<span class="value">' + val + '</span>');
            $elm.change(function(){
                $celm = jQuery(this).parent('.cdropbox-styled').children('.value').html(jQuery(this).find('option:selected').html());
            });
        } else {
			var $span = $elm.parent().find("span.value");
			if ($span.html()) {
				val = $elm.find('option:selected').html();
				$span.html(val);
				$elm.unbind('change').bind('change', function(){
					$celm = jQuery(this).parent('.cdropbox-styled').children('.value').html(jQuery(this).find('option:selected').html());
				});
			}
		}

	//jQuery(this).click(function(){
        //    if(jQuery(this).children('input').attr('checked')){
	//	jQuery(this).addClass('active');
        //    }else{
	//	jQuery(this).removeClass('active');
        //    }
        //
        //})
    });
}


jQuery.fn.adventuremapView = function(options){
    var options = jQuery.extend({
    }, options);
    return this.each(function(){
        id = jQuery(this).attr('id');
        var latlng = new google.maps.LatLng(0, 0);
        var myOptions = {
            zoom: 1,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.LARGE
            },
            panControl: false,
            streetViewControl: false,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        };
        google_map_view = new google.maps.Map(document.getElementById(id), myOptions);
        jQuery('.panel .box .place-item').each(function(){
            var place_id = new String(jQuery(this).attr('id'));
            place_id = place_id.substr(6);
            view_marker[place_id] = new google.maps.Marker({
                map: google_map_view,
                position: new google.maps.LatLng(jQuery(this).attr('lat'), jQuery(this).attr('lng'))
            });
        });
        jQuery('.panel .box .place-item').click(function(){
            var place_id = new String(jQuery(this).attr('id'));
            place_id = place_id.substr(6);
            google_map_view.setCenter(view_marker[place_id].getPosition());
        });
    });
}

function select_prev_option(selector)
{
    $elm = jQuery(selector + ' option:selected');
    $elm.removeAttr('selected')
    $elm.prev().attr('selected', 'selected');
    if (!jQuery(selector + ' option:selected').length)
    {
        jQuery(selector + ' option:first').attr('selected', 'selected');
    }

    jQuery('#selectmonth2').html(jQuery(selector + ' option:selected').html());
    return false;
}

function select_next_option(selector)
{
    $elm = jQuery(selector + ' option:selected');
    $elm.removeAttr('selected');
    $elm.next().attr('selected', 'selected');
    if (!jQuery(selector + ' option:selected').length)
    {
        jQuery(selector + ' option:last').attr('selected', 'selected');
    }
    jQuery('#selectmonth2').html(jQuery(selector + ' option:selected').html());
    return false;
}


