$(document).ready(function() {
    $('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
	/*$('a[href^="http://emyt.co.uk"]').click(function(){
		var wh = $(window).height();
		var ww = $(window).width();
		var h = Math.round(wh / 0.10);
		var w = Math.round(ww / 0.10);
		var ot = Math.round((wh - h) / 2);
		var ol = Math.round((ww - w) / 2);
		window.open($(this).attr('href'),'','top='+ot+', left='+ol+', width='+w+', height='+h);
		return false;
	});*/
    
    if ($('.left','#main').css('border-right-width') == '1px' && $('.left','#main').css('border-right-color') != "rgb(255, 255, 255)") {
        $('.left','#main').height($('.right','#main').height()-5);
    }
    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        //$(':input[type=text],:input[type=password]', 'form.nice').each(function(){
            //$(this).width(400);
        //});
    }
  if ($('#equity').length) {
    $('#equity').clearingInput({text: 'None, Fully Paid etc'});
    $('#vocal_range').clearingInput({text: 'Your Vocal Range, such as Soprano, Tenor, Baritone etc'});
    $('#training').clearingInput({text: 'Acting school...'});
    $('#film').clearingInput({text: 'Any film experience you have...'});
    $('#television').clearingInput({text: 'Any television experience you have...'});
    $('#theatre').clearingInput({text: 'Any theatre experience you have...'});
    $('#theatre_in_education').clearingInput({text: 'Theatre educational experience...'});
    $('#accents').clearingInput({text: 'Any regional accents you can speak. Lincolnshire, south london, klingon etc...'});
    $('#other_skills').clearingInput({text: 'Any other skills you feel make you stand out from the crowd. Cage Fighting, backwards running, finger skating etc...'});
  }
  
    //$('#admin').hide();
    $('.adminclickleft,.adminclickright').each(function() {
        $(this).click(function() {
            toggleAdminClick();
            $('#admin').slideToggle();
            return false;
        });
    });
    
    toggleAdminClick = function() {
        $('.adminclickleft,.adminclickright').each(function() {
            var img = $(this).children().get(0);
            if ($('#admin').is(':hidden')) { $(img).attr('src','/images/icon-up.png'); }
            else {  $(img).attr('src','/images/icon-down.png'); }
        });
    }
    
    
    if ($('#metachanger')) {
        var metadata = '';
        var id = $('#metalink').attr('rel');
        $('#metadiv').hide();
        $('#metalink').click(function(){
            $('#metadiv').slideToggle(500);
            
            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'title' },function(data) {
                //$("form.metaform input[name='title']").val(data);
                $("#mc-title").val(data);
            });
            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'headline' },function(data) {
                //$("form.metaform input[name='desc']").val(data);
                $("#mc-desc").val(data);
            });
            
            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'keywords' },function(data) {
                //$("form.metaform input[name='keywords']").val(data);
                $("#mc-keywords").val(data);
            });
            
            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'weight' },function(data) {
                //$("form.metaform input[name='weight']").val(data);
                $("#mc-weight").val(data);
            });
            
            return false;
        });
        
        $('form#metaform').submit(function() {
            var inputs = [];
            $(':input', this).each(function() {
                inputs.push(this.name + '=' + escape(this.value));
            });
            $('#metadiv').slideUp('fast');
             $.ajax({
                type: "POST",
                url: this.action,
                data: inputs.join('&'),
                beforeSend: function(){$("#loading").slideDown("fast");}, //show loading just when link is clicked 
                complete: function(){ $("#loading").slideUp("fast");}, //stop showing loading when the process is complete 
                success: function(html){ //so, if data is retrieved, store it in html 
                    $("#metadiv").show("slow"); //animation
                    $('#metalog').slideDown('fast');
                    $("#metalog").html("<h2>Meta Log</h2><div style='clear:both'></div>"+html); //show the h
                    setTimeout(function(){
                        $('#metalog').slideUp('slow');
                    }, 5000);
                }
            });
            return false;
        });
    } // metachanger
    
    if ($('#urlalert')) {
      
      $('#name').keyup(function() {
         value = $('#name').val();
         myregex = new RegExp(/\s+/ig);
         value = value.replace(myregex,'-'); // spaces to dash
         myregex = new RegExp(/[^a-zA-Z_0-9\-]/ig); // strip everything else
         myval = value.replace(myregex,'');
         $('#url').val(myval);
      });
      $('#url').keyup(function() {
         value = $(this).val();
         if (value.match(/[^a-zA-Z_0-9\-]/)) {
            myregex = new RegExp(/\s+/ig);
            value = value.replace(myregex,'-'); // spaces to dash
            myregex = new RegExp(/[^a-zA-Z_0-9\-]/ig); // strip everything else
            myval = value.replace(myregex,'');
            $('#url').val(myval);
            $('#urlalert').stop().fadeIn('fast').shake(4,2,125)
             .animate({opacity: 1.0}, 1000)
             .fadeOut('fast');
         }
      });
   }
});

/*******************************************************************************
 *  Misc functions
 ******************************************************************************/
jQuery.fn.shake = function(intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {
   this.each(function() {
      $(this).css({position:"relative"});
      for (var x=1; x<=intShakes; x++) {
         $(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
         .animate({left:intDistance}, ((intDuration/intShakes)/2))
         .animate({left:0}, (((intDuration/intShakes)/4)));
      }
   });
   return this;
};


/*******************************************************************************
 *  Preloading
 ******************************************************************************/
var Preload = {
    load: function(trigger, handlers) {
        if( (typeof trigger).toLowerCase() == 'string' ){
            src = trigger;
        }else{
            src = $(trigger).attr('href');
            try{
                opts = eval( '({' + $(trigger).attr('rel') + '})' );
            }catch(e){}
        }
        //test if it is an image, otherwise, use ajax
        if( src.match(/.jpg$|.jpeg$|.png$|.gif$|.bmp$|.tif$|.tiff$|.gi$/i) ){
            var img = new Image(); 
            if( handlers ){
                if( handlers.loaded && typeof handlers.loaded == 'function' ){
                    img.onload = function(){							
                        response = { 
                            width: img.width,
                            height: img.height,
                            obj: $('<img>').attr('src',img.src)
                        };
                        handlers.loaded( response );
                    };
                }
                if( handlers.loaded && typeof handlers.error == 'function' ){
                    img.onerror = function( err ){
                        handlers.error( err );
                    }
                }
            }
            img.src = src;
        }else if( src.match(/.swf$|.flv$|.SWF$|.FLV$/i) ){
            if( $.fn.flash ){
                if( handlers ){
                    if( handlers.loaded && typeof handlers.loaded == 'function' ){
                    // todo: code flash handling
                    }
                }				
            }
        }else{
            $.get(
                src,
                function( html ){
                    if( handlers ){
                        if( handlers.loaded && typeof handlers.loaded == 'function' ){							
                            var content = $('<div>').html( html );
                            response = { 
                                width: parseInt(content.children(0).css('width')),
                                height: parseInt(content.children(0).css('height')),
                                obj: content,
                                data: html
                            };
                            handlers.loaded( response );
                        }
                    }
                }
            );
        }
    }
};

/* 	gaTracker 1.0.1: jQuery Google Analytics Integration 
	A quicker, automated way to embed Google Analytics.
	(c)2007 Jason Huck/Core Five Creative
	
	* BETA Support for new Analytics API (ga.js) by Jamie Thompson - http://jamazon.co.uk
	* Requires jQuery 1.2.x or higher (for cross-domain $.getScript)
	* TODO: more testing, delay after $.getScript for Safari
	
	Usage:
	Only a tracking code is required:
	$.gaTracker('UA-XXXXX-XX');

	...but other options can be specified:
	$.gaTracker(
		'UA-XXXXX-XX',
		{
			external:	'/external/',
			mailto:		'/mailto/',
			download:	'/downloads/',
			extensions:	[
				'pdf','doc','xls','csv','jpg','gif', 'mp3',
				'swf','txt','ppt','zip','gz','dmg','xml'		
			]
		}
	);

*/

(function($) {
	$.gaTracker = function(code, opts) {
		opts = jQuery.extend({
			external: '/external/',
			mailto: '/mailtos/',
			download: '/downloads',
			extensions: ['pdf', 'doc', 'xls', 'csv', 'mp3', 'swf', 'txt', 'ppt', 'zip', 'gz', 'dmg', 'xml', 'js']
		},
		opts);

		// Returns the given URL prefixed if it is:
		//		a) a link to an external site
		//		b) a mailto link
		//		c) a downloadable file
		// ...otherwise returns an empty string.
		function decorateLink(u) {
			var trackingURL = '';

			if (u.indexOf('://') == -1 && u.indexOf('mailto:') != 0) {
				// no protocol or mailto - internal link - check extension
				var ext = u.split('.')[u.split('.').length - 1];
				var exts = opts.extensions;

				for (i = 0; i < exts.length; i++) {
					if (ext == exts[i]) {
						trackingURL = opts.download + u;
						break;
					}
				}
			} else {
				if (u.indexOf('mailto:') == 0) {
					// mailto link - decorate
					trackingURL = opts.mailto + u.substring(7);
				} else {
					// complete URL - check domain
					var regex = /([^:\/]+)*(?::\/\/)*([^:\/]+)(:[0-9]+)*\/?/i;
					var linkparts = regex.exec(u);
					var urlparts = regex.exec(location.href);
                    if (linkparts[2] != urlparts[2]) trackingURL = opts.external + urlparts[2];
					//if (linkparts[2] != urlparts[2]) trackingURL = opts.external + u;
				}
			}

			return trackingURL;
		}

		// add tracking code to the current page
		function addTracking() {
			$.pageTracker = _gat._getTracker(code);
			$.pageTracker._initData();
			$.pageTracker._trackPageview();

			// examine every link in the page
			$('a').each(function() {
				var u = $(this).attr('href');

				if (typeof(u) != 'undefined') {
					var newLink = decorateLink(u);

					// if it needs to be tracked manually,
					// bind a click event to call GA with
					// the decorated/prefixed link
					if (newLink.length) {
						$(this).click(function() {
							$.pageTracker._trackPageview(newLink);
						});
					}
				}
			});
		}

		// include the external GA script in try/catch to play nice
		function initGA() {
			try {
				// determine whether to include the normal or SSL version
				var gaURL = (location.href.indexOf('https') == 0 ? 'https://ssl': 'http://www');
				gaURL += '.google-analytics.com/ga.js';

				// include the script
				$.getScript(gaURL,
				function() {
					addTracking();
				});
			} catch(err) {
				// log any failure
				console.log('Failed to load Google Analytics:' + err);
			}
		}

		initGA();
	}
})(jQuery);