//common to all popups - rewrite all abc and other stuff to match with this
function popup(url,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	
	childWindow=open(url, "", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+w+",height="+h+",left ="+LeftPosition+",top="+TopPosition+"");
	if (childWindow.opener == null) childWindow.opener = self;	
}

//used only for player so we can change player vars later without having to change the player itself
function popupplayer(url){
	w=980;
	h=510;
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	childWindow=open(url, "", "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width="+w+",height="+h+",left ="+LeftPosition+",top="+TopPosition+"");
	if (childWindow.opener == null) childWindow.opener = self;	
}

//used only for player so we can change player vars later without having to change the player itself
function playVideo(video_id,zone_id){
	w=980;
	h=596;
	url = "/player/?video_id="+video_id+"&zone="+zone_id+"&categories="+zone_id;
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	childWindow = open(url, "","toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width="+w+",height="+h+",left ="+LeftPosition+",top="+TopPosition+"");
	if (childWindow.opener == null) childWindow.opener = self;	
}


function popupUpload(type,id){
	w = 500;
	h= 750;
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	if(type == 'video'){
	childWindow=open("/widgets/videogallery/form.cfm?gallery_id="+id, "", "toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+w+",height="+h+",left ="+LeftPosition+",top="+TopPosition+"");
	}
	else{
		childWindow=open("/widgets/imagegallery/form.cfm?gallery_id="+id, "", "toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+w+",height="+h+",left ="+LeftPosition+",top="+TopPosition+"");
	}
	if (childWindow.opener == null) childWindow.opener = self;	
}

//check to see if any radio button is checked in a family
function chkRadio(btn,msg) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1){
		return true;
	}else{ 
		alert(msg);
		btn[0].focus();
		return false;
	}
}


//prototype function to trim strings
String.prototype.trim = function() {
	return this.replace(/^\s*|\s*$/g, "");
}

//alert and focus in validations
function chkEmpty(el,msg){
	if(el.value.trim() == ""){
		message(el,msg);
		return false;
	}else{
		el.className = 'frmreq';
		return true;
	}
}

function chkSelect(el,msg) {
	if (el.options[el.selectedIndex].value=="") {
		message(el,msg);
		return false;	
	} else {
		el.className =  'text';
		return true;
	}
}

function chkMultiSelect(el,msg) {
	var i=0
	var isSelected=false
	for (i=0;i<el.options.length;i++) {
		if (el.options[i].selected == true && el.options[i].value != "" ) {
			isSelected=true;
			break;
		}
	}
	if (!isSelected) {
		message(el,msg);
		return false;
	} else {
		el.clasName = 'text';
		return true;
	}
}

//alert msg which is called by chkEmpty
function message(el,msg){
	alert(msg);
	if(el.type != 'radio' && el.type != 'checkbox')
		el.className = 'required';
	el.focus();
	return;
}

function form_validate(id,verify){
	var f = document.getElementById(id);
	var els = f.elements;
	for(i=0;i<els.length;i++){
		if($(els[i]).is('.required') || $(els[i]).is('.frmreq')){
			switch(els[i].type){
				case "text":
					if(chkEmpty(els[i],'This field is required and cannot be empty') == false) return false;
					break;
				case "textarea":
					if(chkEmpty(els[i],'This field is required and cannot be empty') == false) return false;
					break;
				case "select":
					if(chkEmpty(els[i],'This field is required and cannot be empty') == false) return false;
					break;
				case "select-multiple":
					if(chkEmpty(els[i],'This field is required and cannot be empty') == false) return false;
					break;
				case "radio":
					if(chkRadio(f.elements[els[i].name],'This field is required. Please select atleast one option') == false) return false;
					break;
				case "checkbox":
					if(chkRadio(f.elements[els[i].name],'This field is required. Please select atleast one option') == false) return false;
					break;
			}
		}
		/*
		else{
			if($(els[i]).is('.captcha')){
				if(els[i].value != verify){
					alert('The verification text you entered does not match the image');	
					return false;
				}
			}
		}
		*/
	}
	return true;
}

function show_form_response(id, response){
	document.getElementById(id).innerHTML = response; 
}


function comments_selectTab(tab, guid, value){
	if(tab == 'new'){
		$('#comments_form_'+guid+' ul li a').removeClass('selected');
		$('#new_'+guid).addClass('selected');
		$('#register_'+guid).show();
		$('#login_'+guid).hide();
		$('#forgot_password_'+guid).hide();
		$('#comments_form_'+guid).find('input[name=subaction]').each(function(){ $(this).attr('value',value); });
	}
	else if(tab == 'forgot'){ 
		$('#comments_form_'+guid+' ul li a').removeClass('selected');
		$('#forgot_'+guid).addClass('selected');
		$('#forgot_password_'+guid).show();
		$('#login_'+guid).hide();
		$('#register_'+guid).hide();
		$('#comments_form_'+guid).find('input[name=subaction]').each(function(){ $(this).attr('value',value); });
	}
	else{ 
		$('#comments_form_'+guid+' ul li a').removeClass('selected');
		$('#registered_'+guid).addClass('selected');
		$('#login_'+guid).show();
		$('#register_'+guid).hide();
		$('#forgot_password_'+guid).hide();
		$('#comments_form_'+guid).find('input[name=subaction]').each(function(){ $(this).attr('value',value); });
	}
}
	
function comments_submit(guid){
	//Validate comments.
	if($('#comments_form_'+guid+ ' input[name=subaction]').attr('value') == 'register'){
		if($('#comments_form_'+guid+ ' input[name=authorName]').attr('value').length == 0){
			$('#comments_form_'+guid+ ' input[name=authorName]').focus();
			$('#message_'+guid).addClass('error').removeClass('success').html('<strong>Error:</strong> You must enter a Name.').show();
			return false;
		}
		var ereg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var address = $('#comments_form_'+guid+ ' input[name=authorEmail]').attr('value');
		if(address.length == 0 || ereg.test(address) == false){
			$('#comments_form_'+guid+ ' input[name=authorEmail]').focus();
			$('#message_'+guid).addClass('error').removeClass('success').html('<strong>Error:</strong> You must a valid E-mail Address.').show();
			return false;
		}
	}
	else if($('#comments_form_'+guid+ ' input[name=subaction]').attr('value') == 'login'){
		if($('#comments_form_'+guid+ ' input[name=authorLogin]').attr('value').length == 0){
			$('#comments_form_'+guid+ ' input[name=authorLogin]').focus();
			$('#message_'+guid).addClass('error').removeClass('success').html('<strong>Error:</strong> Please enter the E-mail Address your registered with to login.').show();
			return false;
		}
	}
	
	if($('#comments_form_'+guid+ ' textarea[name=comments]').attr('value').length == 0){
		$('#comments_form_'+guid+ ' textarea[name=comments]').focus();
		$('#message_'+guid).addClass('error').removeClass('success').html('<strong>Error:</strong> You forgot to enter comments.').show();
		return false;
	}
	
	$('#comments_form_'+guid+' button[name=submitComment]').hide();
	values = $('#comments_form_'+guid).serializeArray();
	$.post('/widgets/comments/ajax.cfm',values,function(data){
		if(data.error){
			$('#message_'+guid).addClass('error').removeClass('success').html(data.message).show();
			$('#comments_form_'+guid+' button[name=submitComment]').show();
		}
		else{
			$('#message_'+guid).addClass('success').removeClass('error').html(data.message).show();
		}
	},'json');
}

function comments_setReplyTo(name, cguid, fguid){
	$('#replyTo_'+fguid).html('<strong>Reply To:</strong> '+name+' <span>[<a href="#comments_'+fguid+'" onclick="comments_clearReplyTo(\''+fguid+'\');">clear</a>]</span>');
	$('#replyTo_'+fguid).show();
	
	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: $('#comments_form_'+fguid).offset().top }, 500);

	$('#comments_form_'+fguid).find('input[name=reply_to]').each(function(){ $(this).attr('value',cguid); });
}

function comments_clearReplyTo(guid){
	$('#replyTo_'+guid).hide();
	$('#comments_form_'+guid).find('input[name=reply_to]').each(function(){ $(this).attr('value',''); });
}

function comments_vote(direction,guid){
	$.post('/widgets/comments/ajax.cfm',{ 
		action: 'submitvote'
		,direction: direction
		,guid: guid
	},function(){
		$('#rater_'+guid.replace(/-/g,'')).html('Voted!');
	});
}

function comments_report(guid){
	$.post('/widgets/comments/ajax.cfm',{ 
		action: 'report'
		,guid: guid
	},function(data){
		$('#rater_'+guid.replace(/-/g,'')).html('Reported!');
	},'json');
}

function comments_sendPassword(guid){	
	var ereg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var address = $('#forgot_password_'+guid+ ' input[name=forgotEmail]').attr('value');
	
	if(address.length == 0 || ereg.test(address) == false){
		$('#forgot_password_'+guid+ ' input[name=forgotEmail]').focus();
		$('#message_'+guid).addClass('error').removeClass('success').html('<strong>Error:</strong> You must a valid E-mail Address.').show();
		return false;
	}
	
	$('#forgot_password_'+guid+' button[name=submitComment]').hide();
	$.post('/widgets/comments/ajax.cfm',{ 
		action: 'forgotpassword'
		,email_address: address
		,guid: guid
	},function(data){
		if(data.error){
			$('#message_'+guid).addClass('error').removeClass('success').html(data.message).show();
			$('#forgot_password_'+guid+' button[name=submitComment]').show();
		}
		else{
			$('#message_'+guid).addClass('success').removeClass('error').html(data.message).show();
		}
	},'json');
	
	return false;
}

function searchBy(type){
	if (type == 'site') {
		$('#search_type_site_label').attr('class', 'active');
		$('#search_type_keyword_label').attr('class', '');
		$('#search_type_site').attr('checked', 'checked');
		$('#search_type_keyword').attr('checked', '');
	} else {
		$('#search_type_site_label').attr('class', '');
		$('#search_type_keyword_label').attr('class', 'active');
		$('#search_type_site').attr('checked', '');
		$('#search_type_keyword').attr('checked', 'checked');
	}
	/*$('search_type_site_label').className = (type == 'site') ? 'active' : '';  
	$('search_type_keyword_label').className = (type == 'keyword') ? 'active' : '';  
	$('search_type_site').checked = (type == 'site') ? true : false;  
	$('search_type_keyword').checked = (type == 'keyword') ? true : false;*/
}

/* Media */

$.fn.mediaViewer = function(options){
	var settings = {
		speed: 350,
		easing: '',		
		animActive: {opacity: 1, left: 0},
		animStart: {opacity: 1, left: 250},
		animStartAlt: {opacity: 1, left: -250},
		animEnd: {opacity: 1, left: -250},
		animEndAlt: {opacity: 1, left: 250},
		thumbView: 5,
		tabs: '',
		mouseWheel: false
	};	
	var options = $.extend(settings, options);
	
	return this.each(function(){
		var speed = settings.speed;
		var easing = settings.easing;
		var animActive = settings.animActive;
		var animStart = settings.animStart;	
		var animStartAlt = settings.animStartAlt;
		var animEnd = settings.animEnd;	
		var animEndAlt = settings.animEndAlt;
		var thumbView = settings.thumbView;
		var tabs = settings.tabs;
		var mouseWheel = settings.mouseWheel;
		var last = 0;
		var current = 0;
		var $this = $(this);
		var photos = $(this).find('.media-photos');
		var photos_list = photos.find('li');
		var thumbs = $(this).find('.media-thumbnails');
		var thumbs_list = thumbs.find('li a');
		var captions = $(this).find('.media-captions');
		var captions_list = captions.find('li');
		var count = photos_list.length;
		var prevBtn = $(this).find('.media-thumbnails-nav-prev');
		var nextBtn = $(this).find('.media-thumbnails-nav-next');	
		var thumbWidth = (thumbs_list.length > 0) ? thumbs_list.eq(0).outerWidth() + (thumbs_list.eq(0).css('marginLeft').replace('px', '') - 0) + (thumbs_list.eq(0).css('marginRight').replace('px', '') - 0) : 0;	
		
		init();
		
		// Attach Events
		thumbs_list.click(function(e){
			cycle(thumbs_list.index(this));
			return false;
		});
		
		prevBtn.click(function(e){
			cycle('prev');
			return false;
		});
		
		nextBtn.click(function(e){
			cycle('next');
			return false;
		});
		
		photos.find('.prev').hover(function(e){
			if (current - 1 >= 0){
				$(this).removeClass('inactive');
				$(this).attr('title', 'Previous');
				$(this).click(function(){
					cycle('prev');
				});
			}
		}, function(e){
			$(this).addClass('inactive');
			$(this).attr('title', '');
			$(this).unbind('click');
		});
		
		photos.find('.next').hover(function(e){
			if (current + 1 < count && count > 1){
				$(this).removeClass('inactive');
				$(this).attr('title', 'Next');
				$(this).click(function(){
					cycle('next');
				});
			}
		}, function(e){
			$(this).addClass('inactive');
			$(this).attr('title', '');
			$(this).unbind('click');
		});
		
		photos_list.hover(function(e){
			$(this).find('.caption').stop().animate({top: $(this).find('img').height() - $(this).find('.caption span').outerHeight()}, {duration: speed, easing: easing});
		}, function(e){
			$(this).find('.caption').stop().animate({top: $(this).find('img').height()}, {duration: speed, easing: easing});
		});
		
		photos.bind('mousewheel', function(event, delta){
			if (mouseWheel){
				var val = (delta < 0) ? current + 1 : current - 1;
				cycle(val);			
				return false;
			}
		});
		
		// Tabs
		if (tabs != ''){
			$(tabs + ' li a').click(function(){
				var index = $(this).parent().parent().find('li').index($(this).parent());
				var tabs = $(this).parent().parent();
				var panel = $(this).parent().parent().parent().parent().find('.media-tabs-panel');
				
				tabs.find('li').attr('class', '');
				tabs.find('li').eq(index).attr('class', 'active');
				panel.find('li.media').css('display', 'none');
				panel.find('li.media').eq(index).css('display', 'block');
				
				init();
				return false;
			});
		}
		
		// Methods		
		function init(){
			var hidden = false;
			if ($this.css('display') == 'none'){
				$this.css('display', 'block');
				hidden = true;
			}
			photos.addClass('loading');			
			if (photos.find('.dir').length === 0){
				photos.append('<span class="dir prev inactive"/>');
				photos.append('<span class="dir next inactive"/>');	
			}
			if (current + 1 < count && count > 1){
				nextBtn.find('a').attr('class', '');
			}
			photos_list.css(animStart);
			photos_list.eq(0).css(animActive);
			photos_list.each(function(e){
				var img = $(this).find('img');
				loadImg(this, img.attr('src'), img.attr('alt'), e);
			});
			if (hidden) $this.css('display', 'none');
		}
		
		function cycle(val){		
			if (val == 'next'){
				if (current + 1 < count) current++;
			} else if (val == 'prev'){
				if (current - 1 >= 0) current--;
			} else {
				var reg=/^\d$/;
				if (reg.test(val) && val >= 0 && val < count) current = val;
			}
			
			if (last == current) return false;
			
			if (current > 0){
				prevBtn.find('a').attr('class', '');
				photos.find('.prev').removeClass('inactive');
			} else {
				prevBtn.find('a').attr('class', 'inactive');
				photos.find('.prev').addClass('inactive');
			}
			if (current < count - 1){
				nextBtn.find('a').attr('class', '');
				photos.find('.next').removeClass('inactive');
			} else {
				nextBtn.find('a').attr('class', 'inactive');
				photos.find('.next').addClass('inactive');
			}
			
			if (current > last){
				photos_list.eq(current).css(animStart).stop().animate(animActive, {duration: speed, easing: easing});
				photos_list.eq(last).stop().animate(animEnd, {duration: speed, easing: easing});
			} else {
				photos_list.eq(current).css(animStartAlt).stop().animate(animActive, {duration: speed, easing: easing});
				photos_list.eq(last).stop().animate(animEndAlt, {duration: speed, easing: easing});
			}
			
			// Resize height for content
			photos.stop().animate({height: photos_list.eq(current).height()}, {duration: speed, easing: easing});
			
			if (count > thumbView){
				if ((current + 1) > Math.floor(thumbView / 2)){					
					var offset = -(thumbWidth * ((current + 1) - Math.floor(thumbView / 2) - 1));																						   
					if (Math.abs(offset) >= (thumbWidth * count) - (Math.floor(thumbView / 2) * thumbWidth * 2)) {						
						offset = -((count * thumbWidth) - ((Math.floor(thumbView / 2) * thumbWidth * 2) + thumbWidth));
					}
					thumbs.find('ul').stop().animate({left: offset}, {duration: speed, easing: easing});
				} else {
					thumbs.find('ul').stop().animate({left: 0}, {duration: speed, easing: easing});
				}
			}
			// Carousel effect
			//thumbs.find('ul').animate({left: -(current * 250)}, {duration: speed, easing: easing});
			
			captions_list.attr('class', '');
			captions_list.eq(current).attr('class', 'active');
			
			thumbs_list.parent().attr('class', '');
			thumbs_list.eq(current).parent().attr('class', 'active');
			
			last = current;
			
			return false;
		}
		
		function loadImg(el, src, alt, pos){
			if ($(el).find('img').length > 0){
				$(el).find('img').remove();
				$(el).find('.caption').css('display', 'none');
				
				var img = new Image();			
				$(img).load(function(){
					$(this).css('display', 'none');				
					photos.removeClass('loading');
					if ($(el).find('a').length > 0){
						$(el).find('a').prepend(this);
					} else {
						$(el).prepend(this);
					}				
					if ($(el).find('.caption span').length < 1) $(el).find('.caption').wrapInner('<span/>');
					$(el).find('.caption').css({top: $(this).height()});
					$(el).find('.caption').css('display', 'block');
					if (pos === 0) photos.css('height', $(this).height());
					$(this).fadeIn();
				}).error(function(){
					// error here
				}).attr('src', src).attr('alt', alt);
			}
		}
	});
};


/* Common items to go in document ready */
$(document).ready(function(){
						   
	//Used to toggle captions on news images
	$('div.credit a').click(function(){
		$(this).parent().parent().find('.caption').toggle();
		
		if ($(this).html() != 'Hide caption') {
			$(this).html('Hide caption');
		} else {
			$(this).html('Show caption <span>&darr;</span>');
		}
		
		return false;
	});
	
});