// Javascript

// Firebug
if (!window.console || !console.firebug){
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i) {
        window.console[names[i]] = function() {};
	}
}

$(document).ready(function () {

    //corners();
    pageActions();
    userAlerts();
    flashEmbeds();
    trackAds.init();
    launchSearch();
    shadowBox();
    shadowBoxSmall();
    confirm_delete();
    gallery.init();
    rating();
    disableCP();
    searchSuggest();
    dashboardTabs();
    galleryScroll();
	maxLength();
	datePicker();
	toolTips();
	limitCopy();
	externalLinks();
	
});

// externalLinks()
/*
* Allows external links to be opened in a new window without the use of target attribute
* @return bool
*/
function externalLinks() {
	
	//SETS DOMAIN OF SITE
	var domainName=document.domain;
	
	var externalLinks=document.getElementsByTagName("a"); //FIND ALL LINKS ON THE CURRENT PAGE
	
	for(var i=0; i<externalLinks.length; i++) { //LOOP THROUGH LINKS ARRAY
	
		var attribute=externalLinks[i].getAttribute("href"); //GETS CONTENT OF 'HREF' ATTRIBUTE ON CLICKED LINK
		
		var elementClass = externalLinks[i].className; //STORES CLASS NAME OF ELEMENT
		
		if (attribute) {
		
			var contains_http=attribute.indexOf("http"); //GET VALUE http IN 'HREF' **FOR MOZILLA&&
			
			var contains_domain=attribute.indexOf(domainName); //GET VALUE domainName **FOR IE**
			
			if(contains_http>-1 && contains_domain==-1) { //DOES CONTAIN AN 'http' OR DOES NOT CONTAIN domainName
			
				setElementAttribute(externalLinks[i], 'target', '_blank');	
				
			}
			
			if(elementClass.indexOf('new_window') > -1 ) { //FORCE LINK TO OPEN IN NEW WINDOW
				
				setElementAttribute(externalLinks[i], 'target', '_blank');
				
			}
		
		}
		
	}
	
}

// setElementAttribute()
/*
* Sets elements attribute
* @return bool; @param element: Element to attach attr to, attr: The attribute to be added, val: value of attribute
*/
function setElementAttribute(element, attr, val) {

	element.setAttribute(attr, val); //SET ATTRIBUTE ON ELEMENT

	return true;

}

function limitCopy ()
{

	var level = $('#mb_visibility');

	$('#mb_summary').bind('keyup', function () {
	
		var length = 250;
		if (level.val() == 'silver') {
			length = 150;	
		} else if (level.val() == 'bronze') {
			length = 100;
		}
	
		var curlen = $(this).val().split(' ');
		if ((curlen.length-1) > length) {
			limitValue (curlen, $(this), length);
		}
	
	});
	
	$('#mb_summary').bind('focus', function () {

		var length = 250;
		if (level.val() == 'silver') {
			length = 150;	
		} else if (level.val() == 'bronze') {
			length = 100;
		}

		var curlen = $(this).val().split(' ');
		if ((curlen.length-1) > length) {
			limitValue (curlen, $(this), length);	
		}
	
	});
	
	$('#mb_summary').bind('blur', function () {

		var length = 250;
		if (level.val() == 'silver') {
			length = 150;	
		} else if (level.val() == 'bronze') {
			length = 100;
		}

		var curlen = $(this).val().split(' ');
		if ((curlen.length-1) > length) {
			limitValue (curlen, $(this), length);
		}
	
	});

}

function toolTips ()
{

	if($('.tip').length == 0) { return false; }
	
	// select all desired input fields and attach tooltips to them
	$(".tip").tooltip({
	
		// place tooltip on the right edge
		position: "center right",
		
		// a little tweaking of the position
		offset: [-2, 10],
		
		// use the built-in fadeIn/fadeOut effect
		effect: "fade"
	
	});
	
}



function shadowBoxSmall() {

    if ($('*[rel="shadowboxsmall"]').length == 0 && $('*[rel="shadowbox[Gallery]"]').length == 0) return false;
    Shadowbox.init({
    height: 300
});

}

function shadowBox() {

    if ($('*[rel="shadowbox"]').length == 0 && $('*[rel="shadowbox[Gallery]"]').length == 0) return false;
    Shadowbox.init();

}

function datePicker ()
{

	if ($('.date').length == 0) return false;

	$(".date").dateinput({
		format: 'dd/mm/yyyy',
		selectors: true,
		yearRange: 	[-100, 5]
	});


}

function maxLength() 
{

	if ($('.maxlen').length == 0) return false;
	
	var classes = $('.maxlen').attr('class').split(' ');
	var length  = classes[1];
	var lengths = length.split('_');
	length      = lengths[1];
	
	$('.maxlen').bind('keyup', function () {
	
		var curlen = $(this).val().split(' ');
		if ((curlen.length-1) > length) {
			limitValue (curlen, $(this), length);
		}
	
	});
	
	$('.maxlen').bind('focus', function () {
	
		var curlen = $(this).val().split(' ');
		if ((curlen.length-1) > length) {
			limitValue (curlen, $(this), length);	
		}
	
	});
	
	$('.maxlen').bind('blur', function () {
	
		var curlen = $(this).val().split(' ');
		if ((curlen.length-1) > length) {
			limitValue (curlen, $(this), length);
		}
	
	});
	

}

function limitValue (curlen, obj, length)
{
	
	var newString = '';
	for(var i=0; i<length; i++) {
		newString += curlen[i] + ' ';
	}
	
	obj.val($.trim(newString));	
	
}

function galleryScroll() {
    if ($(".scrollable").length == 0) {
        return false;
    }
	
	$(".scrollable").scrollable({circular: true});
	
}

function dashboardTabs() {
    if ($("ul.dashboardTabs").length == 0) {
        return false;
    }
    $("ul.dashboardTabs").tabs("div.panes > div");
}

function searchSuggest ()
{

	if ($('#search_suggest').length == 0) return false;
	
	$('#searchfield').live('keyup', searchKeywords);

	$('#searchfield').live('blur', function () { setTimeout('hideSearch()', 300); });
	
}

function hideSearch ()
{

	$('#search_suggest').addClass('hidden');

}

function searchKeywords ()
{

	$.ajax({
		type: 'GET',
		url:  'search/search-suggestion/?keywords=' + $('#searchfield').val().replace(' ', '+') + '/',
		success: function (msg) {
			$('#search_suggest').removeClass('hidden');
			$('#search_suggest').html(msg);
			$('#search_suggest').corner();
		}
	});

}

function confirm_delete() {
	$('a.delete').each(function() {
							$(this).click(function() {
												   		if (!confirm('Are you sure you want to delete this item?')) {
															return false;
														}
										});
					  	});	
}

function userAlerts ()
{

	if ($('#messages').length == 0) return false;
	
	var windowHeight  = parseInt(window.innerHeight);
	var messageHeight = parseInt($('#messages #inner-message-wrap').height());
	
	$('#messages').css('height', $('body').height() + 'px');
	$('#messages div').css('top', ((windowHeight/2)-(messageHeight/2)) + 'px');

}

function pageActions()
{

	if ($('.action').length == 0) return false; //Check to see if there are actions on the page
	
	$('.action').bind('click', function () { //Bind the click action to the action element
	
		if ($(this).hasClass('print')) { //Check that the element has a print class
	
			actions.printPage();
		
		} else if ($(this).hasClass('closeWindow')) { //Check that the element has a close class
			
			actions.closeWindow(); //Close the window
			return false;
			
		} else if ($(this).hasClass('setHP')) { //User wants to set the homepage as their homepage
			
			actions.setHomePage(); //Close the window
			return false;
			
		}
		
	});

}

var actions = {

	printPage: function () {
		print();
		return false;
	},
	closeWindow: function () {
		$('#messages').fadeOut('slow', function () { $('#messages').remove(); }); //Fade out the wrapping div and remove the HTML when complete
	},
	setHomePage: function () {
		window.setHomePage('http://www.roundtable.co.uk/members');
		return false;
	}

}

//Adds corners on to defined elements
function corners ()
{

	if ($('#headerlinks li a').length > 0) {
	
		$('#headerlinks li a').corner("10px");
	
	}
	
	if ($('.searchwrap').length > 0) {
	
		$('.searchwrap').corner("br 0");
	
	}
	
	if ($('#navpanel li a').length > 0) {
		$('#navpanel li a').corner("5px");
	}
	
	if ($('#ctaspanel li a').length > 0) {
		$('#ctaspanel li a').corner("5px");
	}
	
	if ($('#event_info').length > 0) {
		$('#event_info').corner("10px");
	}
	
	if ($('.searchwrap').length > 0) {
		$('.searchwrap').corner("10px left");
	}
	
	if ($('.searchwrap').length > 0) {
    	$('.searchwrap').corner("10px left");
	}
	
	if ($('.tabs li a').length > 0) {
    	$('.tabs li a').corner("top 15px");
	}
	
	if ($('.dashboardTabs li a').length > 0) { 
    	$('.dashboardTabs li a').corner("top 15px");
	}
	
	if ($('.tContent').length > 0) {
		$('.tContent').corner("right 15px");
	}
	
	if ($('.tContent').length > 0) {
		$('.tContent').corner("bl 15px");
	}
	
	if ($('.tContentHead').length > 0) {
		$('.tContentHead').corner("tr 15px");
	}
	
	if ($('.tabbedContent.notabs').length > 0) {
		$('.tabbedContent.notabs').corner("tl 15px");
	}
	
	if ($('.notabs .tContent').length > 0) {
		$('.notabs .tContent').corner("tl 15px");
	}
	
	if ($('.notabs .tContentHead').length > 0) {
		$('.notabs .tContentHead').corner("tl 15px");
	}
	
	if ($('.noticeBoardHead').length > 0) {
		$('.noticeBoardHead').corner("top 10px");
	}
	
	if ($('.noticeBoardFoot').length > 0) {
		$('.noticeBoardFoot').corner("bottom 10px");
	}
	
	if ($('.lastrow').length > 0) {
		$('.lastrow').corner("bottom 15px");
	}
	
	if ($('.calendarwrap').length > 0) {
		$('.calendarwrap').corner("bottom 15px");
	}
	
	if ($('.newsfeature').length > 0) {
		$('.newsfeature').corner("bottom 15px");
	}
	
	if ($('.spHead').length > 0) {
		$('.spHead').corner("top 10px");
	}
	
	if ($('.galleryBody').length > 0) {
		$('.galleryBody').corner("10px");
	}
	
	if ($('.spContent').length > 0) {
		$('.spContent').corner("10px");
	}
	
	if ($('.spFoot').length > 0) {
		$('.spFoot').corner("bottom 10px");
	}
	
	if ($('.alert').length > 0) {
    	$('.alert').corner("10px");
	}
	
	if ($('.success').length > 0) {
    	$('.success').corner("10px");
	}
	
	if ($('.error').length > 0) {
    	$('.error').corner("10px");
	}

}

// use swfobject to embed flash
function flashEmbeds() {
	$('.flashHolder').each(function() {
					  id = $(this).attr('id');
					  movie = $(this).find('span.movie').html();
					  width = $(this).find('span.width').html();
					  height = $(this).find('span.height').html();
					  swfobject.embedSWF(movie, id, width, height, "9.0.0", "assets/flash/expressInstall.swf");
					  });	
}

var trackAds = {
	init:function() {
		
		$('div.banner').each(function() {
							id = $(this).attr('id');
							id = id.replace(/banner/, '');
							$(this).find('a').click(function() {
														href = $(this).attr('href');
														url = "http://www.roundtable.9xb.com/ajax/adTracker/"+id+"/?uri="+encodeURIComponent(href);
														
														var contains_http=href.indexOf("http"); //GET VALUE http IN 'HREF' **FOR MOZILLA&&
			
														var contains_domain=href.indexOf(domainName); //GET VALUE domainName **FOR IE**
														
														if(contains_http>-1 && contains_domain==-1) { //DOES CONTAIN AN 'http' OR DOES NOT CONTAIN domainName
															window.open(url,
																		'mywindow',
																		'width=400,height=200,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
														} else {
															window.location = url;	
														}
														
														return false;
													});

						  });
	}
}

function launchSearch () 
{

	$('#headerlinks .search a#toggleSearch').live('click', function () {
		toggleSearch();
		return false;
	});
	
	$('.hackblock').live('click', function () {
		toggleSearch();
		return false;
	});


}

function toggleSearch ()
{
	if ($('.searchwrap').is(':hidden')) {
		$('.searchwrap').removeClass('hidden');														
		$('.search').addClass('active');
		$("#searchfield").focus().select();
	} else {
		$('.searchwrap').addClass('hidden');
		$('.search').removeClass('active');
	}
}

var gallery = {
	default_caption:'Add Caption',
	
	init:function() {
		if ($('ul.galleries').length==0) { return; }
	},
	
	edit_caption:function(id) {
		caption = $('#image_'+id+' span.gallery_caption a').html();	
		html = '<span class="gallery_save">Save</span> <input id="edit_caption_'+id+'" value="'+caption+'" maxlength="50"/>';
		$('#image_'+id+' span.gallery_caption').html(html);	
		
		$('#edit_caption_'+id).blur(function() {
											 gallery.save_caption(id);											 
											 });
		$('#edit_caption_'+id).select();		
	},
	
	save_caption:function(id){
		caption = $('#edit_caption_'+id).val();
		if (caption==gallery.default_caption) { caption = ''; }
		
		html = 'saving...';
		$('#image_'+id+' span.gallery_caption').html(html);	
		
		$.ajax({
			   url:"gallery/caption/"+id+"/",
			   data:{'caption':caption},
			   dataType:"json",
			   success:function(data) { gallery.success(data); },
			   error:function(data) { gallery.error(data); }
			   });

	},
	
	success:function(data) {
		if (data.caption == '') { data.caption = gallery.default_caption; }
		
		html = '<a href="javascript:gallery.edit_caption('+data.id+')">'+data.caption+'</a>';
		$('#image_'+data.id+' span.gallery_caption').html(html);			
	},
	
	error:function(data) {
		alert('Error saving caption');
	}
	
	
}

//Do the effects for the rating starts
function rating() {
	
	if($('.rating').length == 0) return false;
	
	var stars = $('.rating li'); //Get the li elements within the rating list

	var currentRating = $('.rating li a.active');
	
	stars.each(function() { //Loop though each of the star lis
		
		if ($(this).parent().hasClass('no-rating')) return false;
		
		$(this).mouseover(function() { //Listen out for the mouse going over the li
		
			var prev = $(this).prevAll('li'); //Gets all of the previous star lis
			
			var next = $(this).nextAll('li'); //Gets all of the next star lis
			
			prev.each(function() { //For each of the previous stars
						
				$(this).children().addClass('active'); //Add the active class to highlight the star
			
			});
			
			next.each(function() { //For each of the next stars in the list
			
				$(this).children().removeClass('active'); //Remove the active class to de select the star
			
			});
			
			$(this).children().addClass('active');
		
		});
		
		$(this).mouseout(function() { //Listen out for the mouse leaving an li
		
			$(this).siblings().each(function() { //Loop through each of the lis in the list
			
				$(this).children().removeClass('active'); //de-select all of the lis
			
			});
			
			$(this).children().removeClass('active');
			
			currentRating.addClass('active'); //Re-highlight the current rating
		
		});
	
	});
	
	return false;
	
}

function disableCP ()
{

	var fields = [];
	var inputs = document.getElementsByTagName("input");
	var textareas = document.getElementsByTagName("textarea");

	for (var i = 0; i < inputs.length; i++) {
		fields.push(inputs[i]);
	}

	for (var i = 0; i < textareas.length; i++) {
		fields.push(textareas[i]);
	}

	for (var i = 0; i < fields.length; i++) {
		
		var field = fields[i];
		
		if (field.getAttribute('class') == 'no-copy') {
	
			if (typeof field.onpaste == "function") {
				var oninput = field.oninput;
	
				field.oninput = function () {
					if (typeof oninput == "function") {
						oninput.apply(this, arguments);
					}
	
					if (typeof this.previousValue == "undefined") {
						this.previousValue = this.value;
					}
	
					var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
	
					if (pasted && !this.onpaste.apply(this, arguments)) {
						this.value = this.previousValue;
					}
	
					this.previousValue = this.value;
				};
	
				if (field.addEventListener) {
					field.addEventListener("input", field.oninput, false);
				} else if (field.attachEvent) {
					field.attachEvent("oninput", field.oninput);
				}
			}
		
		}
		
	}


}

