var $j = jQuery.noConflict();

/* Are we in a client app or in a browser? */
function appOrBrowser() {
  // If the userAgent string has no version, we're in an app
  if(navigator.userAgent.indexOf('Version') > 0) {
    return 'browser';
  } else {
    return 'app'
  }
}

function menuCarouselInitCallback(carousel) {
  window.menuCarousel = carousel;
}

function bodyCarouselInitCallback(carousel) {
  window.bodyCarousel = carousel;
}

function selectMenuTab(element) {
  var index = $j(element).parent().attr('jCarouselIndex');
  window.menuCarousel.scroll(index - 2);
  window.bodyCarousel.scroll(index - 2);
  $j('#menutab li').removeClass('active');
  $j(element).parent().addClass('active');
}

function initCarousels() {
  /* Prep menu tab carousel */
  // First, add onclick logic to all menu items
  $j('#menutab li').each(function() {
    // We need to include a physical anchor tag, and not a bind, because this will get 
    // replicated many times by the carousel logic
    $j(this).html('<a href="javascript:void(null);" onclick="selectMenuTab(this);" rel="hands-off">' + $j(this).html() + '</a>');
  });
  
  // Next, init carousels
  $j('#menutab').jcarousel({
  	wrap: 'circular',
  	initCallback: menuCarouselInitCallback
  });
  $j('#listings').jcarousel({
  	wrap: 'circular',
  	initCallback: bodyCarouselInitCallback
  });
  
  $j('#menutab .tab').removeClass('active');
  $j('#menutab .tab.default').addClass('active');
}

/* fix rotate */

function getTransformProperty(element) {
    var properties = ['transform', 'WebkitTransform',
                      'MozTransform', 'msTransform',
                      'OTransform'];
    var p;
    while (p = properties.shift()) {
        if (element.style[p] !== undefined) {
            return p;
        }
    }
    return false;
}

function _rotate( el, deg ){
  var el = el.get(0);
  var property = getTransformProperty(el);
  if ( property ) {
    $j( el ).data('rotatation', deg );
    if ( deg == 0 ) {
      el.style[ property ] = '';
    } else {
      el.style[ property ] = 'rotate(' + deg%360 + 'deg)';
    }
  }
}

function initCategories() {
  /* Activate "view all categories" area */
  $j('#seeCategory').click(function() {
    if($j(this).hasClass('activated')) {
      $j(this).removeClass('activated');
      //$j(this).find('.icon').animate({'rotate': 0});
      _rotate( $j(this).find('.icon'), 0 );
      $j(this).parent().find('#allCategories').slideUp(500);
      $j(this).find('.label').html('&nbsp;See All Our Categories');
    } else {
      $j(this).addClass('activated');
      //$j(this).find('.icon').animate({'rotate': -90});
      _rotate( $j(this).find('.icon'), -90 );
      $j(this).parent().find('#allCategories').slideDown(500);
      $j(this).find('.label').html('&nbsp;Close Categories');
    }
  });
  
  /* Assign banner classes */
  $j('.ribbon.marketplace #listings #categoryheading .label .special').each(function() {
    $j(this).parents('#categoryheading').addClass($j(this).html().replace(/[^A-Za-z]/g, '').toLowerCase());
  });
  
  /* Add category label for search results page */
  $j('#featured #allCategories > .category a').each(function() {
    $j(this).attr('href', $j(this).attr('href') + '&category=' + escape($j(this).html()));
  });
}

function prepareFindUrl(){
  var elWhat = $j('form#searchForm input#what');
  var elWhere = $j('form#searchForm input#where');
  var what = elWhat.val() == elWhat.attr('default') ? '' : elWhat.val();
  var where = elWhere.val() == elWhere.attr('default') ? '' : elWhere.val();
  var location = $j('form#searchForm').attr('target') + '&string=' + escape(what) + '&open=&location_tags=' + escape(where) + '&radius_center=' + escape(where);
  $j('#findbttn').attr('href', location);
}

function initFind() {
  /* Activate Find button */
  $j('form#searchForm input').change(function() {
    prepareFindUrl();
  }).bind('keypress', function(e){
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13){
      prepareFindUrl();
      window.location = $j('#findbttn').attr('href');
    }
  });;

  /* Apply default text logic to text inputs */
  $j('input.hasDefault').each(function() {
    $j(this).addClass('default');
    $j(this).bind('focus', function() {
      if($j(this).val() == $j(this).attr('default')) {
        $j(this).val('');
        $j(this).removeClass('default');
      }
    });
    $j(this).bind('blur', function() {
      if($j(this).val() == '') {
        $j(this).val($j(this).attr('default'));
        $j(this).addClass('default');
      }
    });
  });
}

function cleanUpResults() {
  // Add classes to listings for styling
  $j('.ribbon.marketplace #results_list > div[id^=result_]').each(function() {
    $j(this).addClass('listing');
    // This element will be a bar div with no class if it's a plain old listing, 
    // otherwise, it's a featured listing
    if($j(this).children().children().attr('class') != '') {
      $j(this).addClass('featured');
    }
  });
  
  // Remove old map container
  $j('#featured #results_map_container').remove();
  
}

function moveContent() {
  /* Move listings into place */
  $j('.cms-listings .widgetBody > div').addClass('listing');
  // Remove tags
  $j('.cms-listings .fontSmall a[href^=/pages]').parent().remove();
  $j('.ribbon.marketplace #listings li').each(function() {
    $j(this).find('.column.first').append($j('.cms-listings.' + $j(this).attr('rel') + ' .widgetBody > div:even').clone());
    $j(this).find('.column.last').append($j('.cms-listings.' + $j(this).attr('rel') + ' .widgetBody > div:odd').clone());
  });
  $j('.cms-listings').remove();
}

$j(function() {
  if($j('.ribbon.marketplace.index').size() > 0) {
    initCategories();
    initFind();
    initCarousels();
    moveContent();
  } else if($j('.ribbon.marketplace.results').size() > 0) {
    cleanUpResults();
    initFind();
  }
});
