jQuery(document).ready(function($) {

  var popupTemplate = '<div id="business-card-${id}" class="business-card business-card-${type}"><div class="business-card-close"><a href="#">close</a></div>' +
                      '<div class="business-card-header"><h4 class="business-card-title"><a href="/${friendly_uri}">${company}</a></h4></div>' +
                      '{{if logo}}<div class="business-card-logo"><img src="${logo}" alt="${company} logo" /></div>' +
                      '{{else}}<div class="business-card-logo-empty"></div>{{/if}}' +
                      '<div class="business-card-content">' +
                      '{{if tagline}}<div class="business-card-desc">${tagline}</div>{{/if}}' +
                      '<div class="business-card-address"><p class="business-card-address">${street_address} ${suburb} ${state}</p></div>' +
                     '{{if has_phone}}<p class="business-card-phone"><a class="ph-${id}" href="">View Phone Number</a></p>{{/if}}' +
                      '</div></div>';

  $('#add-comment-form').submit(function() {
    $('input[type=submit]', this).attr('disabled', 'disabled');
  });

  // we have a custom popup for the maps
  omg.maps.Map.prototype.attachClickEvent = function(marker, address) {
    me = this;
    google.maps.event.addListener(marker, 'click', function(event) {
    $('.business-card').hide().remove();
      me.markerRemoveAllFocus();
      var overlay = new omg.maps.TemplateOverlay(me.map,
                                             $.tmpl(popupTemplate, address).get(0));
      me.offsetCenter(marker.position, 0, -80);
      markerId = marker.get('identity');
      me.focusMarker(marker);
      return false;
    });
  }


  $('.business-card-close a').live('click', function() {
    $(this).parents('.business-card').hide().remove();
    map.markerRemoveAllFocus();
    clearResultFocus();
    return false;
  });


function clearResultFocus() {
  $('.map-results-item').removeClass('map-results-item-focus');
  $('.map-marker img').each(function() {
    var src = $(this).attr('src');

    if (overlayPath == null) {
      var src = src.replace(/\_over\.png/, '.png');
    } else {
      var src = src.replace(overlayPath, markerPath);
    }

    $(this).attr('src', src);
  });
}


  /* Toggle tabs & tab planes */
  $('#profile_tabs li').click(function() {
    /* tabs */
    $('#profile_tabs li.current').removeClass('current');
    $(this).addClass('current');

    /* planes */
    $('.tab_plane.current').removeClass('current');
    $('#' + $(this).attr('id') + '_plane').addClass('current');

    if ($(this).attr('id') == 'tab_1') {
      $('.tab-bottom-boxes').show();
    } else {
      $('.tab-bottom-boxes').hide();
    }

  });

  /* toggle side sections */
  $('#sections .section span.toggle, #sections .section h3.clickable').click(function() {
      $(this).parents('.section').find('.section_inner').slideToggle();
      $(this).parents('.section').toggleClass('closed');
  });

  /* special offers */
  $('.specialoffer_box a').click(function(evt) {
    evt.preventDefault();
    if ($('.specialoffer .offer_link').length > 0) {
      $('.specialoffer .offer_link a').eq(0).click();
    }
  });

  $('.specialoffer_box a').click(function() {
    $('.section_icon.specialoffer_icon h3.clickable').click();
  });

  $('a.show_img_tab').click(function() {
    $('ul#profile_tabs li#tab_2').click();
  });

  /* image gallery popups */
  $('a.gallery1').fancybox({type: 'image'});
  $('a.gallery2').fancybox({type: 'image'});
  $('.send_to_mobile a').fancybox({type: 'iframe', width: 640, height: 240});
  $('.click_to_call a').fancybox({type: 'iframe', width: 640, height: 300});
  $('.call_back a').fancybox({type: 'iframe', width: 640, height: 390});
  $('.business-info-email a').fancybox({type: 'iframe', width: 640, height: 530});
  $('#profile-map-overlay-link').fancybox({width: 720, height: 480, onComplete: function() {createMap(); }});
  $('#profile-map-link').fancybox({width: 720, height: 480, onComplete: function() {createMap(); }});

  // special offer
  $('.specialoffer .offer_link a').fancybox({width: 580, height: 270});

  /* youtube links */
  $('a.youtube_links').fancybox();

  $('input.stars').rating();

    // top search box html
    var search_box_html = '<div id="header_search_box">';
    search_box_html += $('#overview_top_search').html();
    search_box_html += '</div>';

    // show the top search bar
    var hsb_top = 0;
    if ($('#header-logo-link a').length > 0) {
      var header_offset = $('#header-logo-link a').offset();
      hsb_top = header_offset.top;
    }
    else if ($('.logo-title a').length > 0) {
      var header_offset = $('.logo-title a').offset();
      hsb_top = header_offset.top;
    }
    else {
      hsb_top = $('#header .banner-728').css('margin-top');
    }
    $('#header .banner-728').after(search_box_html);
    $('#header #header_search_box').css('float', 'right');
    $('#header #header_search_box').css('margin-top', hsb_top);
    $('#header #header_search_box').css('margin-right', $('#header .banner-728').css('margin-right'));

    $(':input[class*=predictive_category]').omgsuggestion({
      url: '/static/predictive/category.php',
      dataType: 'json',
      text: 'Type to search for category'
    });

    $(':input[class*=predictive_location]').omgsuggestion({
      url: '/static/predictive/search.php',
      dataType: 'json',
      text: 'Type to search for location'
    });

  /* anchor hooks */
  if ((document.location.hash != '') && (document.location.hash.length > 1)) {
    var anchorStr = document.location.hash.substring(1, document.location.hash.length);
    switch (anchorStr) {
      case 'gallery':
      case '_tab_2':
        // top of gallery
        if ($('ul#profile_tabs li#tab_2').length > 0) {
          $('ul#profile_tabs li#tab_2').trigger('click');
        }
        break;
      default:
        if (anchorStr.charAt(0) == '_') {
          anchorStr = anchorStr.substring(1, anchorStr.length);
        }
        if ($('ul#profile_tabs li#' + anchorStr).length > 0) {
          $('ul#profile_tabs li#' + anchorStr).trigger('click');
        }
        break;
    }
  }

  if ($('.bs-content').height() <= 200) {
    $('.read-more').hide();
    $('.expandable').removeClass('expandable');
  }

  /* show additional locations */
  $('.show_locations').click(function(evt) {
    evt.preventDefault();
    $(this).hide();
    $('.additional_locations').show('fast');
    return false;
  });

  $('.read-more').click(function() {
    $('#businesslisting_summary .expandable').removeClass('expandable');
    $(this).hide();
    return false;
  });

  $('.show_videos').click(function() {
    if ($('.more-videos').is(':visible')) {
      $(this).text($(this).text().replace('Hide', 'Show'));
    } else {
      $(this).text($(this).text().replace('Show', 'Hide'));
    }

    $('.more-videos').slideToggle('slow');

    return false;
  });

  $('.show_downloads').click(function() {
    if ($('.more-downloads').is(':visible')) {
      $(this).text($(this).text().replace('Hide', 'Show'));
    } else {
      $(this).text($(this).text().replace('Show', 'Hide'));
    }

    $('.more-downloads').slideToggle('slow');

    return false;
  });

  if ($('#more-comments').length) {
        $('#show-more-comments').click(function() {
            $('#more-comments').slideDown('slow');
            return false;
        });
    }

    $('.write-review-button').click(function() {
      $('#tab_1').click();
      $('#comment-form').slideDown('slow');

      var targetOffset = $('#comment-form').offset().top;
      $('html,body').animate({scrollTop: targetOffset}, 1000);
      return false;
    });

	$('#key-info-rating .business-rating,#key-info-rating .business-review-number').click(function() { 
	  var targetOffset = $('#comments').offset().top; 
	  $('html,body').animate({scrollTop: targetOffset}, 1000); 
	  return false; 
	}); 

    $('.write-review').click(function() {
      $('#comment-form').slideDown('slow');

      var targetOffset = $('#comment-form').offset().top;
      $('html,body').animate({scrollTop: targetOffset}, 1000);
      return false;
    });

    $('.close-comment a').click(function() {
      $('#comment-form').slideUp('slow');
      return false;
    });

    if (location.hash != undefined) {
        var href = location.hash;
        $('a[href="' + href + '"]').filter('.autoclick').click();
    }

    defaultMapStyle = {};

    if ($('.bus-map').length > 0) {
      $('a#enlarge_map').fancybox({onStart: function() {
        defaultMapStyle.width = $('#map_canvas').css('width');
        defaultMapStyle.height = $('#map_canvas').css('height');
        $('#map_canvas').css({'width': 640, 'height': 450});

        if (typeof map != 'undefined') {
          map.resize();
        }
      },
      onClosed: function() {
        $('#map_canvas').css({'width': defaultMapStyle.width, 'height': defaultMapStyle.height});
        if (typeof map != 'undefined') {
          map.resize();
        }
      }});
    }

    var photo = jQuery('.thumbnail_inner');
    $('.zoom_icon').css('opacity','0');

    photo.hover(function(){
      $(this).find('img.thumbnail_image').stop(true, true).animate({opacity: 0.7}, 500);
      $(this).find('.zoom_icon').stop(true, true).animate({opacity: 1}, 400);
    }, function(){
      $(this).find('.zoom_icon').stop(true, true).animate({opacity: 0}, 400);
      $(this).find('img.thumbnail_image').stop(true, true).animate({opacity: 1}, 500);
    });

    $('.business-info-phone a').live('click', function() {
        var container = $(this).parent();
        var listing_id = $(this).data('id');
        var hash = $(this).data('hash');
        var call = $(this).data('enable');

        var add_loc = $('#additional_location_' + listing_id).text();
        var add_uri = '&hash='+hash;
        if (add_loc > 0) {
            add_uri = '&additional_loc_id=' + add_loc;
        }

        $.getJSON('http://' + location.hostname + '/static/secure_omg/businesslisting_details.php?data_type=phone&id=' + listing_id + add_uri,
            function(data) {
            if (typeof data != 'undefined') {
                if (data.phone != '') {
                      var phone = '<span class="phone-number-view">' + data.phone;
                      $(container).html(phone);
                      if (call) {
                        $('.click_to_call a').click();
                      }
                }
                if (data.tracking != '') {
                var tracking = $('<img border="0" width="0" height="0" src="' + data.tracking + '" />');
                tracking.appendTo('body');
                }
            }
            });
        return false;
    });

   $('.thumbnail_image').each(function() {
    var image = $(this);
    var parentContainer = image.parent().parent();

    var parWidth = parseInt(parentContainer.width());
    var parHeight = parseInt(parentContainer.height());
    var parAspect = parWidth / parHeight;

    var imgWidth = parseInt(image.width());
    var imgHeight = parseInt(image.height());
    var imgAspect = imgWidth / imgHeight;

    image.parent('a').css({'margin-left': Math.round((parWidth - imgWidth) / 2) + 'px'});
  });

  $('.website-tracking').click(function() {
     var url = statsBeacon + '/';

     if ($('#website-tracker').length == 0) {
      $('<img id="website-tracker" width="0" height="0" src="' + url + '" />').appendTo('body');
    }
  });

  function formValidator(form, e) {
    var errorContainer = form.parent('div').find('.cf-error');
    var errorList = errorContainer.find('ul');
    errorList.html('');

    form.find('.cf-required').each(function() {
      var element = $(this);
      var friendlyName = element.data('friendly');

      if (element.attr('type') == 'checkbox') {
        if (element.attr('checked') == false) {
        errorList.append('<li>' + friendlyName + ' Required</li>');
        }
      } else {
        if (element.val() == '') {
          errorList.append('<li>' + friendlyName + ' Required</li>');
        }
      }
    });

    if (errorList.find('li').length > 0) {
      errorContainer.fadeIn();
      return false;
    } else {
      errorContainer.hide();
      return true;
    }
  }

    function checkHash() {
        if (location.hash) {
            if (location.hash.indexOf('#show_photo_') === 0) {
                var photoid = location.hash.substr(12), tab;
                if (tab = $('ul#profile_tabs li#tab_2')) {
                    tab.click();
                }
                $('#photo_' + photoid).click();
            } else if (location.hash.indexOf('#show_video_') === 0) {
                var videoid = location.hash.substr(12);
                $('#video_' + videoid).click();
            } else if (location.hash.indexOf('#tab_') === 0) {
                if (tab = $('ul#profile_tabs li' + location.hash)) {
                    tab.click();
                }

            }
        }
    }

    checkHash();

    $('.stream-content a').click(function(e) {
        setTimeout(checkHash, 200);
    });
    
    // Text-Overflow //
    $('#sections .section ul.downloads p.dl-description').textOverflow();
    $('.business-info .business-info-website p a').textOverflow();
    $('#sections .section ul.downloads span.heading').textOverflow();
	$('#key-info-box h1').textOverflow();

    // Tool Tips //
    $('.business-rating').qtip({
      position: {
        corner: {
        target: 'topMiddle',
        tooltip: 'bottomMiddle'
        }
      },
      style: { name: 'blue', tip: true } });
    
    $('#sections .section ul.downloads p.dl-description').qtip({
      position: {
        corner: {
        target: 'topMiddle',
        tooltip: 'bottomMiddle'
        }
      },
      style: { name: 'blue', tip: true } });

});

