var debug = true;
var tooltipStrings = [];
tooltipStrings["tool_studio"] = "Your weekly 30 minute fix of golf news, opinion, conjecture and other stuff we've been up to";
tooltipStrings["tool_prozone"] = "If they're on tour, they're in here — Interviews, insight, inside the ropes";
tooltipStrings["tool_whattoplay"] = "Upgrade your gear";
tooltipStrings["tool_howtoplay"] = "Improve your game";
tooltipStrings["tool_wheretoplay"] = "Find your golf paradise";
tooltipStrings["tool_bedlam"] = "That part of the channel where things get a bit unusual";
tooltipStrings["tool_yourgolf"] = "Everything you ever needed in a golf social networking site but were afraid to ask for — <br />talk to your golf pals, create a society, log scores, get &amp; track a handicap, show off your photos, loads more – marvelous";
tooltipStrings["tool_competition"] = "Golf competition videos";// // // // //

function trace(str) {
	if (typeof(console) == 'object') {
		console.log(str);
	}
}

function isset(variable) {
	return (variable == undefined);
}

// // // // //

function init_base() {
	$.classifyInputs();
	$(".giveMyChildrenClass").giveMyChildrenClass();
	$.formatMenuAndFooter();
	$(".identifyLast").identifyLast();
	$(".identifyFirst").identifyFirst();
	//$("label.overlabel").overlabel();
	$(".hoverMe").addHover();
	$(".stripeMe").stripeMe();
	$('div.bubble.comment').formatBubbleComment();
	$("table.numberRows").numberRows();
	$(".makeMeLink").makeMeLink();
	$(".makeMeChildsLink").makeMeChildsLink();
	//$(".starRater:has(select)").stars({inputType:"select"});
	//
	fix_topmenu();
	colour_dataTables();
	$.googleAnalytics();
	prepTooltips();
}

/// BASICS

$(document).ready(function() {
	init_base();
  $('.cont').hover(function() {
    $(this).addClass('cont-hover');
  }, function() {
    $(this).removeClass('cont-hover');
  });
})



/// LAYOUT FUNCS

function fix_topmenu() {
	$(".top_menu").each(function() {
		$(this).prepend("<span class='buffer_before'>&nbsp;</span>");
		$(this).hover(function() {
			$(this).addClass('hover');
		},function() {
			$(this).removeClass('hover');
		});
	});
}

function colour_dataTables() {
	$("table.data thead").each(function() {
		var $this = $(this);
		var _color = $this.css('background-color');
		$this.parent().css('border-color',_color);
	});
}

$.classifyInputs = function () {
	$("input[type=text]").addClass('text');
	$("input[type=password]").addClass('password');
	$("input[type=submit]").addClass('submit');
	$("input[type=button]").addClass('button');
	$("input[type=checkbox]").addClass('checkbox');
};

$.formatMenuAndFooter = function () {
  $("ul.sidemenu li:has(a), #footer ul li:has(a)").each(function() {
    $(this).addClass('hoverMe makeMeChildsLink');
  });
};

$.googleAnalytics = function() {
  return false;
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  $(document).append(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
  var pageTracker = _gat._getTracker("UA-4917116-1");
  pageTracker._initData();
  pageTracker._trackPageview(); 
}

$.fn.identifyLast = function () {
	return this.each(function() {
		$this = $(this);
		if ($this.hasClass('identifyLast')) {
			$this.parent().find('.identifyLast:last').addClass('last');
			$this.parent().find('.identifyLast').removeClass('identifyLast');
		}
	})
}

$.fn.identifyFirst = function () {
	return this.each(function() {
		$this = $(this);
		if ($this.hasClass('identifyFirst')) {
			$this.parent().find('.identifyFirst:first').addClass('first');
			$this.parent().find('.identifyFirst').removeClass('identifFirst');
		}
	})
}

$.fn.addHover = function() {
	return this.each(function() {
	 	var _self = $(this);
		_self.hover(function() {_self.addClass('hover')}, function() {_self.removeClass('hover')} );
	})
};

$.fn.stripeMe = function() {
	return this.each(function() {
		var _data = $(this).metadata();
		if (typeof(_data.stripeMe) == 'undefined') {
			_selector = 'tr';	
		} else {
			_selector = _data.stripeMe;
		}
		$(this).find(_selector+':even').each(function() {
			$(this).addClass('alt');	
		})
	})
}

$.fn.numberRows = function() {
	return this.each(function() {
		$(this).removeClass('numberRows')
		var _count = 1;
		debug(this);
		$(this).find('thead tr').each(function() {
			$(this).prepend("<td class='rowNumber'>&nbsp</td>");
		});
		$(this).find('tbody tr').each(function() {
			$(this).prepend("<td class='rowNumber'>"+_count+".</td>");
			_count++;
		});	
	});
}  

$.fn.makeMeLink = function () {
  return this.each(function() {
    $this = $(this);
    var _data = $this.metadata();
    var _href = _data.href;
    $this.css('cursor','pointer');
    $this.click(function() {
      window.location = _href;
    });
  });
}

$.fn.makeMeChildsLink = function () {
  return this.each(function() {
    $this = $(this);
    $child = $($this.find("a").eq(0));
    var _href = $child.attr('href');
    $this.css('cursor','pointer');
    $this.click(function() {
      window.location = _href;
    }); 
  }); 
}

$.fn.formatBubbleComment = function () {
  return this.each(function() {
    settings = {
      tl: { radius: 10 },
      tr: { radius: 10 },
      bl: { radius: 10 },
      br: { radius: 10 },
      antiAlias: true,
      autoPad: true
    }
    //
    $(this).find('p').wrap("<div class='rounded'><blockquote></blockquote></div>");
    $(this).find('cite').addClass('rounded');
    //
    $(this).find('.rounded').each(function() {
     //var myBoxObject = new curvyCorners(settings,this);
     //myBoxObject.applyCornersToAll();
    });
  });
}

$.fn.giveMyChildrenClass = function () {
  return this.each(function() {
    var $this = $(this);
    var _data = $this.metadata();
    var _classes = _data.giveMyChildrenClass;
    $this.children().each(function() {
      $(this).addClass(_classes);
    });
  }); 
}

$.fn.identify = function () {
  return this.each(function() {
    trace(this);
  });
};

$.insertVideo = function ($id,$element,$autoplay,$width,$height) {
  // trace("insert video " + $id + " into element "+$element);
  var url = '/video/'+$id+'/_getPlayer?autoplay='+$autoplay+'&width='+$width+'&height='+$height;
  //traces(url);
  $($element).load(url);
  return false;
} 

$.fn.manyFields = function () {
  return this.each( function() {
    var $this = $(this);
    trace(this);
    $this.parent().wrapInner("<div></div>");
    $this.before("<span class='manyFieldsContainer'></span>");
    $this.after("<span class='inputTip'>Press enter to add more</span>");
    var $name = $this.attr('name');
    $this.attr('name',$name+"[]");
    $this.keydown(function(k) {
      if ((k.keyCode == 9 || k.keyCode == 13) && ($this.val().trim() != "")) {
        $this.val($this.val().trim());
        var spanStr = "<span class='manyFieldsItem'>"+$(this).val()+"<input type='hidden' name='"+$name+"[]' value='"+$(this).val()+"'><img src='/asset/icons/famfam/delete.png' onclick='$(this).parent().remove()'></span> ";
        $this.parent().find('.manyFieldsContainer:first').append(spanStr);
        $(this).val('');
        return false;
      }
    });
  }); 
}

function prepTooltips(){
	/* CONFIG */
	xOffset = 10;
	yOffset = 20;
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
	/* END CONFIG */
	$(".tooltip").hover(function(e){								  
		//this.t = this.title;
		//this.title = "";									  
		$("body").append("<p id='tooltip'>"+tooltipStrings[$(this).attr('id')]+"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.css("z-index","99999")
			.fadeIn("fast");		
		},
		function(){		
			$("#tooltip").remove();
		}
	);
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


/// AC

function formatItem(row) {
  return row[0];
}
// function selectItem(li) {
  // findValue(li);
// }

///// TRIM

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


///// TINY MCE

function initMCE()
{
    tinyMCE.init({ mode : "none",
		theme : "advanced",
		plugins : "spellchecker, table",
		theme_advanced_layout_manager : "SimpleLayout",
		theme_advanced_disable: "hr,",
		theme_advanced_buttons1: "bold,italic,underline,separator,link,separator,bullist,numlist,outdent,indent,spellchecker",
		theme_advanced_buttons2: "tablecontrols",
		theme_advanced_buttons3: "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		content_css : "css/content.css",
		table_styles : "Header 1=header1;Header 2=header2;Header 3=header3",
		table_cell_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Cell=tableCel1",
		table_row_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1",
		table_cell_limit : 100,
		table_row_limit : 5,
		table_col_limit : 5
	})
}

jQuery.fn.tinymce = function(options)
{
    return this.each(function()
    {
        if (!jQuery(this).attr('id')) {
			jQuery(this).attr('id','mce_'+Math.floor(Math.random()*100001))	
		}
		toogleEditorMode(this.id);
    });
}
// this is where we decide the toggle of 'on' (true) or 'off' (false)
// init an array to keep each id's state seperate
var tinyMCEmode = new Array();
function toogleEditorMode(sEditorID)
{
	trace("MCE - " + sEditorID);
    if(tinyMCEmode[sEditorID])
    {
        try
        {
            tinyMCE.execCommand('mceRemoveControl', false, sEditorID);
            tinyMCEmode[sEditorID] = false;
        }
        catch(e)
        {
            alert( "REMOVE:" + sEditorID + ':' + e.message);
        }
    }
    else
    {
        try
        {
            tinyMCE.execCommand('mceAddControl', false, sEditorID);
            tinyMCEmode[sEditorID] = true;
        }
        catch(e)
        {
            alert( "ADD:" + sEditorID + ':' + e.message);
        }
    }
}