var speed_timeout=4000;
var speed_transition=1000;
var arrow_wait=2000;
var this_carousel=0;

jQuery(document).ready(function(){
    jQuery('.smartedit').each(function(){
        if(jQuery(this).attr('alt')=='')
            jQuery(this).attr('alt',jQuery(this).val());
    });
    jQuery('.smartedit').focus(function(){
        if(jQuery(this).val()==jQuery(this).attr('alt'))
            jQuery(this).val('');
        jQuery(this).addClass('smarteditactive');
    });
    jQuery('.smartedit').blur(function(){
        if(jQuery(this).val()==''){
            jQuery(this).val(jQuery(this).attr('alt'));
            jQuery(this).removeClass('smarteditactive');
        }
    });      
    jQuery('.smartedit.datepicker').change(function(){
        if(jQuery(this).val()!=jQuery(this).attr('alt') && !jQuery(this).hasClass('smarteditactive')){
            jQuery(this).addClass('smarteditactive');
        }
    });      
    
    jQuery('#topnav li.parent').hover(function(){
        jQuery(this).addClass('hover');
    },function(){
        jQuery(this).removeClass('hover');
    });
    
    jQuery('.boxcontent').each(function(){
        var box=jQuery(this);
        box.find('p').each(function(){
            var para=jQuery(this);
            if(para.find('img').length==0)
                para.addClass('padme');
        });
        box.find('a').each(function(){
            var link=jQuery(this);
            var container=jQuery(this).parent();
            var searchstring=container.html();
            var position=strpos(searchstring,link.text())+strlen(link.text())+strlen('</a>');
            var nextchar = substr(searchstring,position,1);
            
            if(nextchar=='.'){
                link.text(link.text()+'.');
                var searchstring=container.html();
                var position=strpos(searchstring,link.text())+strlen(link.text())+strlen('</a>');                                
                var newhtml='';
                if(substr(searchstring,position+1))
                    newhtml=substr(searchstring,0,position)+substr(searchstring,position+1);
                else newhtml=substr(searchstring,0,position);
                container.html(newhtml);
            }
        });
        box.find('a').each(function(){
            if(jQuery(this).text()!='') jQuery(this).append(' <img src="'+BASE+'img/bg-link-tri.gif" />');
        });        
        box.find('.padme').addClass('last');
    });
    
    jQuery('.story').each(function(){
        var story=jQuery(this);
        story.find('h3 a:last').html(story.find('h3 a:last').html()+' <img src="'+BASE+'img/story-tri.gif" />');
    });    

    jQuery('#right').prepend('<img src="'+BASE+'img/roundtop.gif" class="roundtop"/>')
    jQuery('#right').prepend('<img src="'+BASE+'img/roundbottom.gif" class="roundbottom"/>')
    jQuery('#right').prepend('<a href="javascript:void(0)" class="enlarge">Enlarge</a>')
    jQuery('#right').prepend('<a href="javascript:void(0)" class="reduce">Reduce</a>')
    
    jQuery('#content table tr:odd').addClass('odd');
    
    jQuery('.specialfield').hide();
    
    jQuery('input[type=hidden]').hide();     
        
    var clicks = 0;
    var fontsize = 78; 
    jQuery('.enlarge').click(function() { 
        if (clicks < 4) {
            fontsize+=5;
            jQuery('html').css({'font-size': fontsize+'%'});
            clicks++;
        }
        return false; 
    });
 
    jQuery('.reduce').click(function() { 
        if (clicks > -4) {
            fontsize-=5;
            jQuery('html').css({'font-size': fontsize+'%'});
            clicks--;
        }
        return false;
    }); 
    
    window.setInterval(function(){
        jQuery('#tweets').animate({
            top:'-18px'
        },1000,function(){
            jQuery('#tweets li:first').appendTo('#tweets');
            jQuery('#tweets').css('top','10px');
        });        
    },5000);
    
    jQuery('#left').append('&nbsp;');
    jQuery('#buddy').append('&nbsp;');
    
    Cufon.replace('.hoverbox' ,{ fontFamily: 'NeoSans' });
    Cufon.replace('#content h1' ,{ fontFamily: 'NeoSans' });
    Cufon.replace('#hero .hero-arrow a' ,{ fontFamily: 'NeoSans Light' });
    Cufon.replace('#content h2' ,{ fontFamily: 'NeoSans Light' });
    Cufon.replace('.story h2' ,{ fontFamily: 'NeoSans Light' });    
    Cufon.replace('.story h3' ,{ fontFamily: 'NeoSans Light' });    
    
    jQuery('#content h1, #content h2, .story h2, .hoverbox').css('visibility','visible');

});   

jQuery(window).load(function(){
    if(jQuery('#hero').length){                
        var carousels=jQuery('#hero > .carousel').length;                
        
        jQuery('.carousel').each(function(count){
            var carousel = jQuery(this);
            carousel.css('z-index',carousels-count);
            if(count!=0) carousel.hide();            
        });

        jQuery('#hero .hoverbox').click(function(){
            var story=jQuery(this).attr('rel');
            jQuery('#story'+story).fadeIn(speed_transition);
        });
        
        jQuery('#hero .story .closestory').click(function(){
            var story=jQuery(this).attr('rel');
            jQuery('#story'+story).fadeOut(speed_transition);
        });        
        
        jQuery('#hero .story .hero-arrow a').click(function(){
            var carouselno=jQuery(this).attr('rel');
            jQuery('#hero'+carouselno).hide();
            move_on(carouselno,carousels,'#story'+carouselno);
        });
        
        jQuery('#hero').css('visibility','visible');
        run_carousel(0,carousels);
    }   
    
    jQuery('.datepicker').datepicker({dateFormat:'dd/mm/yy', changeYear:true, changeMonth: true});
});

function run_carousel(carouselno,carousels){
    this_carousel=carouselno;
    jQuery('#hero'+carouselno).cycle('destroy').cycle({
                fx: 'fade',
                nowrap: true,
                timeout: speed_timeout,
                speed: speed_transition,
                startingSlide: 0,
                after: onAfter
    });

    jQuery('#hero'+carouselno+' .hero-arrow a').click(function(){
        move_on(carouselno,carousels,'#hero'+carouselno);
    });    
}

function onAfter(curr, next, opts) {
    var index = opts.currSlide;
    if(index==2){
        window.setTimeout(function(){
            jQuery('.hero-arrow[rel='+this_carousel+']').fadeIn(speed_transition);
        },arrow_wait);
    }
}

function move_on(carouselno,carousels,tofade){
    var nextcarousel=((carouselno+1)%carousels);
    var thishero=jQuery('#hero'+carouselno);
    var nexthero=jQuery('#hero'+nextcarousel);
    var fader=jQuery(tofade);
    
    nexthero.show();                                                                // show the next hero
    fader.fadeOut(speed_transition,function(){ thishero.css('z-index',0); });       // now fade out this hero and put it at the bottom of the pile
    jQuery('.carousel').each(function(){                                            // reassign all heros to move them up 1 in the pile
        var thisindex=jQuery(this).css('z-index');
        jQuery(this).css('z-index',thisindex+1);
    });        
    run_carousel(nextcarousel,carousels);                                           // now run the next carousel    
}

function checksearch(){
    if(jQuery('#searchbox').val()=='' || jQuery('#searchbox').val()=='SEARCH'){
        alert('Please enter a search term and try again');
        return false;
    }
    return true;
}

function checkform(form){
    var no_error=true;
    jQuery(form+' .required').each(function(){
        if(jQuery(this).val()==''){
            alert('Please ensure that all fields marked with a * have been entered into.');
            no_error=false;
        }
    });
    return no_error;
}

function substr (str, start, len) {
    var i = 0, allBMP = true, es = 0, el = 0, se = 0, ret = '';
    str += '';
    var end = str.length;

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
    switch(
        (this.php_js.ini['unicode.semantics'] && 
            this.php_js.ini['unicode.semantics'].local_value.toLowerCase())) {
        case 'on': // Full-blown Unicode including non-Basic-Multilingual-Plane characters
            // strlen()
            for (i=0; i < str.length; i++) {
                if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i+1))) {
                    allBMP = false;
                    break;
                }
            }

            if (!allBMP) {
                if (start < 0) {
                    for (i = end - 1, es = (start += end); i >= es; i--) {
                        if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i-1))) {
                            start--;
                            es--;
                        }
                    }
                }
                else {
                    var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
                    while ((surrogatePairs.exec(str)) != null) {
                        var li = surrogatePairs.lastIndex;
                        if (li - 2 < start) {
                            start++;
                        }
                        else {
                            break;
                        }
                    }
                }

                if (start >= end || start < 0) {
                    return false;
                }
                if (len < 0) {
                    for (i = end - 1, el = (end += len); i >= el; i--) {
                        if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i-1))) {
                            end--;
                            el--;
                        }
                    }
                    if (start > end) {
                        return false;
                    }
                    return str.slice(start, end);
                }
                else {
                    se = start + len;
                    for (i = start; i < se; i++) {
                        ret += str.charAt(i);
                        if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i+1))) {
                            se++; // Go one further, since one of the "characters" is part of a surrogate pair
                        }
                    }
                    return ret;
                }
                break;
            }
            // Fall-through
        case 'off': // assumes there are no non-BMP characters;
                           //    if there may be such characters, then it is best to turn it on (critical in true XHTML/XML)
        default:
            if (start < 0) {
                start += end;
            }
            end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
            // PHP returns false if start does not fall within the string.
            // PHP returns false if the calculated end comes before the calculated start.
            // PHP returns an empty string if start and end are the same.
            // Otherwise, PHP returns the portion of the string from start to end.
            return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
    }
    return undefined; // Please Netbeans
}
function strpos (haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
function strlen (string) {
    var str = string+'';
    var i = 0, chr = '', lgth = 0;

    if (!this.php_js || !this.php_js.ini || !this.php_js.ini['unicode.semantics'] ||
            this.php_js.ini['unicode.semantics'].local_value.toLowerCase() !== 'on') {
        return string.length;
    }

    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };

    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}

