/**
 * @author braynej
 */
 
/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
} 
 

var Application = Class.create();
 
Object.extend(Application.prototype, {
 	
	version: 0.1,
	
	initialize: function(){
		this.kkeys = [];
		this.konami = "38,38,40,40,37,39,37,39,66,65";
		this.currentTrack = null;
		this.currentPage = 'home';
		this.audioLoaded = false;
		this.g = {};
		this.submitted = false;
		this.feedAPIkey = "ABQIAAAAoKpoOGY7pc1FI0TRsK5xDRQ-ziT8xP17h8NdDWljRNrqzNxaXxQeVBYCeUvHLerplIe648JlufJ1Mw";
	},
	
	fetchComments: function(){
		var params = {};
		params.url = 'lib/php/fetchComments.php';
		params.onSuccess = app.setComments;
		app.request(params);
	},
	
	getsong: function(form){
		if(app.validate(form)){
			var params = {};
			params.params = $(form).serialize(true);
			params.url = 'lib/php/getsong.php';
			params.onSuccess = function(res){
				var msg = "<p>Thank you for downloading our new song! Look in your inbox shortly for the link to download the song.</p>";
				app.g.info(msg, {
					header: "Go get your song!",
					life: 15
				});
				$('getsong').update();
			};
			app.request(params);
		}
	},
	
	gup: function( name ){
		var name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return false;
		else
			return results[1];
	},
	
	loadMore: function(blurb, content){
		$('story').update(content);
		$('button_story').observe('click', function(){
			app.loadLess(blurb, content);
		});
	},
	
	loadLess: function(blurb, content){
		$('story').update(content);
		$('button_story').update('Read Less...');
		$('button_story').observe('click', function(){
			app.loadMore(blurb, content);
		});
	},
	
	loadBlog: function(title, id){
		var feed = new google.feeds.Feed("http://jeffreybrayne.blogspot.com/feeds/posts/default");
		feed.load(function(result) {
			if (!result.error) {
			    var container = document.getElementById("feed");
			    for (var i = 0; i < result.feed.entries.length; i++) {
			    	var entry = result.feed.entries[i];
			    	var div = new Element('div', {className: 'box newsitem'});
			    	var h3 = new Element('h3').update(entry["title"]);
			    	var h4 = new Element('h4').update("Author: " + entry["author"]);
			    	var link = new Element('p').update(new Element('a', {href: entry["link"]}).update('Link to Story'));
			    	var story = new Element('div', {id: "story"});
			    	var blurb = new Element('div').update(entry["contentSnippet"]);
			    	var content = new Element('p').update(entry["content"]);
			    	var pubdate = new Element('p').update("Published: " + entry["publishedDate"]);
			    	//var more = new Element('button', {id: "button_story"}).update("Read More...");
			    	//more.observe('click', function(){
			    	//	app.loadMore(blurb, content);
			    	//});
			    	div.insert(h3);
			    	div.insert(h4);
			    	div.insert(link);
			    	div.insert(pubdate);
			    	div.insert(story.update(content));
			    	//div.insert(more);
			        container.appendChild(div);
			    }
			}

		});
	},
	
	navigate: function(e){
		var link = e.target.id;
		if(app.currentPage !== link) $(app.currentPage).toggleClassName('hot');
		//app.setContent(link);
		new Effect.Fade('content', {
			duration: 0.3,
			afterFinish: function(){
				var div = app.currentPage + "wrapper";
				$(div).setStyle({display: 'none'});
				app.setContent(link);			
			}		
		})
		/*if(link !== app.currentPage){
			$(app.currentPage).toggleClassName('hot');
			if(app.currentPage === 'home'){
				new Effect.Move($('icons'), {
					x: 1920,
					y: 0,
					duration: 0.3,
					afterFinish: function(){
						new Effect.Fade('homewrapper', {
							afterFinish: function(){
								app.setContent(link);
							},
							duration: 0.1
						});
					}
				});
			}else{
				app.setContent(link);
			}
		}*/
	},
		
	request: function(params){

		new Ajax.Request(params.url, {
			method: params.method || 'POST',
			evalJS: params.evalJS || false,
			evalJSON: params.evalJSON || false,
			parameters: params.params || null,
			onLoading: params.onLoading || null,
			onSuccess: params.onSuccess || function(res){ window.status = res.status },
			onFailure: params.onFailure || function(){ }, //Controller.onFailure(); },
			onComplete: params.onComplete || null
		});
	},
	
	resetForm: function(form){
		Form.reset(form);
	},
	
	run: function(hotlink){
		//this.setLinks();
		this.g = new k.Growler({location: 'br'});
		$(hotlink).addClassName('hot');
		/* konami code easter egg */
		/*document.observe('keydown', function(e) {
			app.kkeys.push( e.keyCode );
			if (app.kkeys.toString().indexOf( app.konami ) >= 0 ){
				document.stopObserving('keydown',arguments.callee);
				$('wrapper').setStyle({display: 'none'});
				$('header').setStyle({display: 'none'});
				$('footer').setStyle({display: 'none'});
			}
		});
		var e = {target: {id: "home"}};
		this.navigate(e);*/
	},
	
	setComments: function(response){
		$('innerComments').update();
		var response = response.responseText.evalJSON();
		response.each(function(res){
			var comment = new Element('div', {
				className: 'commentContainer'
			});
			
			var user = new Element('p', {
				className: 'comment_username'
			});

			user.insert('<a href="' + res.email + '">' + res.username + '</a> said @ ' + res.timestamp);
			var text = new Element('p', {
				className: 'comment'
			});
			text.update(res.comment);
			comment.insert(user);
			comment.insert(text);
			comment.insert(new Element('hr'))
			$('innerComments').insert(comment);
		});
	},
	
	setContent: function(id){
		var id = id;
		$(id).toggleClassName('hot');
		var div = id + 'wrapper';
		$(div).setStyle({display: "block"});
		app.currentPage = id;
		new Effect.Appear('content', {
			duration: 0.3
		});
	},
	
	setLinks: function(){
		$$('.link').each(function(link){
			link.observe('click', app.navigate);
		});
	},
	
	stripslashes: function(str) {
        str=str.replace(/\\'/g,'\'');
        str=str.replace(/\\"/g,'"');
        str=str.replace(/\\\\/g,'\\');
        str=str.replace(/\\0/g,'\0');
        return str;
    },
    
    subscribe: function(form){
		if(app.validate(form) && !app.subscribed){
			var params = {};
			params.params = $(form).serialize(true);
			params.url = 'lib/php/subscribe.php';
			params.onSuccess = function(res){
				app.subscribed = true;
				var res = res.responseText.evalJSON();
				var msg = "<p>You've subscribed with the following information:</p>";
				msg += "<ul><li>Name: " + res.first_name + "</li>";
				msg += "<li>Email: " + res.email + "</li></ul>";
				msg += "<p>If these are not correct, please click <a style='cursor: pointer;' onclick='app.deleteUser(" + res.id + ", \"" + res.email + "\");'>here</a> and try again!</p>"
				app.g.info(msg, {
					header: "You've Subscribed Successfully!",
					life: 15
				});
				app.resetForm('mailerForm');
			}
			app.request(params);
		}else{
			app.g.error("You have already subscribed...", {
				header: "Already Subscribed!",
				life: 15
			});
			app.resetForm('mailerForm');
		
		}
		
	},
	
	submitComment: function(form){
		if(app.validate(form) && !app.submitted){
			var params = {};
			params.params = $(form).serialize(true);
			params.url = 'lib/php/submitComment.php';
			params.onSuccess = function(res){
				app.submitted = true;
				var res = res.responseText.evalJSON();
				var msg = "<p>Thank you for your comment " + res.username + "!</p>";
				app.g.info(msg, {
					header: "Comment Submitted!",
					life: 15
				});
				app.resetForm('commentForm');
				app.fetchComments();
				
			}
			app.request(params);
		}else{
			app.g.error("You have already submitted a comment. Thank you!...", {
				header: "Already Submitted Comment!",
				life: 15
			});
			app.resetForm('commentForm');
		}
		
	},
	
	submitform: function(form){
		if(app.validate(form)){
			var params = {};
			params.params = $(form).serialize(true);
			params.url = 'lib/php/submitform.php';
			params.onSuccess = function(res){
				//app.submitted = true;
				var res = res.responseText.evalJSON();
				if(res.success === 'true')
					$(res.target).update(res.msg);
				else
					app.g.error(res.msg, {header: "Error with your submission", life: 15});
			}
			app.request(params);
		}		
	},
	
	updater: function(params){
		/**
		 * @description generic interface into Ajax.Updater();
		 */
		var div = params.div || 'content';
		new Ajax.Updater(div, params.url, {
			method: params.method || 'POST',
			parameters: params.params || null,
			evalScripts: params.evalScripts || false,
			onLoading: params.onLoading || null,
			onSuccess: params.onSuccess || null,
			onFailure: params.onFailure || function(){},
			onComplete: params.onComplete || null
		});
	},
	
	validate: function(form){
		var required = $$("#" + form + ' .required');
		var validate = $$("#" + form + ' .validate');
		var msg = [];
		var me = this;
		required.each(function(field){
			if($(field).value==''){
				msg.push($(field).name.replace('_', ' ').toUpperCase() + " is Required");
			}else if($(field).readAttribute('datatype')){
				var err = me.validateForm($(field).readAttribute('datatype'), $(field).value);
				if(err) msg.push(err);
			}
		});
		validate.each(function(field){
			if($(field).readAttribute('datatype') && $(field).value!=''){
				var err = me.validateForm($(field).readAttribute('datatype'), $(field).value);
				if(err) msg.push(err);
			}
		});
		if (msg.length > 0) {
			app.g.error(msg.join('\n'), {
				header: "Error!",
				life: 60
			});
            return false;
		}else{
            return true;
        }
	},
	
	validateForm: function(datatype, value){
		var error = "";
		switch(datatype){
			case 'alnum_space':
				var filter = /[0-9a-zA-Z\ \.]/;
				if(!(filter.test(value))){
					error = "You must use only characters or numbers";
				}
				break;
			case 'alnum':
				var filter = /[0-9a-zA-Z]/;
				if(!(filter.test(value))){
					error = "You must use only characters or numbers";
				}
				break;
			case 'alpha_space':
				var filter = /[a-zA-Z\ ]/;
				if(!(filter.test(value))){
					error = "You must use only characters or spaces";
				}
				break;
			case 'alpha':
				var filter = /[a-zA-Z]/;
				if(!(filter.test(value))){
					error = "You must use only characters";
				}
				break;
			case 'digits':
				var filter = /[0-9]/;
				if(!(filter.test(value))){
					error = "You must use only numbers";
				}
				break;
			case 'email':
				var emailFilter= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;   ///^.+@.+\..{2,3,4,6}$/;
				if (!(emailFilter.test(value))) {
					error = "Please enter a valid email address.";
				}
				var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
				if (value.match(illegalChars)) {
					error = "The email address contains illegal characters.";
				}
				break;
			case 'phone':
				var stripped = value.replace(/[\(\)\.\-\ ]/g, '');
				//strip out acceptable non-numeric characters
				if (isNaN(parseInt(stripped))) {
					error = "The phone number contains illegal characters.";
				}
				if (!(stripped.length == 10)) {
					error = "The phone number is the wrong length. Make sure you included an area code.";
				}
				break;
            case 'phone_3':
                if(isNaN(value)){
                    error = "The phone number must be digits only";
                }
                if(value.length < 3){
                    error = "You must have at least three digits for this part of the phone number";
                }
                break;
             case 'phone_4':
                if(isNaN(value)){
                    error = "The phone number must be digits only";
                }
                if(value.length < 4){
                    error = "You must have at least three digits for this part of the phone number";
                }
                break;
			case 'dropdown':
			    if (value == '') {
			       error = "You didn't choose an option from the drop-down list.";
			    }
				break;
			case 'date':
				var re = /(^\d{4}\-\d{1,2}\-\d{1,2}$)/;
				if(!(re.test(value))) {
					error = "Please enter a valid date: YYYY-MM-DD";
				}
				break;
			case 'zip':
				var zipExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
				if (!(zipExp.test(value))) {
					error = "Please enter a valid zip code.";
				}
				break;
			default:
				error = false;
		}

		return error;
	},
	
	vote: function(){
		var vote = $RF('voteform', 'vote');
		if(vote === null){
			alert("You must choose a song!");
		}else{
			var params = {};
			params.url = "lib/php/vote.php";
			params.params = {song: vote};
			params.onSuccess = function(res){

				var res = eval(res.responseText);

				$$("#voteform ul li input").each(function(obj){
					obj.remove();
				});

				res.each(function(song){
					var span = new Element('span', {'class': 'votetally'}).update(song.count);
					$(song.title).update(span);
				});	
				$("submit").update("Thank you for voting!");	
			};
			app.request(params);
		}
	}
	
});