// verblog js code

var verblog = {}

// - - - Comment Preview - - - //

verblog.CommentPreview = Class.create()

verblog.CommentPreview.prototype = {
	DefaultOptions : {
		textarea	: 'commentbox',
		preview		: 'preview'
	},

	initialize : function (options) {
		this.options = Object.extend(
			Object.extend({},this.DefaultOptions), options || {}
		);

		this.textarea = $(this.options.textarea)
		this.preview = $(this.options.preview)

		this.showdown = new Showdown.converter()

		// attach to changes in the commentbox
		this.observer = new Form.Element.Observer(
			this.textarea,
			0.5,
			this.updatePreview.bind(this)
		)
	},

	updatePreview : function () {
		Element.update(
			this.preview,
			this.showdown.makeHtml(Form.Element.getValue(this.textarea))
		)
	}	
}

// - - - Comment Code Generator - - - //

verblog.CommentCode = Class.create()

verblog.CommentCode.prototype = {
	DefaultOptions : {
		codeinput	: 'commentcode',
		waittext 	: 'Please Wait'
	},
	initialize : function (options) {
		this.options = Object.extend(
			Object.extend({},this.DefaultOptions), options || {}
		);

		this.clickedButton = null

		this.input = $(this.options.codeinput)
		this.form = this.input.form

		// get all the submit buttons
		this.buttons = Form.getInputs(this.form,'submit')
		
		this.buttontext = {};

		// attach trackers to each of the submit buttons
		this.buttons.each(function(el){
			el.onclick = this._clickedButton.bind(this,el.name)
			this.buttontext[ el ] = el.value
		}.bind(this))

		// attach ourself to the form
		this.oldsubmit = this.form.onsubmit.bind(this.form)
		this.form.onsubmit = this.submit.bind(this)
	},
	_clickedButton : function(name) {
		this.clickedButton = name
	},
	
	submit : function() {
		/* if (!this.clickedButton || this.clickedButton != 'post') {
			return true
		} */
	
		// -- disable the form -- //
		Form.disable(this.form)

		// -- set our waiting message -- //
		this.buttons.each(function(el){
			el.value = this.options.waittext
		}.bind(this))

		// -- send off our code request -- //

		var req = new Ajax.Request(
			this.options.url,
			{
				method: 'get',
				onComplete : this._insertCode.bind(this)
			}
		)

		// -- return -- //

		return false
	},

	_insertCode : function (req) {
		// -- place code into the form -- //

		this.input.value = req.responseText

		// -- re-enable the form -- //
		Form.enable(this.form)
		
		// -- replace text in buttons -- //
		this.buttons.each(function(el){
			el.value = "Sending"
		}.bind(this))
		
		// -- fire the submit -- //

		if ( this.oldsubmit ) {
			this.oldsubmit()
		} else {
			this.form.submit()
		}		
	}
}

//----------

verblog.NewsroomStoryFX = Class.create()
verblog.NewsroomStoryFX.prototype = {
    initialize : function (id) {
        // save our story id
        this.story = id
        
        var vAcc = new accordion('accordion')
        vAcc.activate($$('#accordion .accordion_toggle')[0]);

        this.activatePhotoDrag()
    },
    activatePhotoDrag : function () {
        // set up sortable on the story photos
        var sort = Sortable.create("story_photos",{
            tag : "div",
            onUpdate : this._updatePhotoOrder.bind(this)
        })        
    },
    _updatePhotoOrder : function (c) {
        new Ajax.Request(
            "/newsroom/story/"+this.story+"/photos/order",{
            parameters : Sortable.serialize(c)
        })
    }
}

//----------

verblog.TipFX = Class.create();
verblog.TipFX.prototype = {
    DefaultOptions : {
        show_ctl: 'tip_form_show',
        hide_ctl: 'tip_form_cancel',
        
        opener: 'tip_opener',
        widget: 'tip_form'
    },
    
    initialize : function(options) {
        this.options = Object.extend(
			Object.extend({},this.DefaultOptions), options || {}
		);
		
		this.show = $( this.options.show_ctl )
		this.hide = $( this.options.hide_ctl )
		
		this.opener = $( this.options.opener )
		this.widget = $( this.options.widget )
		
		if ( this.show && this.hide ) {
		    this.showHandler = this._handleShow.bind(this)
		    this.hideHandler = this._handleHide.bind(this)
		    
		    // attach listener to both to start
		    this.show.observe('click',this.showHandler)
		    this.hide.observe('click',this.hideHandler)
		}
    },
    
    _handleShow : function() {
        // detach show listener to prevent double clicks
        this.show.stopObserving('click',this.showHandler)
        
        new Effect.BlindUp(this.opener,{
            afterFinish : function () {
                new Effect.Grow(this.widget,{ afterFinish : function () {
                    this.show.observe('click',this.showHandler)
                }.bind(this),direction: "top-left"});                
            }.bind(this)
        })
        
    },
    
    _handleHide : function() {
        this.hide.stopObserving('click',this.hideHandler)
        
        new Effect.BlindUp(this.widget,{ afterFinish : function () {
            new Effect.BlindDown(this.opener,{ afterFinish : function () {
                this.hide.observe('click',this.hideHandler)
            }.bind(this)})            
        }.bind(this)});
    }
}

//----------

// ActiveContent handles the Active Stories / Recent Comments widget
verblog.ActiveContent = Class.create();
verblog.ActiveContent.prototype = {
    DefaultOptions : {
        tabs : ['rc_stories','rc_comments'],
        dvalue : 1,
        cookie : "verblog_activeContent"
	},

	initialize : function (options) {
		this.options = Object.extend(
			Object.extend({},this.DefaultOptions), options || {}
		);
		
		this.options.tabs.each(function(id,idx) {
		    Event.observe(id+"_c","click",this._clickedTab.bind(this,id,idx))
		}.bind(this))
		
		// set one visible
		
		var init = Cookie.get(this.options.cookie) || this.options.dvalue
		this._clickedTab(this.options.tabs[init-1],init-1)
	},
	
	_clickedTab : function (tab,idx) {
	    // turn everyone off
	    this.options.tabs.each(function(id) {
	        $(id).hide()
	        $(id+"_c").removeClassName('active')
	    })
	    	    
	    // turn ours on
	    $(tab).show()
	    $(tab+"_c").addClassName('active')
	    
	    // set a cookie
	    Cookie.set(this.options.cookie,idx+1,86400)
	}
}

//----------

verblog.UserPhotos = Class.create()
verblog.UserPhotos.prototype = {
    DefaultOptions : {
        finder: '#user_photos_thumbs img',
        load : 'user_photos_load',
        pop : 'user_photos_pop',
        
        nprev: 'user_photos_prev',
        nnext: 'user_photos_next'
    },
    
    initialize : function(options) {
        this.options = Object.extend(
			Object.extend({},this.DefaultOptions), options || {}
		);
		
		this.load = $( this.options.load )
		
		this.count = 0
		this.current = null
		
		this.handlers = []
		
		var i = 0
		
		// attach to each image in the thumbs div
		$$(this.options.finder).each(function(img) {
		    //console.info('got img: ',img)
		    
		    var handler = this._handleImgClick.bind(this,img,img.parentNode.href,i)
		    img.observe('click',handler)
		    
		    this.handlers[i] = handler
		    
		    // update counters
		    this.count++
		    i++
		    
		    // replace the normal href
			img.parentNode.href = 'javascript:void(0)'
		}.bind(this))
	},
	
	_handleImgClick : function(img,href,i) {
	    //console.warn('got click for ',i,href)
	    
	    this.current = i
	    
	    new Ajax.Updater(
			this.load,
			href,
			{
			    method : "GET",
				asynchronous : true,
				evalScripts : true,
				onComplete : function(req) {
				    this._activateNavLinks()
					RedBox.addHiddenContent(this.load)
					
					// logging
					//Mint.TT.behavior.record("galleryView",href)
					gUrl = href.match(/(\/[^\/]+)$/)
					
					if (gUrl) {
					    //console.warn('logging for ' + window.location.pathname + gUrl[1])
    					pageTracker._trackPageview(window.location.pathname + gUrl[1])					    
					}
				}.bind(this),
				onLoading : function() {
					RedBox.loading()
				}
			}
		)
	},
	
	_activateNavLinks : function() {
	    var nprev = $(this.options.nprev)
	    var nnext = $(this.options.nnext)
	    
	    if ( nprev && this.current > 0 ) {
	        // add prev link
	        //console.info("adding prev link")
	        nprev.observe("click",this._handlePrevClick.bind(this))
	        nprev.show()
	    } else {
	        $(this.options.nprev).hide()	        
	    }
	    
	    if ( nnext && this.current < (this.count-1) ) {
	        // add next link
	        //console.info("adding next link")
	        nnext.observe("click",this._handleNextClick.bind(this))
	        nnext.show()
	    } else {
	        $(this.options.nnext).hide()
	    }
	},
	
	_handlePrevClick : function() {
	    // run the handler for current - 1
	    if ( this.current > 0 ) {
	        this.handlers[ this.current - 1 ]()
	    }
	},
	
    _handleNextClick : function() {
        // run the handler for current + 1
        if ( this.current < (this.count - 1) ) {
	        this.handlers[ this.current + 1 ]()
	    }
    }
	
}

// cookie code from prototype-tidbits
// http://livepipe.net/projects/prototype_tidbits/

/**
 * Tidbit : Cookie
 */

var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			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
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}

1;

