/**
 *
 * Look for when the page has finished loading and attach events accordingly
 *
 * @author James Broad
 * @copyright 2007 Time Out Communications Ltd
 *
 */

// IE has an issue with console.log...

try {
	console.log('Console Logging Initiated');
} catch(e) {
	console = {
		log: function() {}
	};
}


/**
 * Submit a form automatically when a checkbox value is changed
 */

function bookmarkPage(){

    var title = document.title;
    var url = window.location.href;

	if ( url.indexOf( "?" ) != -1 ) {
		url = url + "&DCMP=OTC-Bookmark";
	} else {
		url = url + "?DCMP=OTC-Bookmark";
	}

	var ua = navigator.userAgent.toLowerCase();
	var button = ( ua.indexOf( 'mac' ) != -1 ) ? 'Command/Cmd' : 'Ctrl';
	var isSafari = ( ua.indexOf( 'webkit' ) != -1 );
	var isKonq = ( ua.indexOf( 'konqueror' ) != -1 );

	if ( window.home || isSafari ) {
	   alert( "To bookmark Time Out please click 'OK' then press " + button + " + D" );
    } else if( window.external ) { // IE Favorite
    	window.external.AddFavorite( url, title);
    } else if ( window.opera || isKonq ) {
	   alert( "To bookmark Time Out please click 'OK' then press " + button + " + B" );
	}
}

/**
 * Select all checkboxes when a central checkbox value is changed
 */

function selectAll(element){
	var items = $(element).up('form').getElementsBySelector('input[type~=checkbox]');
	element.observe('click', function() {
		if(element.checked === true){
		    items.each(function(item){
    			  item.checked = true;
    		});
		}
		else{
    		items.each(function(item){
    			  item.checked = false;
    		});
		}
	}.bind(element));
}

/**
 *  Swap the image gallery stuff
 */

function tinyImageGallery( el ){

    this.mainImage = $('galleryImage');
    this.mainImageHeight = 219;
    this.mainImageWidth  = 198;
    this.baseImageUri = 'http://www.timeout.com/img/forced';
    this.highlightThumbClass = 'selected';

    /*
     * Get all the thumbnail elements
     *
     * @return Array array of link tags
     */


	this.getThumbnails = function(){

        if( el ){
           return $(el).getElementsBySelector('a');
        }
		return false;
    };

    /*
     * Preload all large images to appear in placeholder
     *
     * @return Boolean
     */

    this.preloadImages = function(){
		var thumbs = this.getThumbnails();
		var tempImages = [];

		for( i = 0; i < thumbs.length; i++ ){
			var thumb = thumbs[i];
			var thumbImage = thumb.down('img');
			var thumbImageId = this.extractImageId( thumbImage.src );

			tempImage = new Image();
			tempImage.src = this.buildMainImageSource(thumbImageId);
			tempImage.alt = '';

			if(tempImage){
				tempImages.push(tempImage);
			}
		}

		if(tempImages){
			return true;
		}

		return false;
    };

    /*
     * Make up the correct image uri
     * using the Time Out image url system
     *
     * @param Integer the id of the image
     * @return String the new uri
     */

	this.buildMainImageSource = function( id ){

        if( id ){
           var source = this.baseImageUri + '/' + id + '/w' + this.mainImageWidth + '/h' + this.mainImageHeight + '/image.jpg';
		   return source;
        }
		return false;
    };

    /*
     *	Set the main image source
     *
     * @param String pass the new source for the main image
     * @return Image the main image object
     */

    this.setMainImage = function( src ){
        if( this.mainImage ){
            this.mainImage.src = src;
            return this.mainImage;
        }
		return false;
    };

    /*
     *  Popup window with image
     *
     *  @param Element thumbnail to popup
     */
    this.popupWindow = function( el ) {

        if(el){
            var parentId = el.up('ul').readAttribute('id');
    		var id 		 = parentId.replace(/^.*\-([\d]*)$/, "$1");
    		var itemSrc  = el.down('img').src;
    		var image_id = itemSrc.replace(/^.*\/(\d+)\/.*$/, "$1");
    		var type_id  = 2;
    		window.open( 'http://www.timeout.com/img/popUp/imageViewer.php?id=' + id + '&image=' + image_id + '&type=' + type_id , 'Extra', "status=1,toolbar=0, menubar=0, location=0, directories=0, resizable=1, scrollbars=0" );
    		window.focus();
			return true;
        }
		return false;
    };

	/*
	 * Set the active thumbnail
	 *
	 * @todo make less tightly coupled with specific elements
	 * @param Element a thumbnail 'li' tag
	 */
	this.setActiveThumb = function( el ){

		if(el){
			var thumbImg = el.down('img');

			// Remove existing items with the selected class attached
			var siblings = el.parentNode.siblings();
			siblings.each(function(items){
				items.getElementsBySelector('img').invoke('removeClassName', 'selected');
			});

			thumbImg.addClassName('selected');
			return true;
		}
		return false;
	};

	/*
	 * Get the id of an image from a uri
	 *
	 * @param String
	 * @return Integer
	 */
	this.extractImageId = function ( str ){

        if(str){
            return str.replace(/^.*\/(\d+)\/.*$/, "$1");
        }
		return false;
    };

    /*
     * Initiate scripts
     */
    this.init = function(){
        //console.log('Main Image ', this.mainImage);
		this.preloadImages();
    };
}









/**
 * Submit a form automatically when a dropdown box value is changed
 */
function autoSubmit(element){
    var items = $(element).getElementsBySelector('select[class=autosubmit], select[class=autoSubmit]');
	items.each(function(item) {
		item.observe('change', function() {
			element.submit();
		}.bind(item));
	});
}

/**
 * Change the page based on the values in a select box
 *
 * Need to ensure that the url value is valid!
 */

function jumpUrl(element){
    var items = $(element).getElementsBySelector('select[class=jumpurl], select[class=jumpUrl]');
	items.each(function(item) {
		item.observe('change', function() {
			window.location.assign(item.value);
		}.bind(item));
	});
}

/**
 * Remember form field values and clear them if need be
 */
function focusText(element){
    // Get all input and text area elements  but ignore anything with the class noMemorize
    var inputElements = $(element).getElementsBySelector('input[type=text]:not([class~=noMemorize]), textarea');
    inputElements.each(function(input) {
        input.observe('focus', function() {
			if($F(this) == this.defaultValue){
			    this.select();
			}
		}.bind(input));
    });
}

/**
 * Attach actions to the page
 */

function init(){

    $$('form').each( function( e ) {
    	autoSubmit( e );
    	jumpUrl( e );
    	focusText( e );
    });

	$$('q').each( function( e ) {
    	if(navigator.appName.search('Explorer') > -1){
    		e.innerHTML = "'" + e.innerHTML + "'";
    	}
    });

    $$('.selectAll').each( function( e ) {
    	selectAll(e);
    });

    $$('.targetBlank').each(function( e ) {
    	e.target = "_blank";
    });

    $$('a[rel~=external]').each(function( e ) {
    	e.target = "_blank";
    });

    $$('.bookmark_page').each(function( e ) {
		try {
			e.observe('click', function(el) {
				bookmarkPage();
			});
		}
		catch ( err ) {
			e.addEvent('click', function(el) {
				bookmarkPage();
			});
		}
    });
}

init();