/*-- Google Analytics --*/
var ga_url=location.href.replace(/^http:\/\/.*?\//i, '/');
if (ga_pl) {
    if (ga_url.indexOf('?') > -1) {
        ga_url+='&';
    } else {
        ga_url+='?';
    }
    ga_url+='hl='+ga_pl;
}
var _gaq = _gaq || [];
function track_click_out() {
    try {
        _gaq.push(["my_tracker._trackEvent", "ad", "click", "0"]);
    }catch(err){}
    return true;
}
_gaq.push(function() {
    var ga_tracker = _gat.createTracker(ga_acct, 'my_tracker');
    var fp_tracker = _gat.createTracker('UA-2551200-33', 'fp_tracker');
});
_gaq.push(['my_tracker._setAccount', ga_acct],
          ['fp_tracker._setAccount', 'UA-2551200-33'],
          ['_setDomainName', '.madthumbs.com'],
          ['my_tracker._setAllowLinker', true],
          ['my_tracker._setAllowHash', false],
          ['my_tracker._setCustomVar', 4, 'Role', ga_user_role, 2]);
_gaq.push(function() {
    var ga_tracker = _gat._getTrackerByName('my_tracker');
    var first_time = ga_tracker._getVisitorCustomVar(1);
    var first_source = ga_tracker._getVisitorCustomVar(5);
    if (!first_time || (first_source && ga_source && first_source != ga_source)) {
        _gaq.push(['my_tracker._setCustomVar', 1, 'FirstTime', ga_time, 1],
                  ['my_tracker._setCustomVar', 2, 'FirstCampaign', ga_campaign, 1],
                  ['my_tracker._setCustomVar', 3, 'LastMilestone', '0', 1],
                  ['my_tracker._setCustomVar', 5, 'FirstSource', ga_source, 1]);
    } else {
        var last_milestone_raw = parseInt(ga_tracker._getVisitorCustomVar(3));
        if (last_milestone_raw < 10) {
            var last_milestone_default = last_milestone_raw;
            var last_milestone_mobile = 0;
        } else {
            var last_milestone_default = Math.floor(last_milestone_raw / 10);
            var last_milestone_mobile = last_milestone_raw % 10;
        }

        var time_since_first = ga_time - first_time;
        var time_milestone_map = [[86400, 1], [259200, 2],
            [604800, 3], [1209600, 4], [2592000, 5]];
        var last_milestone = (ga_is_mobile) ? last_milestone_mobile : last_milestone_default;
        var new_milestone = last_milestone;
        var new_goal_day = 0;

        for (var i = 0; i < time_milestone_map.length; ++i) {
            var map_i = time_milestone_map[i];
            if (time_since_first > map_i[0] && last_milestone < map_i[1]) {
                new_milestone = map_i[1];
                new_goal_day = Math.floor(map_i[0] / 86400);
            } else if (time_since_first <= map_i[0]) {
                break;
            }
        }

        var goal_dir = '/goal/repeat/';
        if (!document.referrer) {
            goal_dir = '/goal/loyalty/';
            _gaq.push(['my_tracker._trackPageview', '/goal/hook/bookmark']);
        }

        if (new_goal_day) {
            if (ga_is_mobile) {
                var new_milestone_enc = last_milestone_default * 10 + new_milestone;
            } else {
                var new_milestone_enc = new_milestone * 10 + last_milestone_mobile;
            }
            var goal_path = goal_dir + 'day_' + new_goal_day;
            _gaq.push(['my_tracker._setCustomVar', 3, 'LastMilestone', new_milestone_enc, 1],
                      ['my_tracker._trackPageview', goal_path]);
        }
    }
});
_gaq.push(['my_tracker._trackPageview', ga_url]);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = 'http://www.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();


/*-- Core JavaScript functions --*/

var mt_main = {
    warning:{
        init: function(){
            if (!is_network()) {
        		$('#warning').overlay({
        		top: 300,
                fixed: false,
        	    mask: { 
        	        color: '#000', 
        	        loadSpeed: 0, 
        	        opacity: 1 
        	    }, 
        	    closeOnClick: false, 
        	    closeOnEsc:false,
        	    load: true,
        	    zIndex: 10000 
        	    });
        	} else {
        		createCookie('warned', '1', 360);
        	}
        	
        	$('#enterlink').click(function(){
        		createCookie('warned', '1', 360);
        		$('#warning').overlay().close();
        		return false;
        	});
        }
    },
/*
    ads:{
       init: function(width, height, adSrc, zone, container, css, frame_name){
       try{
            _gaq.push(function () {
            var div = document.getElementById(container),
                ga_tracker = _gat._getTrackerByName("my_tracker");
                src = ga_tracker._getLinkerUrl(adSrc + zone);
            frame = document.createElement("iframe");
            frame.setAttribute("name", frame_name);
            frame.setAttribute("width", width);
            frame.setAttribute("height", height);
            frame.setAttribute("scrolling", "no");
            frame.setAttribute("class", css);
            frame.setAttribute("allowtransparency", "true");
            frame.setAttribute("frameborder", "0");
            frame.setAttribute("marginheight", "0");
            frame.setAttribute("marginwidth", "0");
            frame.setAttribute("src", src);
            div.insertBefore(frame, div.firstChild);
            });
        } catch(e){}
       }
    },
*/
    mobile_redirect:{ 
       init: function(request){
            var url = request.match(/videos/i) ? 'http://mobile.madthumbs.com/' + request : request.match(/categories/i) ? 'http://mobile.madthumbs.com' + request.replace(/categories/, '') : '';
            if(navigator.userAgent.match(/iphone/i))
            { 
            //Iphone 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/ipod/i))
            { 
            //Ipod 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/android/i))
            { 
            //Android 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/sgh/i))
            { 
            //Samsung 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/sonyericsson/i))
            { 
            //Sony Ericsson 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/psp/i))
            { 
            //Playstation Portable 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/mot/i))
            { 
            //Motorolla 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/htc/i))
            { 
            //HTC 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/lg/i))
            { 
            //LG 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/opera mini/i))
            { 
            //Opera mini 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/blackberry/i))
            { 
            //BlackBerry 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/nokia/i))
            { 
            //Nokia 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/palm/i))
            { 
            //PALM 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/ipaq/i))
            { 
            //iPAQ 
            location.replace(url); 
            }
            else if(navigator.userAgent.match(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|pda|treo)/i) && !navigator.userAgent.match(/ipad/i))
            { 
            //Other Device 
            location.replace(url); 
            } 
        }
    }, 
    admin: {
        init: function(){
                var href;
                // admin override of user uploaded vidspage
                $('.edit_user', '#admin_form').live('click', function(){
                    $(this).parent('.admin_override').find(':hidden').show().find('input.override').focus().change(function(){
                        var self = $(this);
                        if (self.val() == 'yes'){
                        self.parents('form').find(':input:disabled').removeAttr('disabled').end().find('.admin_override').empty();
                        $('#save_close').removeAttr('disabled');
                            $('.listOfTags span').each(function() {
                                //console.log($(this).find('u'));
                                var tagName = $(this).find('u');
                                tagName.replaceWith("<a class=\"removableTag\" href=\"#\">"+tagName.text()+"</a>");
                            });
                        
                        }            
                    });
                });
                
                $('#banned, #banned_reason', '#admin_form').live('change', function(){
                    $(this).parents('form').find('input[type=submit], #save_close').removeAttr('disabled');
                });
                
/*
                $('#watermark_button', '#admin_form').live('click', function(){
                    var pos = $('input[name="watermark_position"]:checked', '#admin_form').val();   
                    var spawn = $(this).val() + '&pos=' + pos;
                    var id = $(this).val().split('?id=')[1]; 
                    window.open(spawn, 'Watermark Video' + id, 'status=1,toolbar=0,location=1,menubar=0,directories=0,resizable=0,scrollbars=0,height=450,width=550');
                    $(this).attr('disabled', 'disabled').after('<span class="green fr">Processing…</span>');
                    return false;
                });
*/
                                
                $('a.admin_icon, a.admin_link').live('mouseenter',
                    function () {
                        var error = false;
                    $(this).overlay({
                            //api: true,
                            target: '#overlay',
                            close: '#close',
                            fixed: false,
                            mask: {
                                color: '#333333',
                                loadSpeed: 600,
                                opacity: 0.75,
                                zIndex: '9997'
                            },
                            //closeOnClick: false,
                            zIndex: '9998',
                            onBeforeLoad: function () {
                                var wrap = this.getOverlay().find('.formWrap');
                                href = this.getTrigger().attr('href');
                                wrap.load(href, function () {
                                    var form = $('#admin_form');
                                    $('#close').show();
                                    $('#category').change(function () {
                                        var category = $(this).find('option:selected').val();
                                        $(':input[value="' + category + '"]').attr('checked', 'checked');
                                    });
                                    if(form.hasClass('user_upload')) form.find(':input').not('.override').attr('disabled', 'disabled');
                                    form.submit(function(e) {
                                        var str = $(this).serialize();
                                        $.ajax({
                                            type: 'POST',
                                            url: href,
                                            async: false,
                                            cache: false,
                                            data: str,
                                            error: function (xhr, text, error) {
                                                $('#message').html('<span class="error fr">Save error!</span>');
                                                error = true;
                                            },
                                            success: function (data) {
                                                var msg = $(data).find('#message').html();
                                                var response = msg.length ? '<span class="green fr">' + msg + '</span>' : '<span class="error fr">Save error. Please try again.</span>';
                                                $('#message').html(response);
                                                if (msg.length == 0) error = true;
                                            }
                                        });
                                        return false;
                                    });
                                });
                                if (typeof $f() != 'undefined') $f().stop().close();
                            },
                            onLoad: function(){
                                var over = this;
                                $('#save_close').live('click', function () {
                                    //$('#admin_form').submit();
                                    if (!error) setTimeout(function(){over.close();}, 600);
                                });
                            }
                        });
                });
                
/*
                $('a.admin_link', '#player').click(function (e) {
                    href = $(this).attr('href');
                    $('#close').hide();
                    $('#overlay').css('position', 'static').insertAfter('#player').slideToggle(500, function () {
                            $('html, body').animate({scrollTop:$('#overlay').offset().top}, 'fast'); 
                        if ($(this).is(':visible')) $(this).find('.formWrap').load(href, function () {
                            var form = $('#admin_form');
                            $('#save_close').remove();
                            form.append('<input id="cancel_admin" type="button" class="styled fr" value="Cancel"/><br/>');
                            $('#cancel_admin').click(function (e) {
                                $('#overlay').slideUp(500);
                                e.preventDefault();
                            });
                            $('#category').change(function () {
                                var category = $(this).find('option:selected').val();
                                $(':input[value="' + category + '"]').attr('checked', 'checked');
                            });
                            form.submit(function(e) {
                                var str = $(this).serialize();
                                $.ajax({
                                    type: 'POST',
                                    url: href,
                                    async: false,
                                    cache: false,
                                    data: str,
                                    error: function (xhr, text, error) {
                                        $('#message').html('<span class="error fr">Save error!</span>');
                                    },
                                    success: function (data) {
                                        var msg = $(data).find('#message').html();
                                        var response = msg.length ? '<span class="green fr">' + msg + '</span>' : '<span class="error fr">Save error. Please try again.</span>';
                                        $('#message').html(response);
                                    }
                                });
                                e.preventDefault();
                            });
                            if(form.hasClass('user_upload')) form.find(':input').not('.override, #cancel_admin').attr('disabled', 'disabled');
                            $('#save_close').attr('disabled', 'disabled');
                        });
                    });
                    e.preventDefault();
                });
*/                             

                // cash4porn overlay admin    
                $('#status').live('change', function(){
                    var self = $(this);
                    var selected = self.children('option').filter(':selected');
                    self.siblings('input[type=text]').hide();
                    if (selected.val() == 'PAYABLE') $('#cash_amount').show().focus();
                    if (selected.val() == 'UNPAYABLE') $('#c4p_reason').show().focus();
                });  
                
                $('input[name="watermark_position"]', '#admin_form').live('change', function(){
                    if ($(this).is(':checked')) $('#reencode').attr('checked', 'checked');
                });
                
                $('#reencode').live('change', function(){
                    if (!$(this).is(':checked')) $('input[name="watermark_position"]:checked', '#admin_form').removeAttr('checked');
                });
                               
        }
    },
    star_rating: {
        init: function(url){
                $('input[type=radio].star').rating({ 
                callback: function(value, link) {
                    var postVal = url + '/' + value / 2;
                    $.ajax({
                        type: 'POST',
                        url: postVal,
                        async: false,
                        data: null
                        //success: function (data) {
                        //   $('span.rated').html('OK!');
                        //}
                    });  
                }
                });
        }
    },
    player_page: {
        init: function(){
                //*-- player page specific functionality --*//    
            
                $('button', '#flag').click(function () {
                    var complaint = $('#flag_reason').find('option:selected').val() + '&c=' + escape($('#flag_comment').val());
                    var action = $(this).val() + complaint;
                    $.ajax({
                        type: 'POST',
                        async: false,
                        url: action,
                        data: null,
                        success: function (data) {                            
                            $('.flaglink', '#playerInfo').empty().html('Flagged!<span class="flagged"></span>').removeAttr('href');
                            $('#flag').slideUp();
                        }
                    });

                    return false;
                });
                
                $('input[name="seekonstart"]', '#embed').change(function(){
                    var param = '&t=' + $(this).val();
                    $('#embed_code').text(function(index, text){
                        return text.replace(/(id%3D\d*)(%26t%3D\d*)?/gi, '$1' + escape(param));
                    });
                });
                
                $('#embed_code, #link_code').mouseup(function(){
                    $(this).select();
                });
                
                $('#video_description').hide();
                
                $('.first a, .flaglink', '#playerInfo').click(function(e){
                   var div = $(this).attr('href');
                   $(div).slideToggle(function(e){
                        if(div == '#embed' && $(div).is(':visible')) $(div).children('textarea').select();
                    });
                   return false;
                   e.stopImmediatePropagation(); 
                });
                
                //*-- ad popup --*//    
            /*   $('.toggle').click(function(){
                    var pos = $(this).css('background-position') === '50% 100%' ? '50% 0' : '50% 100%';
                    $(this).css('background-position', pos);
                    var pop = $('#ad_popup');
                    if (pop.is(':visible') && pop.height() == 20){ 
                        $('#pop_wrap').unbind('mousemove mouseleave');
                        pop.animate({height: 92}, 500, null, function(){
                            $(this).find(':hidden').show();
                        });
                    } else {
                        pop.slideUp(function(){
                            $('#pop_wrap').bind({
                            mousemove: function(){
                                if(pop.is(':hidden')) pop.height(20).fadeIn();
                            },
                            mouseleave: function(){
                                pop.fadeOut();
                            }
                            });
                        }).find('img, iframe').hide();
                    }    
                });
            */
                $('.toggle', '#ad_popup').click(function(){
                    $('#ad_popup').stop(true).slideUp();
                });
                
                $('a', '#share').click(function(e){
                    switch ($(this).attr('id')) {
                    case 'twitter':
                        window.open('http://twitter.com/share?url=' + encodeURIComponent(window.location) + '&via=MadThumbsTube&related=realitykings:THE%20TOP%2028%20HD%20PORN%20SITES%20ON%20THE%20WEB!!!%206000%2B%20VIDEOS&text=' + escape(vid_title), 'Twitter', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,height=450,width=550');
                        break;
                    case 'facebook':
                        window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(window.location) + '&t=' + escape(vid_title), 'Facebook', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,height=440,width=620');
                        break;
                    case 'reddit':
                        window.open('http://reddit.com/submit?url=' + encodeURIComponent(window.location) + '&title=' + escape(vid_title), 'Reddit', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,height=740,width=860');
                        break;
                    default:                    
                        break;
                    }
                    return e.preventDefault();
                });           
        }
    },
    flowplayer:{
        init: function(swf_url, vid_url, banned, xml_url, sprite_url, deep_tags){
            var seekTime = location.hash.split('t=')[1];
            var toggleCont = function(isPlaying) { 
                var scroll = fp.getPlugin('thumb_scroll');
                var fs = fp.getControls();
                var screen = fp.getScreen();
                   if (isPlaying){
                    scroll.animate({opacity: 1, top: '50pct'}, 500);
                    fs.enable({fullscreen: false});
                    screen.animate({opacity: 0.3},500);
                   } else { 
                    scroll.animate({opacity: 0, top: '150pct'}, 500);
                    fs.enable({fullscreen: true});
                    screen.animate({opacity: 1},500);
                   }
            };
            
            var fp = $f('thePlayer', {src: swf_url, version:[9, 115], expressInstall:null, wmode:'opaque', cachebusting: false}, { 
            //debug:true,
            //log:{ level: 'debug', filter:'org.flowplayer.pseudostreaming.*'},
            onError: function(errorCode, errorMessage){
                try {
                    _gaq.push(["fp_tracker._trackEvent", "Errors", errorCode + errorMessage, fp.getClip().url, fp.getTime()]);
                }catch(error){
                    //console.log(error);
                }
            },
            onBeforeLoad: function(){
                if (deep_tags){
                    $('#thePlayer, #playerCont').css({'height':'516px'});
                    $('#pop_wrap').css({'bottom' : '40px'});
                }
            },
            onLoad: function(){
                if (!deep_tags) return;

                var controls = fp.getControls();
                controls.animate({bottom: 16}, 500, function(){
                    if(!banned){ 
                        $('#ad_popup').show().delay(4000).slideUp(function(){
                            $('#pop_wrap').remove();
                        });
                    }
                });
                
                fp.loadPlugin('deep_tags','http://cache.tgpsitecentral.com/madthumbs/js/flowplayer/plugins/flowplayer.deeptags-3.2.6-dev.swf', {
                    'duration':vid_duration,
                    'urlBase':'http://www.madthumbs.com',
                    'id':vid_id
                }, function(){
                    //callback
                    $('#thePlayer').append('<img src="http://cache.tgpsitecentral.com/madthumbs/images/deep_tags.png" class="deep_tag_logo" alt="DeepTags&trade;" title="DeepTags&trade; - Patent Pending"/>');
                });
            },
            //onStart: function(clip) {
    			//fp.getScreen().animate({width: clip.w, height: clip.h}, 500);
    		//},
            onBeforeFullscreen: function (){
                if(banned) return false;
            },
            onFullscreenExit: function() { 
               toggleCont();
               if(fp.isPaused()) fp.play();
               if (deep_tags) fp.getControls().animate({bottom: 16}, 500);
            },
            onBeforeResume: function() { 
                if(banned) return false; 
            },  
    		screen:{
    		  bottom: 23
    		},
            plugins: {
                thumb_scroll: {
                    xmlPath: xml_url,
                    showRating: !banned,
                    url: 'http://cache.tgpsitecentral.com/madthumbs/js/flowplayer/plugins/flowplayer.thumbscroller-3.2.5-dev.swf',                     
                    opacity: 0,
                    top: '150%',
                    left:0,
                    zIndex: 2
                },
                controls: {
                    tooltips: {
                        scrubberImage: sprite_url
                    },
                    autoHide: {
                        enabled: false
                    }
                }
            },
            clip:{
                //playlist: [{
                    url: vid_url,
                //}],
                duration: vid_duration,
                onBegin: function(clip){
                    toggleCont();
                },
                onMetaData: function(clip){
                    var keyframes = clip.metaData.keyframes.times || [];
                    var interval = Math.floor(vid_duration/keyframes.length); //approx time between keyframes
                    if (interval > 1 || keyframes.length == 0){
                        try {
                            _gaq.push(["fp_tracker._trackEvent", "Keyframes", vid_id, interval + " seconds apart"]);
                        }catch(error){
                            //console.log(error);
                        }
                    } 
                },
                onStart: function(){
                    if (seekTime){ 
                        fp.seek(seekTime);                
                    }
                    
                    if(banned){
                        fp.stop();
                        this.getControls().hide();
                    }    
                },
                onPause: function (clip) { 
                   toggleCont(1);
                },
                onBeforeSeek: function(){
                   if(fp.isPaused()) fp.resume();
                },
                onBeforeFinish: function(clip) { 
                   if(fp.isFullscreen()) fp.toggleFullscreen();
                   toggleCont(1);
                }, 
                onResume: function(clip){
                    toggleCont();
                },
                onStop: function(clip){
                    toggleCont(1);
                }
            }              
            });
            
            /*
$('a.playbutton', '#playerCont').click(function(){
                $(this).fadeOut(600); 
                fp.load();
                return false;
            });
*/
            
            if(banned){
                $('#playerInfo').html('<p class="s bot"><br/>This video has been removed.</p><br/>');
            }
            
        }
    },
/*
    deep_tags: {
        init: function(){
                var hide;
                $('a', '#deep_tags').bind({
                click: function(){
                    var seekTime = $(this).attr('href').split('#t=')[1];
                    if ($('#thePlayer_api').length){ 
                        $f().seek(seekTime);            
                        hide = setTimeout(function(){$f().getControls().hideTooltip();}, 1000);
                    }
                    return false;
                },
                mouseover: function(){
                    var $anchors = $('a','#deep_tags');
                    var indx = $anchors.index(this);
                    var marker = $('a', '#markers').eq(indx);
                    var thumb = Math.floor(parseFloat(marker.css('left')) / 2);
                    var xPos = Math.floor(marker.position().left);
                    marker.css({'border-color': '#eee', 'height': '15px'});
                    if ($('#thePlayer_api').length){ 
                        $f().getControls().triggerTooltip(xPos, thumb);
                    }
                },
                mouseleave: function(){
                    var $anchors = $('a','#deep_tags');
                    var indx = $anchors.index(this);
                    var marker = $('a', '#markers').eq(indx);
                    clearTimeout(hide);
                    marker.css({'border-color': '#f60', 'height': '6px'});
                    $f().getControls().hideTooltip();
                }
                });

                $('a', '#markers').hover(
                function(){
                    var $markers = $('a','#markers');
                    var indx = $markers.index(this);
                    var $tag = $('a', '#deep_tags').eq(indx);
                    $tag.css({'color': '#eee', 'text-shadow': '0 0 3px #f90'});
                },
                function(){
                    var $markers = $('a','#markers');
                    var indx = $markers.index(this);
                    var $tag = $('a', '#deep_tags').eq(indx);
                    $tag.css({'color': '#f60', 'text-shadow': '1px 1px 2px #000'});
                });
        }
    },
*/
    profile_page: {
        init: function () {
            //*-- profile page specific functionality --*//        
            //*-- jQuery ajax tabs --*//
            var isIE6 = $.browser.msie && $.browser.version == 6.0;
            var tabSelect = location.hash ? location.hash : '#recently_viewed_tab';
            var $tabs = $('#tabs').tabs({
                selected: null,
                cache: true,
                spinner: 'Loading&hellip;',
                ajaxOptions: {
                    cache: false,
                    error: function (xhr, status, index, anchor) {
                        $(anchor.hash).html('<div class="cont"><p class="bodytext"><br/><span class="error">Error retrieving data. Please try refreshing the page.</span></p></div>');
                    }
                },
                load: function (event, ui) {
                    $('.pagination a', ui.panel).live('click', function (e) {
                        $(ui.panel).load(this.href, function () {
                                if (!isIE6){
                                $('.scrub_box').one('mouseenter', function(e){
                                    initScrubber($(this), {
                                    speed:400,
                                    numImages:50
                                    });
                                });
                                }
                        });
                        return false;
                    });
                    $('#programs_form').submit(function () {
                        //$(this).find('span.error').remove();
                        return formSubmit($(this), $(this).attr('action'), function () {
                            $('#programs_form .err').text('Changes saved').show();
                            //$('#programs_form').find('input[value=""]').parents('li').find('span:first').after('<span class="error fr">Missing values. Not saved.</span> ');
                        });
                    });
                }
            }).bind({
                tabsload: function (event, ui) {
                    var panel = $(ui.panel);
                    if (panel.attr('id') == 'programs') {
                        $('#clear_ads').change(function () {
                            if ($(this).is(':checked')) $(this).parent('label').siblings('fieldset.sponsor').find('input[type=text]:not([name*=linkurl])').val('');
                            else $tabs.tabs('load', ui.index);
                        });
                    }
                    if (!isIE6){
                    $('.scrub_box').one('mouseenter', function(e){
                        initScrubber($(this), {
                        speed:400,
                        numImages:50
                        });
                    });
                    }
                },
                tabsselect: function (event, ui) {
                    if (String(location).match(/profile/i)) location.hash = $(ui.panel).attr('id') + '_tab';
                }
            });
            
            if (cashUser){
                $tabs.tabs('select', 'cash4porn_tab');
            } else {
                $tabs.tabs('select', tabSelect.split('_tab')[0]);
            }
            
            if (String(location).match(/profile/i)) {
                $('.biglink a').not(':last').click(function () {
                    var href = $(this).attr('href');
                    $(this).addClass('active');
                    tabSelect = href.substr(href.lastIndexOf('#'));
                    $tabs.tabs('select', tabSelect);
                    $tabs.tabs('load', $tabs.tabs('option', 'selected'));
                    return false;
                });
            }
            
            $('#resend').click(function(){
                $.post('/users/email_request/', function(data){
                    $('#confirm_email').html('<p>Instructions for verifying your email address have been sent to ' + email + '.</p>');
                });
                return false;
            });
            
            $('#profile_form').validate({
                //ignore: '.ignore',
                errorPlacement: function(error, element) {
                    error.insertBefore($('input[type=submit]', '#profile_form'));
                },
                rules: {
                    email: {
                        required: true,
                        email: true
                    },
                    number: {
                        required: true,
                        phoneUS: true
                    }
                },
                messages: {
                    email: "Please enter a valid email address",
                    number: "Please enter your mobile #"
                },
                submitHandler: function (form) {
                    formSubmit($(form), "/users/update", function () {
                    });
                }
            });
            
            $('.formToggle', '#member_box').click(function(){
                var form = $(this).attr('href');
                $('ul, input[type=submit]', form).slideToggle();
                return false;
            });
            
            $('input[name="payment_method"]:first', '#payment_method').change(function(){
                if ($(this).is(':checked')) $('#address_field').slideDown();
            }).triggerHandler('change');
            
            $('#tax_form').validate({
                //ignore: '.ignore',
                errorPlacement: function(error, element) {
                    if (element.attr('name') == 'certify')
                    error.insertBefore($('input[type=submit]', '#tax_form'));
                    else
                    error.insertAfter(element);
                },
                rules: {
                    first_name: {
                        required: true
                    },
                    last_name: {
                        required: true
                    },
                    address: {
                        required: true
                    },
                    city: {
                        required: true
                    },
                    tax_name: {
                        required: true
                    },
                    payment_type: {
                        required: true
                    },
                    certify:{
                        required: true
                    }
                },
                messages: {
                    first_name: "Please enter your first name",
                    last_name: "Please enter your last name",
                    address: "Please enter your street address",
                    city: "Please enter your city",
                    state: "Select your state",
                    tax_name: "Please enter the name of your business",
                    certify: "You must certify that this information is correct"
                    
                },
                submitHandler: function (form) {
                    var $form = $(form);
                    var action = $form.attr('action');
                    formSubmit($form, action, function(){
                        $('<span class="green block">Tax Info Updated</span>').appendTo($form).delay(2000).slideUp();
                    });
                }
            });
        }
        
    }
};

jQuery.fn.swap = function (b) {
    b = jQuery(b)[0];
    var a = this[0];
    var t = a.parentNode.insertBefore(document.createTextNode(''), a);
    b.parentNode.insertBefore(a, b);
    t.parentNode.insertBefore(b, t);
    t.parentNode.removeChild(t);
    return this;
};

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number.");

var validateAjaxForms = function(trigger){
    var $parent = '#overlay_form';
    var $trigger = trigger;
    $('#forgot', $parent).validate({
        rules: {
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            email: "Please enter a valid email address"
        },
        submitHandler: function (form) {
            formSubmit($(form), "/users/login", function () {
                location.reload();
            });
        }
    });   
          
    $('#login_overlay', $parent).validate({
        rules: {
            username: {
                required: true,
                minlength: 1
            },
            password: {
                required: true,
                minlength: 1
            }
        },
        messages: {
            username: {
                required: "Please enter a username",
                minlength: "Please enter a username"
            },
            password: {
                required: "Please provide a password",
                minlength: "Please enter a username"
            }

        },
        submitHandler: function (form) {
            formSubmit($(form), "/users/login", function () {
                var href = $trigger.attr('href').split('?page=')[1];
                if (typeof href != 'undefined'){
                    location.href =  '/' + href;
                }else {
                    location.href = String(location).split('?')[0];
                }
            });
        }
    });
    
    $('#signup_overlay', $parent).validate({
        ignore: '.premium',
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            },
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            username: {
                required: "Please enter a username"
            },
            password: {
                required: "Please provide a password"
            },                        
            email: "Please enter a valid email address"
        },
        submitHandler: function(form) {
            formSubmit($(form), "/users/register", function () {
                var href = $trigger.attr('href').split('?page=')[1];
                if (typeof href != 'undefined'){
                    location.href =  '/' + href;
                }else {
                    location.href = String(location).split('?')[0];
                }
            });
        }

    });
};


$(function () {
    var isIE6 = $.browser.msie && $.browser.version == 6.0;

    if (!isIE6){
    $('.scrub_box').one('mouseenter', function(e){
        initScrubber($(this), {
        speed:400,
        numImages:50
        });
    });
    }

    if (!readCookie('nonSocial')){
      $('#social_bookmark').show();
      $('a.close', '#social_bookmark').click(function(){
          createCookie('nonSocial', 'nonSocial', 0);    		      
          $('#social_bookmark').animate({'width': 0}, 400, function(){
            $(this).remove();
          });
          return false;
      });
    }  
   
    //*-- 1min ad refresh --*//
    
    var j = 0;
    var t = window.setInterval(refreshAds, 120000);     
    
    function refreshAds(){
        $('iframe:not(#hd_iframe, #hd_videos)').each(function(){
            $(this).attr('src', function(i, src){
                return src;
            });
        });
       if(++j > 4) window.clearInterval(t);
    }

/*
    $(".account input.realPass").focus(function () {
        var el = $(this);
        if ((this.name == 'password' || this.name == 'password_confirm') && el.attr("type") != 'password') {
            var el2 = $('<input/>').attr("type", "password").attr("name", this.name).addClass('txt');
            el.after(el2);
            el.remove();
            el2.focus();
        }
        el.select();
    });
*/

    // toggle login / signup
    $('#anext, #aprev').click(function () {
        var el = $('#login_overlay');
        var el2 = $('#forgot');
        el.swap(el2).toggle('slow', function(){
            $(this).find('input:first').focus();
        });
        el2.toggle('slow', function(){
            $(this).find('input:first').focus();
        });
    });
    
    $('#searchButton').click(function(){
        var $form = $('#sitesearch'); 
        if ($('#searchInput').val() != 'Search MadThumbs') $form.submit();
        return false;
    });
    
    $('a.fakelink', '#wrapTab, #user, #menu, #footer').click(function(){
        var $this = $(this),
        target = $this.attr('target'),
        rev = $this.attr('rev'),
        title = $this.attr('title').replace(/ /g,'_'); 
        if (target == '_top')
            location = rev;
        else 
            window.open(rev, title);
        return false;
    });

    $('a.login', '#user, #comments, #locker_link, #recent, #member_box').overlay({
            close: '.close',
            top: 300,
            fixed: false,
            target: '#overlay_form',
            mask: {
                color: '#333333',
                loadSpeed: 200,
                opacity: 0.75,
                zIndex: '9997'
            },
            //closeOnClick: false,
            zIndex: '9998',
            onBeforeLoad: function(){
                if (typeof $f() != 'undefined') $f().stop().close();
            },
            onLoad: function(){
                var $trigger = this.getTrigger();
                var $parent = '#overlay_form';
                $('#signup_overlay', $parent).hide();
                $('#loginscroll', $parent).show().find('input[type=text]:first').focus();  
                validateAjaxForms($trigger);                
            }

    });
    
    $('a.signup', '#user, #get_access, #comments').overlay({
            close: '#close',
            top: 300,
            fixed: false,
            target: '#overlay_form',
            mask: {
                color: '#333333',
                loadSpeed: 200,
                opacity: 0.75,
                zIndex: '9997'
            },
            //closeOnClick: false,
            zIndex: '9998',
            onBeforeLoad: function(){
                if (typeof $f() != 'undefined') $f().stop().close();
            },
            onLoad: function(){
                var $trigger = this.getTrigger();
                var $parent = '#overlay_form';
                $('#loginscroll', $parent).hide();
                $('#signup_overlay', $parent).show().find('input[type=text]:first').focus();
                validateAjaxForms($trigger);
            }

    });
    
    $('.login_toggle', '#overlay_form').click(function(){
        $('#signup_overlay, #loginscroll').toggle('slow', function(){
            $(this).find('input:first').focus();
        });
        return false;
    });
                    
    $('#loginscroll').click(function (e) {
        e.stopPropagation();
    });


    // Show Login
/*
    $('#loginL').hover(function () {
        var pos = $(this).offset();
        $('#user a').removeClass('active');
        $('.ttlike').hide();
        $('#loginscroll').css({
            top: pos.top + 20 + 'px',
            left: pos.left - ($('#signup').width() / 2) + ($(this).width() / 2) + 'px',
            position: 'absolute'
        }).show();
        $(this).addClass('active');
    });
*/

    //Show Signup 
/*
    $('#signupL').hover(function () {
        var pos = $(this).offset();
        $('#user a').removeClass('active');
        $('.ttlike').hide();
        $('#signup').css({
            top: pos.top + 20 + 'px',
            left: pos.left - ($('#signup').width() / 2) + ($(this).width() / 2) + 'px',
            position: 'absolute'
        }).show();
        $(this).addClass('active');
    });
*/

/*
    // Stop propagation of click event on signup box
    $('#signup').click(function (e) {
        e.stopPropagation();
    });

    // Hide signup when body is clicked
    $('body').click(function (e) {
        $('.ttlike').fadeOut(300);
        $('#user a').removeClass('active');
    });


    // When onfocus on passwordTxt -> change display password 
    $('#passwordTxt').focus(function () {
        $(this).hide();
        $('#password_ajax').show().focus();
    });

    // When onfocus on passwordTxt -> change display password 
    $('#password_confirmTxt').focus(function () {
        $(this).hide();
        $('#password_confirm').show().focus();
    });
*/

    $.formSubmit = formSubmit;
            
    //*-- Form validation --*// 
    
    $("#register").validate({
        rules: {
            username: {
                required: true,
                minlength: 1
            },
            password: {
                required: true,
                minlength: 1
            },
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            username: {
                required: "Please enter a username",
                minlength: "Please enter a username"
            },
            password: {
                required: "Please provide a password",
                minlength: "Please provide a password"
            },
            email: "Please enter a valid email address"
        },
        submitHandler: function (form) {
            var $form = $(form);
            var action = $form.attr('action');
            if (!String(location).match(/cash/i)){
                formSubmit($form, action, function () {
                    var href = String(location).split('?page=')[1];
                    if (typeof href != 'undefined'){
                        location.href =  '/' + href;
                    }else {
                        location.href = String(location).split('?')[0];
                    }
                });
            } else {
                form.submit(form.serialize());
            }
        }
    });    


    $('#login_form').validate({
        rules: {
            username: {
                required: function(element){
                    $(element).is(':visible');
                },
                minlength: 1
            },
            password: {
                required: function(element){
                    $(element).is(':visible');
                },
                minlength: 1
            }
        },
        messages: {
            username: {
                required: "Please enter a username",
                minlength: "Please enter a username"
            },
            password: {
                required: "Please provide a password",
                minlength: "Please enter a username"
            }

        },
        submitHandler: function (form) {
            var $form = $(form);
            var action = $form.attr('action');
            if (!String(location).match(/cash/i)){
                formSubmit($form, action, function () {
                    var href = String(location).split('?page=')[1];
                    if (typeof href != 'undefined'){
                        location.href =  '/' + href;
                    }else {
                        location.href = String(location).split('?')[0];
                    }
                });
            } else {
                form.submit(form.serialize());
            }
        }
    });   
    
    $('#password_form').validate({
        rules: {
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            email: "Please enter a valid email address"
        },
        submitHandler: function (form) {
            var $form = $(form);
            var action = $form.attr('action');
            if (!String(location).match(/cash/i)){
                formSubmit($form, action, function () {
                    var href = String(location).split('?page=')[1];
                    if (typeof href != 'undefined'){
                        location.href =  '/' + href;
                    }else {
                        location.href = String(location).split('?')[0];
                    }
                });
            } else {
                form.submit();
            }
        }
    });

    var scroll;
    // Search Suggestions
    $('#searchInput').blur(function () {
        setTimeout(function(){$('#suggestions').fadeOut(100);
        }, 250);
    }).keyup(function (e) {
        var link = $('#autoSuggestionsList').children('li.chosen').find('a'),
            restrictedKeys = [27, 33, 34, 37, 38, 39, 40, 46];
        clearTimeout(scroll);
        if (link.length) {
                if (e.keyCode == 13) location = link.attr('href');
                //$(this).val(link.text());
                //$(this).val(link.attr('title'));
            }
        if (restrictedKeys.indexOf(e.keyCode) == -1) lookup($(this).val());
    }).keydown(function (e) { //no keypress for safari :(
        var list = $('#autoSuggestionsList');
        switch (e.keyCode) {
        case 38:
            //up arrow
            if ($('#autoSuggestionsList').children().length) $('#suggestions').fadeIn(100);
            var scrollUp = function(){
                if (indx > 0) {
                    list.children('li').eq(indx -= 1).addClass('chosen').siblings().removeClass('chosen');
                    $('#searchInput').val(list.children('li.chosen').find('a').text());
                    scroll = setTimeout(scrollUp, 120);
                } else {
                    indx = -1;
                    list.children('li:first').removeClass('chosen');
                    $('#searchInput').val(lastSearch);
                    clearTimeout(scroll);
                }
            };
            scrollUp();
            break;
        case 40:
            //down arrow
            if ($('#autoSuggestionsList').children().length) $('#suggestions').fadeIn(100);             
            var scrollDown = function(){
                if (indx < list.children().length - 1){
                    list.children('li').eq(indx += 1).addClass('chosen').siblings().removeClass('chosen');
                    $('#searchInput').val(list.children('li.chosen').find('a').text());
                    scroll = setTimeout(scrollDown, 120);
                }
            };
            clearTimeout(scroll);
            scrollDown();
            break;
        case 27:
            //esc
            $(this).blur();
            $('#suggestions').fadeOut(100);
            $('#autoSuggestionsList').empty();
            break;
        case 37:
            //left arrow
            list.children('li').removeClass('chosen');
            $('#suggestions').fadeOut(100);
            break;
        case 39:
            //right arrow
            list.children('li').removeClass('chosen');
            $('#suggestions').fadeOut(100);
            break;
        case 8:
            //backspace
            list.children('li').removeClass('chosen');
            break;
        case 32:
            //spacebar
            list.children('li').removeClass('chosen');
            break;
            //default :
            //list.children('li').removeClass('chosen');
            //break;
        }
    });  

var offsetMethod = $.fn.position;
$.fn.position = function () {
    var offset = offsetMethod.call(this),
        bottom = offset.top + this.outerHeight(),
        right = offset.left + this.outerWidth(),
        a = arguments;
    return (a.length) ? this.animate({
                                     top  : a[0].top  || a[0],
                                     left : a[0].left || a[1]
                                     }, (a[0].top ? a[1] : a[2]) || 1)
                      : $.extend(offset, {
                                         bottom: bottom,
                                         right: right
                                         });
}; 
   

});

/*-- ajax search --*/
var indx = -1;
var lastSearch = "";
var failedSearch = "";

function lookup(inputString) {
    if (inputString.length < 3) {
        // Hide the suggestion box.
        $('#suggestions').fadeOut(100);

    } else {

        //match this substring against failed substring
        if (failedSearch.length > 2) {
            if (failedSearch == inputString.substr(0, failedSearch.length)) {
                //alert("not doing search for " + inputString);
                $('#suggestions').fadeOut(100);
                return;
            }
        }

        //cancel previous timeout
        window.clearTimeout($.timeoutID);

        lastSearch = inputString;

        //launch timer using 250ms timeout
        $.timeoutID = window.setTimeout(doSearch, 250, inputString);

    }
} //end

function doSearch() {
    // post data to our php processing page and if there is a return greater than zero
    // show the suggestions box
    //lastSearch = inputString;
    inputString = lastSearch;

    $.post('index.php/suggest/', {
        ss: inputString
    }, function (data) {
        //alert('"'+data+'"');
        indx = -1;
        if (data.toString() == "false") {
            $('#suggestions').fadeOut(100);
            failedSearch = lastSearch;
        } else if (data.length > 0) {
            //$('#autoSuggestionsList').html('<ol>');
            $('#autoSuggestionsList').empty();
            var row_type;
            $.each(data, function (bb) {
                //tag search
                row_type = (bb % 2) ? "odd" : "even";
                if (typeof data[bb] === "string") {
                    $('#autoSuggestionsList').append('<li class="' + row_type + '"><a title="' + data[bb] + '" href="/categories/' + data[bb] + '">' + data[bb] + '</a></li>');
                } else if (data[bb].length > 3){
                    $('#autoSuggestionsList').append('<li class="' + row_type + ' model_result"><a title="' + data[bb][2] + '" href="/pornstar/' + data[bb][0] + '/' + data[bb][3] + '">' + data[bb][1] + '</a><span class="smaller fr">Pornstar</span></li>');
                } else {
                    $('#autoSuggestionsList').append('<li class="' + row_type + '"><a title="' + data[bb][2] + '" href="/search?q=' + data[bb][0] + '">' + data[bb][1] + '</a></li>');
                }
                //console.log(data);
            });
            //$('#autoSuggestionsList').append('</ol>');
            $('#suggestions').fadeIn(100);

        } else {
            $('#suggestions').fadeOut(100);
            failedSearch = inputString;
        }
    }, 'json');

}
// if user clicks a suggestion, fill the text box.
function fill(thisValue) {
    $('#searchInput').val(thisValue);
    //setTimeout("$('#suggestions').fadeOut(100);", 200);
}

if (!Array.indexOf) { //fuck you IE
    Array.prototype.indexOf = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

function formSubmit(form, action, fn, errFn) {
    var err = form.find(".err");
    if (!err.length) {
        err = $("<p></p>").addClass("err");
        form.append(err);
    }
    err.hide();

    var dat = form.serialize();
    var response = $.ajax({
        type: 'POST',
        url: action,
        async: false,
        data: dat,
        cache: false,
        error: function(xhr, text, error){
            if(errFn && (typeof errFn == 'function')) errFn.call();
            else alert('Sorry, the form could not be submitted. '+text+': '+error);
        },
        success: function (res) {
            //res = $(res).find(':span.error').html();
            if (res) {
                err.html(res).show();
                setTimeout(function () {
                    err.slideUp();
                }, 4000);
                form.find('input.txt:first').focus();
            } else {
                if (typeof fn == 'string') {
                    err.html(fn).show();
                } else {
                    fn.call();
                }
            }
        }
    });
    return false;
}

function sec_to_min(val) {
    var t = parseInt(val, 10);
    var time = '';
    var h = Math.floor(t / 3600);
    t %= 3600;
    var m = Math.floor(t / 60);
    var s = Math.floor(t % 60);
    if (h > 0) {
        time += (h + ':');
    }
    if (m < 10) {
        time += '0';
    }
    time += (m + ':');
    if (s < 10) {
        time += '0';
    }
    time += s;
    return time;
}

function initScrubber(thumb, config) {
    config = config || {};
    var $box = thumb;
    var $image = $('.scrub_thumb', $box);
    var $anchor = $image.parent('a');
    var sprite = $image.attr('longdesc');
    var origSource = $image.attr('src');
    var duration = $anchor.attr('rev');
    var jump = duration / config.numImages;
    //var pick = Math.floor(Math.random() * config.numImages + 1);
    //var start = jump * pick;
    var $spriteLoader = $('.sprite_loader', $box);
    var $timewrap = $('.timewrap', $box);
    var $timebox = $('.timebox', $box);
    var $arrow = $('.arrow', $box);
    var $timeline = $('.timeline', $box);
    var $dot = $('.timedot', $timeline);
    var playFromStart = true;
    var spriteLoaded = false;
    var startTime = 0;
    var height;
    var pos;
    var n;
    var k;
    var y = 0;
/*
    if (pick > config.numImages) {
        pick = config.numImages
    }
    if (start > duration) {
        start = duration;
    }
*/
    var buffer = function () {
        if(!spriteLoaded) $spriteLoader.fadeIn('fast').delay(1000).fadeOut('fast')
    };

    var scrub = function (e) {
        startTime = Math.floor(jump * y);
        showScrubber();
        window.clearInterval(k);
        pos = (e.pageX - $timewrap.offset().left) / ($timewrap.width() / config.numImages);
        y = Math.round(pos);
        if (y < 1) y = 1;
        height = (y - 1) * 117;
        $anchor.attr('rel', startTime);
        //console.log($anchor.attr('rel'));
        $image.css('top', '-' + height + 'px');
        $('a', $timebox).text(sec_to_min(jump * pos));
        var x = Math.floor((e.pageX - $timewrap.offset().left));
        if (x < 1) x = 1;
        if (x > 156) x = 156;
        updatePosition(x);
    };

    var updatePosition = function (x) { 
        $('.arrow, .timedot, .timebox', $timewrap).each(function(){
            var $self = $(this);
            var min = x - Math.floor($self.outerWidth() / 2);
            var max = $timewrap.outerWidth() - $self.outerWidth();
            if (min < 0) min = 0;
            if (min > max) min = max;
            $self.css('left', min + 'px');
        });   
    };

/*
    var updateTime = function () {
        var seektime = jump * pick;
        $anchor.attr('rel', start);
        $timebox.text(sec_to_min(seektime));
        var x = Math.floor(pick - $dot.outerWidth() / 2);
        updatePosition(x);
    };
*/

    var showScrubber = function () {
        $timebox.show();
        $arrow.show();
        $dot.show();
        $timeline.css('background', '#f90');
        $('.thumb_container', $box).css('border-color', '#f90');
        //cycle.show();
    };

    var hideScrubber = function () {
        $timebox.hide();
        $arrow.hide();
        $dot.hide();
        $timeline.css('background', '#333');
        $('.thumb_container', $box).css('border-color', '#333');
        //cycle.hide();
    };

    var cycle = function () {
        if (!spriteLoaded) return;
        startTime = Math.floor(jump * y);
        window.clearInterval(k);
        playFromStart = true;
            k = window.setInterval(function () {
                y += 5;
                if (y < 1) {
                    y = 0;
                }
                if (y > 49) {
                    y = 0;
                }
                height = (y) * 117;
                $anchor.attr('rel', startTime);
                $image.css('top', '-' + height + 'px');
            }, 400);
    };

    var loadSprite = function (e) {
        n = window.setTimeout(buffer, 400);
        $image.attr('src', sprite).load(function (e) {
            $spriteLoader.clearQueue().fadeOut('fast');
            window.clearTimeout(n);
            spriteLoaded = true;
            //$image.css("top", "-" + (pick == 0 ? 0 : ((pick) * 117)) + 'px');
            //$anchor.attr('rel', start);
            //updateTime();
            $box.unbind('mouseenter', loadSprite);
            $image.mouseover(cycle).trigger('mouseover');
                        
            $timewrap.bind({
                mouseover: function () {
                    playFromStart = false;
                    window.clearInterval(k);
                },
                mouseleave: function () {
                    hideScrubber();
                },
                mousemove: scrub
            });

        }).each(function () {
            if (!$.browser.msie) return;
            if (this.complete || this.readyState === 4) {
                spriteLoaded = true;
                $(this).load();
            }
        });
    };

    //t = window.setTimeout(loadSprite, 400);
    
    $box.hover(loadSprite, function () {
        $image.unbind('load').css('top', '0').attr('src', origSource);
        $anchor.removeAttr('rel');
        $spriteLoader.clearQueue().fadeOut('fast');
        //window.clearTimeout(t);        
        window.clearTimeout(n);
        window.clearInterval(k);
        $box.mouseenter(loadSprite);
        height = 0;
        y = 0;
        $timewrap.unbind('mouseover, mouseleave, mousemove');
    }).mouseenter();
    
    $('a.fastlink', $box).click(function () {
        $(this).attr('href', function (i, href) {
            return href + '?#t=' + $anchor.attr('rel');
        });
    });

    $('.thumb_click', $box).click(function() {
        if (this.getAttribute('id') != '') document.cookie = 'thumb_click=' + this.getAttribute('id').split('thumb_')[1] + '; path=/; domain=madthumbs.com';
    });

};

/*-- Cookie functions -- modified from script on Bigtits.com --*/

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function clicker(url) {
    createCookie('warned', '1', 360);
    return (true);
}

// return true if this is a network site
function is_network() {

    // check if we have #nowarn flag in the URL
    if (location.href.match(/#nowarn/)) {
        return (true);
    }

    if (document.referrer && document.referrer.length > 0) {
        var ref = document.referrer;
        var a = [];
        a[0] = /sublime/;
        a[1] = /madt/;
        a[2] = /cowlist/;
        a[3] = /teeniefiles/;
        a[4] = /purextc/;
        a[5] = /88by88/;
        a[6] = /bigtits/;
        a[7] = /madteenies/;
        a[8] = /treasurethumbs/;
        a[9] = /youporn/;
        a[10] = /fling/;
        a[11] = /tube/;

        // If from search engines always show the screen
        if (ref.match(/google|yahoo|msn|ask\.com|aol|live|altvista|yandex|baidu|netscape|alltheweb|lycos|mamma/i)) {
            return (false);
        }

        // compare the referrer
        var i;
        for (i = 0; i < a.length; i++) {
            if (ref.match(a[i])) {
                return (true);
            }
        }

        return (true);
    }

    return (false);
}
