jQuery.noConflict();
if(!window.ArchantMaps){

	ArchantMaps = {};

}

/*
 * Author:		Adam Collison [adam.collison@soak.co.uk]
 * Agency:		Soak Digital Ltd.
 * Client: 		Archant Dialogue
 * Project: 	HOG Europe Gallery
 * Comment:		Main JS

----------------------


Contents:

1. SIFR
2. Generic JS Functions
3. Additional JQuery custom functions


/* 

 * Create global 'ArchantMaps' object - this is the only global object we create.

 * All other functions and objects should be apart of this.

 */





/*--------------------------------------------------------------------------
	SIFR
----------------------------------------------------------------------------*/
//sIFR.debug.ratios({ src: '/assets/swf/stag.swf', selector: 'h1' });
var stag = {
	src: '/assets/swf/stag.swf'
};

sIFR.activate(stag); // From revision 209 and onwards

sIFR.replace(stag, {
	selector: '#events .month h2',
	ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
	tuneHeight: 0,
	wmode: 'transparent',
	thickness:100,
	css: [
		'.sIFR-root { color: #ffffff; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; }',
	]
});
/* REMOVED FROM BELOW: ', #events #events-detail h3' #*/
sIFR.replace(stag, {
	selector: 'h1, #route-data h2,#at-a-glance h2',
	ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
	tuneHeight: 2,
	wmode: 'transparent',
	thickness:100,
	css: [
		'.sIFR-root { color: #333333; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; }',
		'.sIFR-root em { color: #ff6600; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; font-style:normal; }',
		'.sIFR-root a { color: #333333; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; }',
		'.sIFR-root a:hover { color: #333333; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; }'
	]
});

sIFR.replace(stag, {
	selector: '#cal h2',
	ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
	tuneHeight: 4,
	wmode: 'transparent',
	thickness:100,
	css: [
		'.sIFR-root { color: #333333; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; text-align:center; }',
	]
});


/*--------------------------------------------------------------------------
	Generic JS Functions
----------------------------------------------------------------------------*/
jQuery.promo = function() {
	jQuery("#latest-video").jMyCarousel({
		 visible: '3',
		eltByElt: true,
		evtStart: 'mousedown',
		evtStop: 'mouseup'
	});
	jQuery("#latest-photo").jMyCarousel({
		 visible: '3',
		eltByElt: true,
		evtStart: 'mousedown',
		evtStop: 'mouseup'
	});
			
	jQuery('.promo-gallery .actions li.inactive a').animate({opacity:0.5},1);
	jQuery("#latest-video").addClass('inactive');
	
	jQuery('.promo-gallery .actions li a').live('click',function() {
		
		var tag = jQuery(this).attr('rel');
		
		// specific to action links
		jQuery('.promo-gallery .actions li:not(.news) a').fadeTo(1,1);
		jQuery('.promo-gallery .actions li:not(.news)').addClass('inactive');
		jQuery(this).closest('li').removeClass('inactive');
		jQuery('.promo-gallery .actions li.inactive a').fadeTo(1,0.5);
		// specific to action links
		
		
		jQuery('.promo-gallery #latest-promo div').not(jQuery('#'+tag)).fadeOut('slow',function() {
			jQuery('#'+tag).fadeIn('slow');										
		});
		
		return false;
	});
}

jQuery.fn.disabledMessage = function() {
	
	if(jQuery(this).hasClass('login-first'))
	{
		jQuery(this).append('<a href="/log-in/"><label>'+jQuery(this).attr('title')+'</label></a>');
	}
	else
	{
		jQuery(this).append('<label>'+jQuery(this).attr('title')+'</label>');
	}
	jQuery(this).attr('title','');
	jQuery(this).live('mouseover',function() {jQuery(this).find('label').fadeIn('fast');});
	jQuery(this).find('label').live('mouseout',function() {jQuery(this).fadeOut('fast');});
		
}

jQuery.fn.calendarPanel = function() {
	
	jQuery(this).append('<p class="details"><em></em><br /><a href="#none"></a></p>');
	jQuery(this).find('.event a').live('click',function() {
		
		var title;
		if(jQuery(this).attr('title') != '') { title = jQuery(this).attr('title') } else { title = jQuery(this).data('title') };
		var date = jQuery(this).attr('rel');
		var prevMonth= jQuery('.actions .prev a').attr('rel').split('-', 2)[0];
		var currentMonth = Number(prevMonth) + 1;
		var currentYear = date.split(' ', 3)[2];
		var currentDay = date.split(' ', 3)[0];
		if (currentMonth > 12) {
			currentMonth = 1;
			currentYear  = parseInt(currentYear) + 1
		}
		if (currentMonth.toString().length == 1) {
			currentMonth = '0' + currentMonth;
		}
		if (currentDay.toString().length == 1) {
			currentDay = '0' + currentDay;
		}
		var href = 'hog-events-calendar/date/' + currentMonth + '-' + currentYear + '/?selectedDate=' + currentMonth + '-' + currentDay;
		
		if(!jQuery('.details').data('state') || jQuery('.details').data('state') != 'open') {
                    jQuery(this).data('title',title);
                    jQuery('.details').data('state','open');
                    jQuery('.details a').html(title + ' &raquo;');
                    jQuery('.details em').html(date);
                    jQuery('.details a').attr('href',href);
                    jQuery(this).attr('title','');
                    jQuery('.details').slideDown();
		} else {
                    jQuery('.details em, .details a').fadeOut('fast',function() {
                        jQuery('.details').data('state','open');
                        jQuery('.details a').html(title + ' &raquo;');
                        jQuery('.details em').html(date);
                        jQuery('.details a').attr('href',href);
                        jQuery('.details em, .details a').fadeIn();
                    });
		}
		return false;
		
	});
	
	jQuery(this).find('.tour a').live('click',function() {
            var title;
            if(jQuery(this).attr('title') != '') { title = jQuery(this).attr('title') } else { title = jQuery(this).data('title') };
            var date = jQuery(this).attr('rel');
            var prevMonth= jQuery('.actions .prev a').attr('rel').split('-', 2)[0];
            var currentMonth = Number(prevMonth) + 1;
            var currentYear = date.split(' ', 3)[2];
            var currentDay = date.split(' ', 3)[0];
            if (currentMonth > 12) {
                    currentMonth = 1;
                    currentYear  = parseInt(currentYear) + 1
            }
            if (currentMonth.toString().length == 1) {
                    currentMonth = '0' + currentMonth;
            }
            if (currentDay.toString().length == 1) {
                    currentDay = '0' + currentDay;
            }
            //var href = 'date/' + currentMonth + '-' + currentYear + '/?selectedDate=' + currentMonth + '-' + currentDay;
            var href = jQuery(this).attr('href');

            if(!jQuery('.details').data('state') || jQuery('.details').data('state') != 'open') {
                jQuery(this).data('title',title);
                jQuery('.details').data('state','open');
                jQuery('.details a').html(title + ' &raquo;');
                jQuery('.details em').html(date);
                jQuery('.details a').attr('href',href);
                jQuery(this).attr('title','');
                jQuery('.details').slideDown();
            } else {
                jQuery('.details em, .details a').fadeOut('fast',function() {
                    jQuery('.details').data('state','open');
                    jQuery('.details a').html(title + ' &raquo;');
                    jQuery('.details em').html(date);
                    jQuery('.details a').attr('href',href);
                    jQuery('.details em, .details a').fadeIn();
                });
            }
            return false;
	});

        jQuery('#cal').mouseleave(function(event) {
		jQuery('.details').slideUp('fast',function() {
			jQuery('.details').data('state','closed');							   
		});
		 event.stopPropagation();
	});
	
}

/* Preload js rollover images. */
/* ********************************************************************************* */

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++) {
	jQuery('<img>').attr('src', arguments[i]);
  }
}

/* Simulate rollover on form buttons.  Inputs of type="button" must have a rollover image '-on.gif' */
/* ********************************************************************************* */

jQuery.fn.rolloverImage = function() {
	jQuery(this).hover(function(){
		if (!jQuery(this).data('source')) jQuery.data(jQuery(this).get(0), 'source', { original: jQuery(this).attr('src'), file: jQuery(this).attr('src').split(".")[0] });
		jQuery(this).attr('src', jQuery(this).data('source').file + '-on.gif');
	},
	function(){
		jQuery(this).attr('src', jQuery(this).data('source').original);
	});
}

/* Addthis Config */
var addthis_pub="4a12aca440be8b2d"; // Required for addthis button (http://www.addthis.com/)

jQuery.fn.flagger = function() {
	// this = #language-selector ul
	
	jQuery(this).find("a[class!='active'] img").animate({
		opacity:0.4,
		height:"19px",
		width:"26px",
		marginTop:"8px"
	},1000);
	
	jQuery(this).find("li a[class!='active']").live('mouseover',function() {
		jQuery(this).find("img:not(:animated)").animate({
			opacity:1,
			height:"26px",
			width:"33px",
			marginTop:"0px"
		},300);											  
	});
	
	jQuery(this).find("li a[class!='active'] img").live('mouseout',function() {
		jQuery(this).animate({
			opacity:0.4,
			height:"19px",
			width:"26px",
			marginTop:"8px"
		},100);		
	});
	
}


var et;

jQuery.fn.showRelatedEvent = function() {
	
	// this = '#events .month td a'
	// get pos of parent H2 to align popup with
	var pos = jQuery(this).closest('.month').children('h2').position();
	var setHeight = jQuery(this).closest('div').height();
	
	// call the loading animation while AJAX is firing
	jQuery(this).closest('.month').loader();
	
	// get link ID used to get relevent events listing and set the URL for ajax to call
	var eventDate = jQuery(this).attr('rel');
	var toLoad = '/events-ajax/' + eventDate + '/';
	
	// if event-detail DATA is not set or its a new event ID make AJAX call
	if(!jQuery('#events-detail').data('id') || jQuery('#events-detail').data('id') != eventDate)
	{
		if (jQuery.browser.msie) {
			// IE6 refuses to set height
		}
		else {
			jQuery('#events-detail').css('height','inherit');
		}

		// define DATA for next time a click happens
		jQuery('#events-detail').data('id',eventDate);
		
		// slide up the popup (if previously displaying)
		jQuery('#events-detail').slideUp('fast',function() {
			
			// get the event data from server
			jQuery.ajax({
				type: "GET",
				url: toLoad,
				success: function(data){
	
					// on success populate html
					jQuery('#events-detail').html(data);
					if(jQuery('#events-detail').height() < setHeight)
					{
						setHeight = jQuery('#events-detail').height() + (setHeight - jQuery('#events-detail').height()) -44;
					}
					else
					{
						setHeight = jQuery('#events-detail').height();
					}
					// align to top h2
					jQuery('#events-detail').css({'left':pos.left + 'px','top':pos.top + 29 + 'px'/*,'height':setHeight+'px'*/});
					// fire Timeout to stop and load lag
					et = setTimeout(showEventsDetail,500);
					
					// Fix the flag links to point at the new selected date
					jQuery('#language-selector li a').each( function() {
						jQuery(this).attr('href', jQuery(this).attr('href').replace(/&selectedDate=[0-9]{2}-[0-9]{2}/, '') + '&selectedDate=' + eventDate.replace(/^[0-9]{4}-/, ''));
					});
				}
			 });
		
		});
		
	}
	// otherwise just slide event popup down (dont re-call AJAX)
	else
	{
		showEventsDetail();
	}

}

jQuery.fn.loader = function() {

	var pos = jQuery(this).position();
	
	jQuery('#loading').css({'top':pos.top + 48 + 'px','left':pos.left + 'px','height':jQuery(this).height() - 28 + 'px','width':jQuery(this).width() + 'px'});
	jQuery('#loading, #loading img').show();
		
}

jQuery.fn.bindAccordion = function() {
	jQuery(this).accordion({ 
		header: '.feature-heading',
		changestart: function(event, ui) { 
			ui.oldHeader.find('img').show();
			ui.newHeader.find('img').hide();
			jQuery('#events-detail,.feature-content').css({height:'auto'}); 
		},
		change: function(event, ui) { 
			jQuery('.feature-content').css({'overflow':'visible'}); // Fix IE overflow issue
			
			ui.oldHeader.closest('li').addClass('inactive');
			ui.newHeader.closest('li').removeClass('inactive');
			
			jQuery(this).find('h3').fadeTo(1,1);
			jQuery(this).find('li.inactive h3').fadeTo(1,0.4);
			
		}
	})
		
}

jQuery.fn.bindEventsCalendar = function() {
	jQuery(this).click( function() {
		jQuery.get('/events-calendar-ajax/' + jQuery(this).attr('rel') + '/', function(data) {
			jQuery('div#cal').html(data);
			jQuery('.events-calendar .actions a').bindEventsCalendar();
			jQuery('#cal div').calendarPanel();
			sIFR.replace(stag, {
				selector: '#cal h2',
				ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
				tuneHeight: 4,
				wmode: 'transparent',
				thickness:100,
				css: [
					'.sIFR-root { color: #333333; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; text-align:center; }',
				]
			});
		});
		return false;
	});

}

jQuery.fn.bindToursCalendar = function() {
    jQuery(this).click( function() {
            jQuery.get('/tours-calendar-ajax/' + jQuery(this).attr('rel') + '/', function(data) {
                    jQuery('div#cal').html(data);
                    jQuery('.tours-calendar .actions a').bindToursCalendar();
                    jQuery('#cal div').calendarPanel();
                    sIFR.replace(stag, {
                            selector: '#cal h2',
                            ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01],
                            tuneHeight: 4,
                            wmode: 'transparent',
                            thickness:100,
                            css: [
                                    '.sIFR-root { color: #333333; font-size:14px; font-weight:bold; text-decoration:none; text-transform: uppercase; text-align:center; }',
                            ]
                    });
            });
            return false;
    });
}


function showEventsDetail() {
	jQuery('#loading img').hide();
	jQuery('#events-detail li h3').fadeTo(1,1);
	jQuery('#events-detail li.inactive h3').fadeTo(1,0.4);
	jQuery('#events-detail').slideDown('slow');
	var targetOffset = jQuery('#events-detail').offset().top - 100;
	jQuery('html,body').animate({scrollTop: targetOffset}, 1000);
	jQuery('#events-detail ul').bindAccordion();
	clearTimeout(et);
}



jQuery(function(){
				
	jQuery('.thickbox').lightBox();
	
	var ex,ey;
	if(jQuery('#tip').length > 0)
	{
		jQuery('.help-icon').live('click',function(e) {
			jQuery('#tip').css({'left':e.pageX +'px','top': e.pageY - 200 +'px'});				  
			return false;
		});
		jQuery('#tip .close').live('click',function() {
			jQuery('#tip').css({'left':'-9999px','top':'-9999px'});				  
			return false;
		});
	}
	
	jQuery('#language-selector ul').flagger();
	
	// Preload JS-inserted images
	jQuery.preloadImages('/assets/images/admin/btn-login-on.gif');

	// include external js
	jQuery.getScript('http://s7.addthis.com/js/200/addthis_widget.js');
	
	jQuery('p.share a')
	.mouseover(function(){return addthis_open(this, '', '[URL]', '[TITLE]')})
	.mouseout(function(){addthis_close()})
	.click(function(){return addthis_sendto()});

	if (jQuery('#latest-promo').length > 0) jQuery.promo(); // Initiate promo feature where '#latest-promo' is present
	
	jQuery('#gallery-detail .photo .actions ul li.enlarge a').attr('target','_blank');
	jQuery('#page-content .photo .actions ul li.enlarge a').attr('target','_blank');
	jQuery("a[href^='http:']").not("[href*='gallery'], [href*='local.hog.co.uk']").attr('target','_blank');

	jQuery('#gallery-detail .disabled').disabledMessage();
	jQuery('#cal div').calendarPanel();
	
	jQuery('#go').rolloverImage();
	
	// image, video, rotw rating 
	jQuery('.rating').each(function() {
		var rating = jQuery(this).find('span').attr('class');
		jQuery(this).data('rating',rating);
		jQuery(this).find('span a').click( function () {
			var rating = jQuery(this).attr('class').split('-', 2)[1];
			var type = jQuery(this).attr('rel').split('-', 2)[0];
			var id = jQuery(this).attr('rel').split('-', 2)[1];
			jQuery.get( '/rate-' + type + '/' + id + '/' + rating + '/',
				function(data) {
					jQuery('p.rating').replaceWith(data);
				}
			 );
			 return false;
		});
	});
	
	jQuery('.rating a').hover(function() {
		var newClass = jQuery(this).attr('class');
		jQuery('.rating span').attr('class',newClass);	
	});
	
	jQuery('.rating').bind('mouseleave',function(e){
		var newClass = jQuery(this).data('rating');
		jQuery(this).find('span').attr('class',newClass);										
	});
	
	// Detail page - email form display toggle
	jQuery('.user-comments .leave-comment').not('.open').hide();
	
	jQuery('.user-comments .actions a').click(function() {
		if(!jQuery(this).data('state') || jQuery(this).data('state') == 'hidden')
		{
			jQuery('.user-comments .success').slideUp('fast',function() {});
			jQuery('.user-comments .leave-comment').slideDown('normal');
			if (jQuery(this).hasClass('btn-leave-comment')) {
				jQuery(this).removeClass().addClass('btn-cancel-leave-comment');
			}
			jQuery(this).data('state','showing');
		}
		else
		{
			jQuery('.user-comments .leave-comment').slideUp();
			if (jQuery(this).hasClass('btn-cancel-leave-comment')) {
				jQuery(this).removeClass().addClass('btn-leave-comment');
			}
			jQuery(this).data('state','hidden');
		}
		jQuery(this).blur();
		return false;
	});
		
	//hover states on the static widgets
	jQuery('#dialog_link, ul#icons li').hover(
		function() { jQuery(this).addClass('ui-state-hover'); }, 
		function() { jQuery(this).removeClass('ui-state-hover'); }
	);
	
	// used for event timeout
	// events calendar click to view event function
	
	if(jQuery('#events').length > 0)
	{
		jQuery('#events .month td a').live('click',function() {
			jQuery(this).showRelatedEvent();
			return false;
		});
		
		if(jQuery('#events .month td.active a').length > 0)
		{
			jQuery('#events .month td.active a').showRelatedEvent(1);
		}
	}
	
	
	
	jQuery('#events-detail .close').live('click',function() {
		jQuery('#loading').hide();
		jQuery('#events-detail').slideUp();
		// Fix the flag links to point at an empty selected date
		jQuery('#language-selector li a').each( function() {
			jQuery(this).attr('href', jQuery(this).attr('href').replace(/&selectedDate=[0-9]{2}-[0-9]{2}jQuery/, ''));
		});
		return false;
	});
	
	jQuery('.events-calendar .actions a').bindEventsCalendar();

        jQuery('.tours-calendar .actions a').bindToursCalendar();
	
	jQuery('.latest-gallery .summary ul a').click( function() {
		jQuery('.latest-gallery .summary ul li.selected').removeClass('selected');
		jQuery(this).parent().addClass('selected');
		jQuery.get('/latest-gallery-ajax/' + jQuery(this).attr('rel') + '/', function(data) {
			jQuery('.latest-gallery .gallery').fadeOut();
			setTimeout( function() {
				jQuery('.latest-gallery .gallery').html(data).fadeIn();
			}, 800);
		});
		return false;
	});
	
    newsitems = jQuery("#ticker li").hide().size();
    jQuery("#ticker li").eq(curritem).fadeIn('slow',function() {
    	newstimer = setInterval(ticknews,3000); //time in milliseconds 
	});
	
	jQuery("#ticker li").hover(function() {
		stopScroll();
	},
	function() {
		startScroll();
	});
	
	
});

function startScroll() {
	if (!newstimer) {
		newstimer = setInterval(ticknews,3000); //time in milliseconds 
	}
}

function stopScroll() {
	if (newstimer) {
		clearInterval(newstimer);
		newstimer = false;
	}
}

var newstimer;
var newsitems;
var curritem=0; 

function ticknews() {
	jQuery("#ticker li").eq(curritem).fadeOut('slow',function() {
		curritem = ++curritem%newsitems;
		jQuery("#ticker li").eq(curritem).fadeIn('slow'); 
	});
}

// Allow file upload to be re-selected
function uploadDifferentFile(id) {
    jQuery('#' + id).replaceWith('<input id="' + id + '" name="' + id + '" type="file" />');
}



