var rootPath = "";
var imagePath = "images";

var voted = false;
var lastHover = -1;

$(document).ready(function() {
	$('#submitBasicSearch').click(function() {
		$(this).parent('form').submit();
		return false;
	});

	// Advanced search
	$('#toggleAdvanced').toggle(function() {
		$('#searchAdvanced').slideDown('slow');
		$(this).find('img').attr('src', rootPath + '/' + imagePath + '/spic_minus.gif');
	}, function() {
		$('#searchAdvanced').slideUp('slow');
		$(this).find('img').attr('src', rootPath + '/' + imagePath + '/spic_plus.gif');
	});
	
	// Pagination (todo)
	$('.disabled, .selected', '.pagination').click(function() { return false; });
	
	// Tabs
	$('.tabs > .tabsTitle > a').click(function() {
		if (!$(this).hasClass('selected') && !$(this).hasClass('startSelected')) {
			$('> a.selected, > a.startSelected', '.tabs > .tabsTitle').animate({
				width: '88px'
			}, 'fast').css('borderRight', '1px solid #cdcdcd').removeClass('selected startSelected');
		
			$(this).animate({
				width: '94px',
				borderRight: '0'
			}, 'fast').addClass('selected');
			
			$('> div.selected, > div.startSelected', '.tabs > .tabsContent').removeClass('selected startSelected').show().slideUp('slow');
			$('> div:nth-child(' + ($(this).prevAll().size() + 1) + ')', '.tabs > .tabsContent').addClass('selected').slideDown('slow');
		}
		
		return false;
	});
	
	$('.myform .field').click(function() {
		if (!$(this).hasClass('selected')) {
			$(this).parents('.myform').find('.field.selected').removeClass('selected').children('span').animate({
				opacity: '0'
			}, 'slow');
			$(this).addClass('selected').children('span').animate({
				opacity: '1'
			}, 'slow');
		}
	});
	
    var recipeStepNum = 3;
	// Add recipe form
	$('.dynamicFields > *:input').live('click', function() {
		if ($(this).parent().find('input[value=]').size() < 2) {
            if($(this).attr('name') == 'instructions[]') {
                var step = $('<label>Step ' + recipeStepNum + ':</label>');
                recipeStepNum++;
                $(this).parent().append(step);
            }
			$(this).parent().append($(this).clone().attr('value', ''));
            $(this).parent().siblings('span.frontSpan').css('top', $(this).position().top);
		}
	});

	
	$('.tabs .nextStep').click(function() {
		var temp = $(this).parents('.tabs').find('.tabsTitle > a.selected, .tabsTitle > a.startSelected').next();
		
		if (temp.size()) {
			$(temp).click();
			return false;
		}
	});

	$('textarea#addDescText').live('keyup',function(){
		var left = 200 - $(this).val().length;
		$('span#addDescChars').html(left+' chars left');
	});
	
	// Recipe rating
// Recipe rating
	$('#recipeRating').mousemove(function(e)  {
		if (!voted) {
			var rating = Math.min(5, Math.floor((e.pageX - this.offsetLeft) / 28) + 1);
			// alert (lastHover);
			if (rating != lastHover) {
				lastHover = rating;
				$(this).find('.rating').animate({
					width: (rating * 28) + 'px'
				}, 'fast');
			}
		}
	});
	
	$('#recipeRating').click(function(e) {
		if (!voted) {
			$.get(rootPath + "/vote", {id: $(this).find('span').text(), rating: lastHover}, function(e) {
				if (e == '1') { voted = true; }
			});
		}
	});

	// Recipe gallery
	$('#galleryLinks a').click(function(e) {
		var temp = $(this).parent().siblings(".galleryFocus").clone();

		$('.galleryFocus').slideUp('slow', function() { $(this).remove(); });
		$(temp).hide().find("img").attr("src", $(this).attr("href"));
		$(this).parent().before(temp);
		$(temp).slideDown('slow');
		
		return false;
	});
	
	// Sort by box
	//$('#sort select').change(function() {
	//	var temp = $(this).parent("#sort").find("form");
	//	$(temp).attr("action", $(temp).attr("action") + $(this).val()).submit();
	//});

    $('a.srSort').click(function() {
		var temp = $(this).parent("#sort").find("form");
		$(temp).attr("action", $(temp).attr("action") + $(this).attr('name')).submit();
        return false;
    });

    // Print recipe
    $('#printRecipeLink').click(function() {
        var newWindow = window.open('','','width=600, height=700, scrollbars=yes');
        var logo = '<div style="background-image:url(\'/images/logo_bg.gif\'); padding:10px 0px 0px 10px;"><img src="/images/bethecook_logo.gif"><p style="color:#A7E85A;">Record, upload, and share with the world your best recipes</p></div>';
        var recipeName = '<h1>' + $('#recipeName').html() + '</h1>';
        var ingredient = $('#ingredientInstruction').html();
        if(!ingredient) {
            ingredient = $('div.recipeIngredients').html();
        }
        newWindow.focus();
        newWindow.document.write(logo);
        newWindow.document.write(recipeName);
        newWindow.document.write(ingredient);
        newWindow.document.close();
        newWindow.print();
        newWindow.close();
        return false;
    });


    $('div.similarRecipes div.recipe').live('mouseover', function() {
        $('a img', this).css('border', '1px solid blue');
        $(this).css('background-color', '#eee'); 
        $('div.detail', this).hide();
        $('div.description', this).show();
    });

    $('div.similarRecipes div.recipe').live('mouseout', function() {
        $('a img', this).css('border', '');
        $(this).css('background-color', ''); 
        $('div.description', this).hide();
        $('div.detail', this).show();
    });

    /*
    $.get('categories.php', {'cat':1}, function(data) {
           var res = eval("(" + data + ")");
           var catList = '';
           for (var k in res) {
              var obj = res[k];
              var newLi = '<li><a href="http://www.bethecook.com/categories/' + obj['short_name'] + "\" />" + obj['name'] + "</a></li>";
              catList += newLi;
              console.log(newLi);
           }
         
           //$('li#catID ul').append(catList);
    });
    */

    $('div#leaderBoardAd').load('/leaderBoardAd.php');
    $('div#rectangleAd').load('/rectangleAd.php');
    $('div#skyscraperAd').load('/skyscraperAd.php');

    $('input.searchButton').click(function() {
        var kw = $('input[name="search"]').val();
        if(kw == '') {
            return false;
        }
    });

    // Canonical
    var url = top.location.href;
    var reg1 = new RegExp('\/recipes\/');
    var reg2 = new RegExp('\/yt\/');
    if (url.match(reg1)) {
        $('head').append('<link rel="canonical" href="http://www.bethecook.com/recipes/" />');
    }
    else if (url.match(reg2)) {
        $('head').append('<link rel="canonical" href="http://www.bethecook.com/yt/" />');
    }
    
});

function setVideoCompanionBanner(banners,justHTML){	
	var temp = [], i, showBanner;
	
	if(!banners || !banners.length || banners.length == 0) return;
	
	showBanner = function(banner){
		var getSetVal = function(o, arr){
			for(var i=0; i<arr.length; i++){
				if(o[arr[i]]) return o[arr[i]];
			}
		},gen = {
			'iframe': function(o){
				var url = getSetVal(o,['htmlUrl','url','URL','htmlURL']);
				return $('<iframe src="'+url+'" width="300" height="250" scrolling="no" frameborder="0" marginheight="0" marginwidth="0"></iframe>');
			},
			'image': function(o){
				var imgSrc = getSetVal(o,['imageUrl','url','URL','imageURL']),url;
				if(o['CompanionClickThrough']){
					url = o['CompanionClickThrough'].URL;
				}else{
					url = getSetVal(o,['clickURL','clickUrl']);
				}
				
				return '<a href="'+url+'" target="_blank"><img src="'+imgSrc+'" width="300" height="250" /></a>';
			},
			'swf': function(o){
				var swf = getSetVal(o,['swfUrl','url','URL','swfURL']);
				return flashHTML(swf,300,250,'','opaque');
			},
			'htmlSource': function(o){return getSetVal(o,['source','SOURCE','Code','code']);},
			'static': function(o){
				if(o.creativeType){
					if(o.creativeType=='application/x-shockwave-flash') return gen['swf'](o);					
					if(o.creativeType.substring(0,5)=='image') return gen['image'](o);
					return '';
				}
			},
			'HTML':function(o){
				return gen['htmlSource'](o);
			}
		};
		
		if(gen[banner.resourceType]){
			var o, ad = $('div#rectAd'), b=gen[banner.resourceType](banner);
			if(typeof(b)=='string'){
				o=$('<div id="vComp">'+b+'</div>');
			}else{
				o=$('<div id="vComp"></div>');
				o.append(b);
			}
			
			ad.css({position: 'relative'});
			o.css({position: 'absolute', top: '0px'});
			ad.children().css({visibility: 'hidden', width:'0px', height:'0px', overflow:'hidden'});
			ad.append(o);
			setTimeout(function(){
				ad.children().css({visibility: 'visible',width:'',height:'',overflow:''});
				o.css({visibility: 'hidden'});
			}, 30000);
			return true;
		}
		return false;
	};
	
	if(justHTML){
		return showBanner({source: banners, resourceType: 'htmlSource'});
	}
	
	for(i=0; i<banners.length; i++){
		if(banners[i].height=='250' && banners[i].width=='300'){
			temp.push(banners[i]);
		}
	}
	banners=temp;
	
	for(i=0; i<banners.length; i++){
		if(showBanner(banners[i])){
			return;
		}
	}
}

