// Creates links out of 'dead' JSON return
String.prototype.linkify = function(){
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
        return m.link(m);
    });
};

// Creates link to twitter username
String.prototype.parseUsername = function() {
    return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
        var username = u.replace("@","");
        return u.link("http://twitter.com/" + username);
    });
};

// Create link to twitter search for hashtags
String.prototype.parseHashtag = function() {
    return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
        var tag = t.replace("#","%23");
        return t.link("http://search.twitter.com/search?q="+tag);
    });
};

// Uses JSON returned time stamp to create "human-readable" relative time
function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);
    var r = '';
    if (delta < 60) {
        r = 'a minute ago';
    } else if(delta < 120) {
        r = 'couple of minutes ago';
    } else if(delta < (45*60)) {
        r = (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if(delta < (90*60)) {
        r = 'an hour ago';
    } else if(delta < (24*60*60)) {
        r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if(delta < (48*60*60)) {
        r = '1 day ago';
    } else {
        r = (parseInt(delta / 86400)).toString() + ' days ago';
    }
    return r;
}

// TODO update function to retrieve based on input, i.e. which username or search to use
// Retrieves JSON from twitter and formats for output
function retrieveTweets(){
	var url = "https://twitter.com/status/user_timeline/padandquill.json?count=3&callback=?";
   
    jQuery.ajaxSetup({ cache:true });
	jQuery.getJSON(url, function(json){
        jQuery.each(json, function(index, item){
			console.log(item);
            jQuery('#pandq-self-tweets').append('<li class="tweet"><img src="' + item.user.profile_image_url_https + '" /><strong>' + item.user.screen_name + '</strong><p>' + item.text.linkify().parseUsername().parseHashtag() + '</p><span class="twitter-time">' + relative_time(item.created_at) + '</span></li>');
        });
    });
    
	jQuery('.waiting', '.twitter-block').hide();
}

jQuery(function(){
	// Add "return to top" to box-description
	var origHtml = jQuery('#box-description h2').html();
	jQuery('#box-description h2').html(origHtml + ' <span><a href="#product-links">Return to Top</a></span>');

    // Blog Feed Scroller
    /*jQuery('li','#blog-feed').hide();
    jQuery('li:first-child', '#blog-feed ul').addClass('current-post first').show();
    
    // Pull next blog post
    jQuery('a[rel="next"]', '#blog-feed').click( function(e){
        e.preventDefault();
        jQuery('li.current-post', '#blog-feed').fadeOut('fast', function(){
            if ( jQuery(this).next().length > 0 ){
                jQuery(this).next().addClass('current-post').fadeIn();
            } else {
                jQuery('li:first-child','#blog-feed ul').addClass('current-post').fadeIn();
            }
            jQuery(this).removeClass('current-post').remove().clone().appendTo(jQuery('#blog-feed ul'));
        });
    });
    
    // Pull prev blog post
    jQuery('a[rel="prev"]', '#blog-feed').click( function(e){
        e.preventDefault();
        jQuery('li.current-post', '#blog-feed').fadeOut('fast', function(){
            if( jQuery(this).prev().length > 0 ){
                jQuery(this).prev().addClass('current-post').fadeIn();
            } else {
                jQuery('li:last-child','#blog-feed ul').addClass('current-post').fadeIn();
            }
            jQuery(this).removeClass('current-post').remove().clone().prependTo( jQuery('#blog-feed ul') );
        });
    });*/
	
    // Start pulling tweets
    setTimeout(retrieveTweets,1000);
	
	// Start the slideshow function
    if ( jQuery('#slideshow').length > 0 ) {
        
        /*function loadImages(){
            var slideenchors = jQuery('.slide-anchor', '#slideshow'),
            slideCount = slideenchors.length,
            slideImage = [];
            for( i=0; i<slideCount; i++){
                slideImage = new Image();
                jQuery(slideImage)
                    .attr( 'src', jQuery(slideenchors[i]).attr('name') )
                    .attr( 'alt', jQuery(slideenchors[i]).attr('title') )
                    .attr( 'width', 725 )
                    .attr( 'height', 361 );
                jQuery(slideenchors[i]).append(slideImage);
            }
        }*/

        function createShow(){
            jQuery('#slideshow').after('<ul id="slideshowNav" class="clearfix clear">').cycle({
                speed: 1000,
                timeout: 8000,
                pager: '#slideshowNav',
                pagerAnchorBuilder: function(idx, slide) {
                    var img = jQuery(slide).children().children().eq(0).attr('src'),
					title = jQuery(slide).children().children().eq(0).attr('alt');
                    return '<li><a href="#"><img src="' + img + '" width="100" height="60" /></a><span id="thumb-title">' + title + '</span></li>';
                }
            });
            jQuery('#slideshow').css({"background-image":"none", "overflow":"visible"});
			jQuery('#slideshow-container').animate({ height: '580px'});
        }
        
        //window.setTimeout(loadImages, 500);
        window.setTimeout(createShow, 1000);
	}
    
    // Carousel Function
    if( jQuery('#carousel').length > 0 ){
        var car = jQuery('#carousel'),
        carUL = jQuery('#carousel ul'),
        carULLI = jQuery('li','#carousel ul'),
        liWidth = carULLI.outerWidth('true'),
        step = 3,
        current = 0,
        visible = 9,
        speed = 300,
        max = carULLI.length,
        nextB = jQuery('a[rel="next"]'),
        prevB = jQuery('a[rel="prev"]');

        carUL.width( max * liWidth ).css('left',-(current * max));
        jQuery('li:first', carUL).addClass('active');

        prevB.click(
            function(e)     {
                e.preventDefault();
                if ( current - step < 0 ) {
                    return;
                } else {
                    nextB.removeClass('inactive');
                    current = current - step;
                    carUL.animate({
                        left: -(liWidth * current)
                    }, speed, null);
                    if ( current - step < 0 ) {
                        prevB.addClass('inactive');
                    }
                }
            }
        );
        nextB.click(
            function(e){
                e.preventDefault();
                if ( current + step >= max ){
                    return;
                } else {
                    prevB.removeClass('inactive');
                    current = current + step;
                    carUL.animate({
                        left: -(liWidth * current)
                    }, speed, null);
                    if ( current + step >= max ) {
                        nextB.addClass('inactive');
                    }
                }
            }
        );
            
        carULLI.click( function(e) {
           e.preventDefault();
           jQuery(this).siblings().removeClass('active');
           var newSrc = jQuery(this).addClass('active').children().attr('href');
           jQuery('.product-img-box .product-image img').fadeOut('fast', function(){
               jQuery(this).attr('src', newSrc).fadeIn('100');
           });
        });
    }
    
    if( jQuery('.cms-testimonials ul.testimonial').length > 0 || jQuery('.cms-faq').length > 0 ){
        jQuery('.block-title').click(function(){
           jQuery(this).next().toggle('fast'); 
        });
    }

});


    function checkParent(id){
    	var item = (id == 'is_subscribed' || id == 'subscription')? id : "list["+id+"]";

    	if($(item)){
	    	$(item).checked = true;
	    	$(item).value = 1;
    	}else{
    		if(id == 'is_subscribed'){
	    		checkParent('subscription');
    		}
    	}
    }

    function unCheckGroups(field) {
	    if($(field).select("input").length){
			$(field).select("input").each(function(input, index){
				if(input.type == 'checkbox' || input.type == 'radio'){
					input.checked = false;
				}
			});
		}
		if($(field).select("select").length){
			$(field).select("select").each(function(select, index){
				if(select.type == 'select-one'){
					select.value = select.down('option').value;
				}
			});
		}
   	}

if (!window.Mailchimp) {
    window.Mailchimp = {};
}

Mailchimp.general= {
    initialize: function (element,fieldset) {
		if($(element)){
			this.element = $(element);
			this.fieldset = fieldset;
		    this.onElementMouseClick = this.handleMouseClick.bindAsEventListener(this);
		    this.element.observe('click', this.onElementMouseClick);
		}
    },

    handleMouseClick: function (evt) {
		if(this.element.checked == false)
	        unCheckGroups(this.fieldset);
    },

    hide: function (id) {
		if($(id)){
			this.element = $(id);
			if(this.element.type == 'checkbox' || this.element.type == 'radio'){
				$(id).checked = true;
				this.container = this.element.up('li');
				this.container.hide();
			}
		}
    }
};

