scrollpos=0;
currentpage=1;

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('active');
    });
    jQuery('.smartedit').blur(function(){
        if(jQuery(this).val()==''){
            jQuery(this).val(jQuery(this).attr('alt'));
            jQuery(this).removeClass('active');
        }
    });

    jQuery('a[class^=clickthrough]').each(function(){
        var link=jQuery(this);
        var id = substr(link.attr('class'),13);
        var text = link.text();
        link.replaceWith('<a href="javascript:void(0)" rel="'+id+'" onclick="load_clickthrough(this); return false;">'+text+'</a>');
    });

    jQuery('.homepage .issues .issue').each(function(i){
        if(((i + 1) % 3) === 0)
            jQuery(this).addClass("colender");
    });

    if(jQuery('#polaroidslider').length){
        window.setInterval(function(){
            scroller();
        },4000);
    }

    if(jQuery('.tableofcontents').length){
        var itemcount=0;
        var pagetype='issues';
        if(jQuery('#wrapper.hiv').length){
            pagetype='hiv';
        }
        else if(jQuery('.stickyback h2.health').length){
            pagetype='sexual-health';
        }
        else if(jQuery('.stickyback h2.relationships').length){
            pagetype='relationships';
        }

        if(pagetype=='hiv'){
            jQuery('.content h3').each(function(){
                itemcount++;
                var heading3 = jQuery(this);
                var text=jQuery(this).text();//.toLowerCase();
                jQuery('.tableofcontents').append('<li rel="'+itemcount+'"><a rel="'+itemcount+'" href="#chapter'+itemcount+'">'+text+'</a></li>');
                jQuery('.tableofcontents li[rel='+itemcount+'] a').click(function(){
                    jQuery(this).parent().siblings().removeClass('current');
                    jQuery(this).parent().addClass('current');
                });

                if(false && 'use hashes to segment pages')
                    heading3.before('<a name="chapter'+itemcount+'"></a>');
            });

            if('use hidden chapter styling'){
                var dump = jQuery('#wrapper .content').html();
                dump = str_replace('<h3>','</div><div class="panel"><h3>',dump);
                dump = str_replace('<H3>','</div><div class="panel"><H3>',dump);
                dump = '<div class="panel">'+dump+'</div>';
                jQuery('#wrapper .content').html(dump);
                jQuery('#wrapper .content .panel:first').remove();
                jQuery('#wrapper .content .panel').each(function(j){
                    jQuery(this).attr('rel','chapter'+j);
                }).hide();
                jQuery('#wrapper .content .panel:first').show();

                jQuery('.tableofcontents li a').click(function(){
                    var chapterto = parseInt(jQuery(this).attr('rel'));
                    jQuery('#wrapper .content .panel').hide();
                    jQuery('#wrapper .content .panel:eq('+(chapterto-1)+')').show();
                    if(jQuery('h2.sticky.hiv').length==0) return false;
                });
            }

            jQuery('.tableofcontents li:first').addClass('current');
        }
        else{
            jQuery('.content h3').each(function(){
                itemcount++;
                var heading3 = jQuery(this);
                var text=jQuery(this).text();//.toLowerCase();
                heading3.before('<a name="item'+itemcount+'"></a>');
                jQuery('.tableofcontents').append('<li rel="'+itemcount+'"><a rel="'+heading3.attr('rel')+'" href="'+BASE+pagetype+'/'+heading3.attr('rel')+'/">'+text+'</a></li>');

                var subcount=0;
                var keepgoing=true;
                jQuery(this).nextAll('h3,h4').each(function(){
                    if(jQuery(this).is('h3')) keepgoing=false;
                    if(keepgoing && jQuery(this).is('h4')){
                        subcount++;
                        var heading4 = jQuery(this);
                        var text=jQuery(this).text();//.toLowerCase();
                        heading4.before('<a name="item'+itemcount+'-'+subcount+'"></a>');
                        if(jQuery('.tableofcontents li[rel='+itemcount+'] ul').length==0)
                            jQuery('.tableofcontents li[rel='+itemcount+']').append('<ul></ul>');
                        jQuery('.tableofcontents li[rel='+itemcount+'] ul').append('<li rel="'+itemcount+'-'+subcount+'"><a href="#item'+itemcount+'-'+subcount+'">'+text+'</a></li>')
                    }
                });
            });

            if(jQuery('.issuepanel h3.active, .relationshippanel h3.active').length==0){
                jQuery('.tableofcontents li:first').addClass('current');
            }
            else{
                var active = jQuery('.issuepanel h3.active, .relationshippanel h3.active').attr('rel');
                jQuery('.tableofcontents li a[rel='+active+']').parent().addClass('current');
                jQuery('.issuepanel, .relationshippanel').hide();
                jQuery('.issuepanel h3.active, .relationshippanel h3.active').parent().show();
            }
        }
    }

    if(jQuery('.chapters').length){
        for(i=1;i<=3;i++){
            var itemcount=0;

            // first make the sidebar links
            jQuery('.content-'+i+' h2').each(function(){
                itemcount++;
                var heading = jQuery(this);
                var text=jQuery(this).text();
                jQuery('.topic-'+i+' .chapters').append('<li rel="'+i+'-'+itemcount+'"><a href="javascript:void(0)">'+text+'</a></li>');
            });
            // next add the wrapping divs
            var nextprev = '<div class="clr"> </div><a href="javascript:void(0)" class="prevchapter">previous chapter</a> <a href="javascript:void(0)" class="nextchapter">next chapter</a><div class="clr"> </div>';
            var dump = jQuery('.content-'+i).html();
            dump = str_replace('<h2>',nextprev+'</div><div class="panel"><h2>',dump);
            dump = str_replace('<H2>',nextprev+'</div><div class="panel"><H2>',dump);
            dump = '<div class="panel">'+dump+nextprev+'</div>';
            jQuery('.content-'+i).html(dump);
            jQuery('.content-'+i+' .panel:first').remove();
            jQuery('.content-'+i+' .panel').each(function(j){
                jQuery(this).attr('rel',i+'-'+(j+1));
            }).hide();

            // now do the interactivity
            jQuery('.topic-'+i+' .chapters li').click(function(){
                var dump=explode('-',jQuery(this).attr('rel'));
                var i=dump[0];
                jQuery(this).siblings().removeClass('current');
                jQuery('.content-'+i+' .panel').hide();

                jQuery(this).addClass('current');
                jQuery('.content-'+i+' .panel[rel='+jQuery(this).attr('rel')+']').show();
            });

            // finally, prep the first ups
            jQuery('.topic-'+i+' .chapters li:first').addClass('current');
            jQuery('.content-'+i+' .panel:first').show();

            jQuery('.content-'+i+' .panel:first .prevchapter').remove();
            jQuery('.content-'+i+' .panel:last .nextchapter').remove();
        }

        jQuery('.prevchapter').click(function(){
            var dump=explode('-',jQuery('.topics .topicblock:visible li.current').attr('rel'));
            var book=dump[0];
            var chapter=dump[1];

            jQuery('.topics .topicblock:visible li').removeClass('current');
            jQuery('.content-'+book+' .panel').hide();

            jQuery('.topics .topicblock:visible li[rel='+(book+'-'+(parseInt(chapter)-1))+']').addClass('current');
            jQuery('.content-'+book+' .panel[rel='+(book+'-'+(parseInt(chapter)-1))+']').show();
        });

        jQuery('.nextchapter').click(function(){
            var dump=explode('-',jQuery('.topics .topicblock:visible li.current').attr('rel'));
            var book=dump[0];
            var chapter=dump[1];

            jQuery('.topics .topicblock:visible li').removeClass('current');
            jQuery('.content-'+book+' .panel').hide();

            jQuery('.topics .topicblock:visible li[rel='+(book+'-'+(parseInt(chapter)+1))+']').addClass('current');
            jQuery('.content-'+book+' .panel[rel='+(book+'-'+(parseInt(chapter)+1))+']').show();
        });
    }

    if(jQuery('.storycontents').length){
        var itemcount=0;
        var nextprev = '<div class="clr"> </div><a href="javascript:void(0)" class="prevchapter">previous chapter</a> <a href="javascript:void(0)" class="nextchapter">next chapter</a><div class="clr"> </div>';
        jQuery('.content h2').each(function(){
            itemcount++;
            var heading = jQuery(this);
            var text=jQuery(this).text();
            jQuery('.storycontents').append('<li rel="'+itemcount+'"><a href="javascript:void(0)">'+text+'</a></li>');
        });

        // next add the wrapping divs
        var dump = jQuery('.content').html();
        dump = str_replace('<h2>',nextprev+'</div><div class="panel"><h2>',dump);
        dump = str_replace('<H2>',nextprev+'</div><div class="panel"><H2>',dump);
        dump = '<div class="panel">'+dump+nextprev+'</div>';
        jQuery('.content').html(dump);
        jQuery('.content .panel:first').remove();
        jQuery('.content .panel').each(function(j){
            jQuery(this).attr('rel',(j+1));
        }).hide();

        // now do the interactivity
        jQuery('.storycontents li').click(function(){
            jQuery(this).siblings().removeClass('current');
            jQuery('.content .panel').hide();
            jQuery(this).addClass('current');
            jQuery('.content .panel[rel='+jQuery(this).attr('rel')+']').show();
        });

        // finally, prep the first ups
        jQuery('.storycontents li:first').addClass('current');
        jQuery('.content .panel:first').show();

        jQuery('.content .panel:first .prevchapter').remove();
        jQuery('.content .panel:last .nextchapter').remove();

        jQuery('.prevchapter').click(function(){
            var chapter=jQuery('.topics .storycontents li.current').attr('rel');

            jQuery('.topics .storycontents li').removeClass('current');
            jQuery('.content .panel').hide();

            jQuery('.topics .storycontents li[rel='+((parseInt(chapter)-1))+']').addClass('current');
            jQuery('.content .panel[rel='+((parseInt(chapter)-1))+']').show();
        });

        jQuery('.nextchapter').click(function(){
            var chapter=jQuery('.topics .storycontents li.current').attr('rel');

            jQuery('.topics .storycontents li').removeClass('current');
            jQuery('.content .panel').hide();

            jQuery('.topics .storycontents li[rel='+((parseInt(chapter)+1))+']').addClass('current');
            jQuery('.content .panel[rel='+((parseInt(chapter)+1))+']').show();
        });
    }

    if(jQuery('.current .polaroids').length){
        jQuery('.polaroids .polaroid a').click(function(){
            var id=jQuery(this).attr('rel');
            jQuery('.topicblock, .contentblock').hide();
            jQuery('.topic-'+id+', .content-'+id).show();
            jQuery('.topic-'+id+' li').removeClass('current');
            jQuery('.topic-'+id+' li:first').addClass('current');
            jQuery('.content-'+id+' .panel').hide();
            jQuery('.content-'+id+' .panel:first').show();
            jQuery('.hoversmack').show();
            jQuery('.hover-'+id).hide();

            return false;
        });
    }

    if(jQuery('.pager').length){
        var firstup=5;
        jQuery('#pageby').numeric();

        //initials
        jQuery('.results.stories .smallpolaroid').each(function(){
            if(parseInt(jQuery(this).attr('rel'))>firstup){
                jQuery(this).hide();
            }
        });
        jQuery('#pagecount').html(Math.ceil(jQuery('.results.stories .smallpolaroid').length/firstup));

        // updates
        jQuery('#perpage').change(function(){
            var perpage=jQuery(this).val();
            jQuery('.results.stories .smallpolaroid').hide().each(function(){
                var thisroid=parseInt(jQuery(this).attr('rel'));
                if(thisroid<=perpage){
                    jQuery(this).show();
                }
            });
            jQuery('#pageby').val(1);
            jQuery('#pagecount').html(Math.ceil(jQuery('.results.stories .smallpolaroid').length/perpage));
        });
        jQuery('.pager .next').click(function(){
            shiftpages(1);
        });
        jQuery('.pager .previous').click(function(){
            shiftpages(-1);
        });
        jQuery('.pager #pageby').focus(function(){
            currentpage=jQuery(this).val();
        });
        jQuery('.pager #pageby').blur(function(){
            var pageto=jQuery(this).val();
            var pagewas=currentpage;
            if(pageto>parseInt(jQuery('#pagecount').html()))
                pageto=parseInt(jQuery('#pagecount').html());
            if(pageto<=0)
                pageto=1;
            jQuery(this).val(pageto);
            currentpage=pageto;
            shiftpages(pageto-pagewas);
        });
    }

    if(jQuery('.stickyback .tableofcontents').length){
        jQuery('.stickyback').height(jQuery('.stickyback .tableofcontents').height()+130)
    }

    var location = document.location.toString();
    if (location.match('#')) {
        if(jQuery('h2.sticky.hiv').length){
            var hash = document.location.hash.toString();
            var chapterto = parseInt(substr(hash,8));
            jQuery('.tableofcontents li').removeClass('current');
            jQuery('.tableofcontents li[rel='+chapterto+']').addClass('current');
            jQuery('#wrapper .content .panel').hide();
            jQuery('#wrapper .content .panel:eq('+(chapterto-1)+')').show();
        }
        else window.location=location;
    }

    hoveronframeHoveroffframe('.homepage .issues .issue','.frame','.issuepic');
    hoveronframeHoveroffframe('.homepage #polaroidslider .polaroid','.frame','.framedpic');
    hoveronframeHoveroffframe('.about .sidebar','.frame','.storypic');
    hoveronframeHoveroffframe('.homepage .stories .smallpolaroid','.frame','.smallpic');
    hoveronframeHoveroffframe('.relationships .stories .smallpolaroid','.frame','.storypic');
});

function hoveronframeHoveroffpic(path,frame,picture){
    jQuery(path+' '+frame).hover(function(){
        jQuery(this).siblings(picture).css('opacity','0.75');
    });
    jQuery(path+' '+picture).hover(function(){},
        function(){
            jQuery(this).css('opacity','1');
        }
    );
}
function hoveronframeHoveroffframe(path,frame,picture){
    jQuery(path+' '+frame).hover(function(){
        jQuery(this).siblings(picture).css('opacity','0.75');
    },function(){
        jQuery(this).siblings(picture).css('opacity','1');
    });
}

function load_clickthrough(item){
    var link = jQuery(item);
    var position = link.position();
    var id = link.attr('rel');

    jQuery('#clickthrough').remove();
    jQuery.get(BASE+'clickthrough/view/'+id,function(data){
        var ctTitle = jQuery(data).find('h3').html();
        _gaq.push(['_trackPageview', '/clickthrough/' + ctTitle]);

        jQuery(data).prependTo('.content');
        var leftpos=position.left;
        if(leftpos>280) leftpos=280;
        var toppos=(position.top+10);
        if(toppos>(jQuery('.content').height()-jQuery('#clickthrough').height())) toppos=(jQuery('.content').height()-jQuery('#clickthrough').height());
        jQuery('#clickthrough').css({top: toppos, left: leftpos, display: 'none', visibility: 'visible'});
        jQuery('#clickthrough').fadeIn();
        jQuery('#clickthrough a.close-clickthrough').click(function(){
            jQuery('#clickthrough').remove();
        });
    });
}

function shiftpages(by){
    var perpage=parseInt(jQuery('#perpage').val());
    var pages=parseInt(jQuery('#pagecount').html());
    var currentpage = parseInt(jQuery('#pageby').val());

    if((currentpage+by)>pages)
        currentpage=pages;
    else if((currentpage+by)<=0)
        currentpage=1;
    else currentpage=currentpage+by;

    var previouspages=currentpage-1;
    jQuery('#pageby').val(currentpage);
    jQuery('.results.stories .smallpolaroid').hide().each(function(){
        var thisroid=parseInt(jQuery(this).attr('rel'));
        if((thisroid>(previouspages*perpage)) && (thisroid<(currentpage*perpage)+1)){
            jQuery(this).show();
        }
    });
}
function scroller(){
    jQuery('#polaroidslider').animate({
        top: '-391px'
    },500,function(){
        jQuery('.polaroid:first').appendTo('#polaroidslider');
        jQuery('#polaroidslider').css('top','0px');
    });
}

function str_replace (search, replace, subject, count) {
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
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 explode (delimiter, string, limit) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']

    var emptyArray = { 0: '' };

    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' ) {
        return null;
    }

    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null ) {
        return false;
    }

    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

