/*******************************************************************************************************
CLEAR FIELD
********************************************************************************************************/
var ClearField = new Class({
	initialize : function(inputField, defaultText, newClass) {
		this.inputField = $(inputField);
		this.defaultText = defaultText;
		if (newClass) {
			this.newClass = newClass;
		}
		this.inputField.addEvent('focus', this.enter.bind(this) );
		this.inputField.addEvent('blur', this.leave.bind(this) );		
	},
	enter : function() {
		if (this.inputField.value == this.defaultText) {
			this.inputField.value = '';		
			if (this.newClass) {
				this.inputField.addClass(this.newClass);			
			}
		}
	},
	leave : function() {
		if (this.inputField.value == '') {		
			this.inputField.value = this.defaultText;		
			if (this.newClass) {			
				this.inputField.removeClass(this.newClass);						
			}
		}
	}							   
});


/*******************************************************************************************************
PHONE NUMBER
********************************************************************************************************/
var phoneNumber = {
	element : null,
	init : function(elem) {
		phoneNumber.element = $(elem);
	},
	toggle : function() {
		phoneNumber.element.toggleClass('hidden');			
	}
};
/*******************************************************************************************************
	RATING
********************************************************************************************************/
var Rating = new Class({
	
	initialize : function(container, currentContainer, textContainer) {
	    this.changeText = false;
		
		this.container = $(container);
		this.currentContainer = $(currentContainer);
		if (textContainer) {			
			this.textContainer = $(textContainer);
			this.changeText = true;
		}

		this.defaultWidth = this.currentContainer.getStyle('width');
	
		// Set a flag to determine if this has already been rated
		this.rated = false;
		this.titleRated = 'Thanks for rating';
		this.titleAttempt = 'You have already rated this place';
		// Create an array of possible titles
		this.titles = ['No Good','Passible','Worth Trying','Great','A Fave!'];
		this.ratingWidths = ['0','20%','40%','60%','80%','100%'];
		
		// Grab the existing title
		if (this.changeText) {
			this.curTitle = this.textContainer.get('text');
		}
		
		this.container.addEvent('mouseenter', this.hideDefault.bind(this));
		this.container.addEvent('mouseleave', this.showDefault.bind(this));		
		
		this.container.getElements('li a').each(function(item,index) {
			item.addEvent('mouseenter',this.showRating.pass(index+1,this));
			item.addEvent('click',this.setRating.pass(index+1,this));
		}.bind(this));	
		
		// Set a flag to determine if the default is visible
		this.defaultVisible = false;
	},
	
	setRating : function(num) {
	    if(!VerifyUser()){
	        RedirectLogin();
	        return;
	    }
		if (!this.rated) {
			this.defaultWidth = this.ratingWidths[num];
			this.currentContainer.setStyle('width',this.defaultWidth);

			if (this.changeText) {
				this.curTitle = this.titleRated;
			}
			
			this.showDefault();
			this.rated = true;
			
			if(this.container.id == 'main_rating')
			    SetRating(num);
			else
			    SetRating2(num);
		}
	},
	
	showRating : function(num) {
		if (!this.rated) {		
			if (this.defaultVisible) {
				this.hideDefault();
			}
			this.currentContainer.setStyle('width',this.ratingWidths[num]);		
			if (this.changeText) {
				this.textContainer.set('text',this.titles[num-1]);
			}
		}
	},
	hideDefault : function() {
		if (!this.rated) {
			if (this.defaultVisible) {
				this.currentContainer.setStyle('width','0');
				this.defaultVisible = false;
			}
		}
		else
		{
			if (this.changeText) {			
				this.textContainer.set('text',this.titleAttempt);
			}
		}			
	},
	showDefault : function() {
		if (!this.rated) {
			this.currentContainer.setStyle('width',this.defaultWidth);
			if (this.changeText) {			
				this.textContainer.set('text',this.curTitle);		
				
			}
			this.defaultVisible = true;			
		}
		else
		{
			if (this.changeText) {			
				this.textContainer.set('text',this.curTitle);
			}
		}		
	},
	
	clearRating : function() {
		if (!this.rated) {
			//console.log('clear');
			this.currentContainer.setStyle('width', 0); 
		}		
	},
		
	setTitle : function(num) {
		if (!this.rated) {
			if (this.changeText) {			
				this.textContainer.set('text',this.titles[num]);
			}
		}
	},
	
	resetTitle : function() {
		if (!this.rated) {
			if (this.changeText) {			
				this.textContainer.set('text',this.curTitle);
			}
		}
	}
});


/*******************************************************************************************************
	
	TABS
	
********************************************************************************************************/
var tabs = {						
	
	arrTabs : [],
	arrPanels : [],
	
	init : function(tabElems, panelElems) {
			
		tabs.arrTabs = $$(tabElems);
		tabs.arrPanels = panelElems;		
		
		// Iterate through tabs
		tabs.arrTabs.each(function(item, index) {
								   
			// Add a click event to each tab
			item.addEvent('click', function() {
			
				// Clear all tab selected classes
				tabs.clear();
	
				// Add a selected class to the current tab
				item.addClass('selected');										
	
				// Set the current panel
				tabs.arrPanels[index].setStyle('display','block');
			})
		});
	},
	
	clear : function() {
		// Clear all tab selected classes
		tabs.arrTabs.removeClass('selected');
		
		// Clear all panels
		$$(tabs.arrPanels).setStyle('display', 'none');
	},
	
	showTab : function(index) {
		tabs.clear();
		tabs.arrTabs[index].addClass('selected');
		tabs.arrPanels[index].setStyle('display','block');		
	}	
}

/*******************************************************************************************************
	
	REPLIES
	
********************************************************************************************************/
var replies = {
	
	toggle : function(elem, linkElem) {

		element = $(elem);		
		element.toggleClass('hidden');
		
		linkElement = $(linkElem);
		linkElement.toggleClass('active');
	}		
}


/*******************************************************************************************************
	
	TAG
	
********************************************************************************************************/
var tag = {
	
	tagValue : null,
	
	init: function() {
										
	},
	
	add: function() {
        if(!place.rated){
            tag.ratePlaceError();
            return;
        }
		tag.tagValue = $('add_tag').value;
		
		if (tag.tagValue) {
		    SaveFaveTag(tag.tagValue, place.reviewID, null);
		    $('add_tag').value = "";
		}
		$('add_tag_error').addClass('hidden');
	},
	
	addNewTag: function(idValue) {
	    $('add_tag_error').addClass('hidden');
		var newLi = new Element('li', {'id':idValue});
		var newTagSpan = new Element('span');												
		newTagSpan.appendText(tag.tagValue);
		var newCountSpan = new Element('span');
		newCountSpan.appendText('1');												
		newLi.grab(newTagSpan);							
		newLi.appendText(' (');
		newLi.grab(newCountSpan);
		newLi.appendText(')');																																	
		$('list_tags').grab(newLi);
	},
	increaseCount: function(elem) {
        if(!place.rated){
            tag.ratePlaceError();
            return;
        }
        $('add_tag_error').addClass('hidden');
		tag.tagValue = $(elem).getElement('a').get('text');
		SaveFaveTag(tag.tagValue, place.reviewID, elem);																																																		
	},
	updateTagCount: function(m, elem) {
		msg = m.split(";");
		if(elem == null){
		    elem = $('tag_' + msg[1]);
		    if(elem != null){
		         elem = 'tag_' + msg[1] ;
		    }
		}
		
		if(elem){
		    elemTagCount = $(elem).getElement('span');
		    tagCount = elemTagCount.get('text');												
		    tagCount.toInt();												
		    tagCount++;
		    elemTagCount.set('text', tagCount);
    	}
    	else{
    	     tag.addNewTag(tag.tagValue, 'tag_' + msg[1]);
    	}																						
	},											
	updateError: function (){
	    $('add_tag_error').removeClass('hidden');
	    $('add_tag_error').innerHTML = '<p>You have already selected this item.</p>';
	},
	ratePlaceError: function (){
        $('add_tag_error').removeClass('hidden');
        $('add_tag_error').innerHTML = '<p>Please rate this place first before continuing</p>';
	}											
}


/*******************************************************************************************************
	
	PLACE
	
********************************************************************************************************/
var Place = new Class({
		
	initialize : function(id) {
		this.reviewID = id;
		if(this.reviewID == ''){
		    this.rated = false;
		}
		else{
		    this.rated = true;
		}
	},
	
	rateMain : function(m) {
		// Set rated flag to true
		msg = m.split(";");
		if(msg[0] == 'SUCCESS'){
		    place.reviewID = msg[1];
		    place.rated = true;
            this.rated = true;
            this.reviewID = msg[1];
            
		    // Prompt user to enter tags
		    $("place_more_details_1").addClass('hidden');
		    $("place_more_details_2").removeClass('hidden');
		}	
		else{alert("Unable to process request.");}	
	},

	rateReview : function() {
		// Set rated flag to true
		this.rated = true;
	},
	
	showTags : function() {
	    if(!VerifyUser()){
            RedirectLogin();
            return;
         }
		$("place_more_details_1").addClass('hidden');
		$("place_more_details_2").removeClass('hidden');		
	},
	
	addTags : function() {
		$("place_more_details_2").addClass('hidden');
		$("place_more_details_3").removeClass('hidden');
	},
	
	addTribes : function() {
	    
		$("place_more_details_3").addClass('hidden');		
		$("place_more_details_1").removeClass('hidden');		
		
		// Init a list variable
		var whoList = '';
		
		$$('ul.list_who_enjoy li input').each(function(item){
			if (item.checked) {			
				// Don't add a comma if it's the first value
				if (whoList) {
					whoList += ';';
				}
				whoList += item.getProperty('value');
			}
		});
		if(VerifyUser()){
		    SaveGroup(whoList);
		}
		// Ensure the proper tab is open
		tabs.showTab(0);		
	},
	
	previewReview : function() {
		$("write_review").addClass('hidden');
		$("preview_review").removeClass('hidden');		
	},
	
	postReview : function() {
	   	$('write_review_error').addClass('hidden');
		var reviewTitle = $("review_title").value;
		var reviewMessage = $("review_message").value;
		if(reviewMessage != '' && reviewTitle != ''){
		    if (!this.rated) {
			    $("rate_review").removeClass('hidden');	
			    $("write_review").addClass('hidden');				
		    }
		    else{
		        SaveReview(reviewTitle, reviewMessage);
		    }
		}else{
		    $('write_review_error').removeClass('hidden');
		    $('write_review_error').innerHTML = "<p>We're sorry, but you must fill in both fields.</p>";
		}
	},
    postReview2 : function(m) {
		msg = m.split(";");
		if(msg[0] == 'SUCCESS'){
		    place.reviewID = msg[1];
		    place.rated = true;
            this.rated = true;
            this.reviewID = msg[1];    
            SaveReview($("review_title").value, $("review_message").value);
        }
	},
	editReview : function() {
		$("write_review").removeClass('hidden');
		$("preview_review").addClass('hidden');				
	},	
	
	rateConfirm : function() {
		$("rate_review").addClass('hidden');
		$("write_review").removeClass('hidden');
		// Move to post
	},
	saveResponse : function (m){
	    $("write_review").addClass('hidden');	
	    $("rate_review").addClass('hidden');
	    $("upload_image").removeClass('hidden');
	},
	saveError : function (m){
	    alert("ERROR " + m);
	}
})
	
/*******************************************************************************************************
	
	STICKY SEARCH
	
********************************************************************************************************/
var StickyModule = new Class({
		
	initialize : function(el) {
		this.el = el;
		this.elTopPos = el.getPosition().y;
		this.maxScrollPos = 527;
		this.scrollSize = window.getScrollSize().y;
		this.elHeight = el.getSize().y;
		this.stuck = false;
		this.fixedBottom = false;
				
		window.addEvent('scroll', this.testSticky.bind(this));
	},
	
	testSticky : function() {
		scrollPos = window.getScroll().y;
		if (scrollPos >= this.elTopPos) {
			if(scrollPos > (this.scrollSize - this.maxScrollPos - this.elHeight)) {
				this.fixBottom();		
			}
			else {
				this.stick();
			}			
		}
		else {
			this.unstick();	
		}
	},
	
	stick : function() {
		
		if (Browser.Engine.trident && Browser.Engine.version < 7) {
			scrollPos = window.getScroll().y;
			this.el.setStyles({
				'position':'absolute',
				'top': scrollPos - 472,
				'z-index': 5,
				'bottom':''
			})
			this.fixedBottom = false;
			this.stuck = true;
		}
		else {
			if(! this.stuck) {	
				this.el.setStyles({
					'position':'fixed',
					'top': 0,
					'z-index': 5,
					'bottom':''
				})
				this.fixedBottom = false;
				this.stuck = true;
			}
		}
		
	},
	
	fixBottom : function() {		
		if(! this.fixedBottom) {
			this.el.setStyles({
				'position':'absolute',
				'bottom': (($$('.content_right').getCoordinates()[0].top + $$('.content_right')[0].getCoordinates().height) - (this.scrollSize - this.maxScrollPos)) + 'px',
				'top':'',
				'z-index': 5
			});
			this.fixedBottom = true;
			this.stuck = false;
		}
	},
	
	unstick : function() {
		if(this.stuck) {
			this.el.setStyles({
				'position':'static'
			})
			this.stuck = false;
		}
	}
});

/*******************************************************************************************************
CORE
********************************************************************************************************/

function SetRating (r){
    w.SaveRating(r, ID, place.rateMain, callback);
}
function SetRating2 (r){
    w.SaveRating(r, ID, place.postReview2, callback);
}

function callback(r){
    alert("There was an error processing that request, please try again later. " + r._message);
}

function SaveFaveTag (t, r, e){
    w.SaveFaveTag(ID, r, t, tag.updateTagCount, tag.updateError, e);
}

function SaveReview (review, title){
    w.SaveReview(place.reviewID, review, title, place.saveResponse, place.saveError, null);
}

function SaveUseful (r){
    if(!VerifyUser()){
	    RedirectLogin();
	    return;
	}
    w.RateReview(r,SaveUsefulR, callback, r);
}

function SaveGroup(g){
	if(!VerifyUser()){
	    RedirectLogin ();
	    return;
	}
    w.SaveGroup (ID, g)
}

var homeSearch = {
    cID:'-1',
    nID:'-1',
    gID:'-1',
    Initialize:function (){
        cID = '-1';
        nID = '-1';
        gID = '-1';
    },
    Search:function (c,n,g,cL,nL,gL,sID){
        var cLabel = $('CategoryLabel').innerHTML;
        var nLabel = $('NeighbourhoodLabel').innerHTML;
        var gLabel = $('GroupLabel').innerHTML;
        if (c != '-1')
        {
            homeSearch.cID = c;
            cLabel = cL;
            $('CategoryLabel').innerHTML = cL.toLowerCase();
        }
        if (n != '-1')
        {
            homeSearch.nID = n;
            nLabel = nL;
            $('NeighbourhoodLabel').innerHTML = nL.toLowerCase();
        }
        if (g != '-1')
        {
            homeSearch.gID = g;
            gLabel = gL;
            $('GroupLabel').innerHTML = gL.toLowerCase();
        }
        w.HomeSearch(homeSearch.cID, homeSearch.nID, homeSearch.gID, cLabel, nLabel, gLabel, sID, homeSearch.RenderHomeSearch);
    },
    RenderHomeSearch:function (r){
        $('sort_results').innerHTML = r;
    },
    SearchFail : function (m){
        alert(m + " FAIL")    
    }
}

function SaveUsefulR (r, c, m){
    if(r >= 1){
        el = $("u_" + c);
        ct = el.get('text');												
		ct.toInt();												
		ct++;
        $("u_" + c).set('text', ct);
    }
}

function VerifyUser (){
    if(UserKey == ''){
        return false;
    }
    return true;
}

function SaveFollowing(u){
    if(!VerifyUser()){
	    RedirectLogin();
	    return;
	}
    w.SaveFollowing (u, FollowingComplete, FollowingComplete); return false;
}
function StopFollowing(i){w.StopFollowing(i, StopFollowingComplete, StopFollowingComplete, i); return false;}
function FollowingComplete (r){
    if(r == 'SUCCESS'){
        var f = $('followersCount').get('text');
        f = f.toInt() + 1;
        $('followersCount').set('text', f);
    }
    else{
        alert("There was an error processing that request, please try again later. " + r);
    }
}
function StopFollowingComplete (r, c, m){
    if(r == 'SUCCESS'){
        $('f_' + c).dispose();
    }
    else{
        alert("There was an error processing that request, please try again later.");
    } 
}

function RunSearch (url, query, near){
    var cQuery = document.getElementById(query).value;
    var cNear = document.getElementById(near).value;
    if (cQuery == 'something like... "pizza," or "restaurants"')
    {
        cQuery = '';
    }
    else
    {
        cQuery = '?q=' + cQuery;
    }
    if (cNear == 'somewhere like "Toronto, Ontario"')
    {
        cNear = '';
    }
    else if (cQuery.length > 0)
    {
        cNear = "&a=" + cNear;
    }
    else
    {
        cNear = "?a=" + cNear;
    }
    
    document.location.href = url + cQuery + cNear;
    return false;
}

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

function limitCreation () {
    RedirectLogin();
    $("write_review_error").innerHTML = "<p>Please Login to Continue...It is quick and easy!</p>";
    $('write_review_error').removeClass('hidden');
}

function FireDefaultButton(event, target) 
{
    var element = event.target || event.srcElement;
    if (13 == event.keyCode && !(element && "textarea" == element.tagName.toLowerCase())) 
    {
        var b;
	    b = $(target);
        event.cancelBubble = true;
        if(event.stopPropagation)
	    event.stopPropagation();
	    b.onclick();
   	    return false;
    }
    return true;
}  

function SaveListUseful (l){
    if(!VerifyUser()){
        RedirectLogin();
        return;
    }
    w.RateList(l, true, SaveUsefulList, callback, l);
}
function SaveListNotUseful (l){
    if(!VerifyUser()){
        RedirectLogin();
        return;
    }
    w.RateList(l, false, SaveUsefulList, callback, l);
}

function SaveUsefulList (r, c, m){
    var message = r.split("|");
    if(message != ''){
        $("details").set('text', message[0] + " Likes | " + message[1] + " Dislikes");
    }
    else{
        $("details").set('text', "Please login...");
        RedirectLogin ();
    }
}

function GetUserLists (){
    if(!VerifyUser()){
        RedirectLogin();
        return;
    }
    else if (place.reviewID == ''){
        alert("Pleae add a review first...");
        return;
    }
    else {
        w.GetUserLists (place.reviewID, SiteID, GetUserListsReturn, callback, '');
    }
}

function GetUserListsReturn (r){
    $("add_to_list_wrapper").removeClass('hidden');
    $("add_to_list_wrapper").innerHTML = r;
}

function ListDisplayCancel(){
    $("add_to_list_wrapper").addClass('hidden');
}

function AddToList (listID, listURL){
    if(!VerifyUser()){
        RedirectLogin();
        return;
    }
    else if (place.reviewID == ''){
        alert("Pleae add a review first...");
    }
    else{
        w.AddToList (listID, place.reviewID, AddToListReturn, callback, listID + "/" + listURL);
    }
}

function AddToListReturn (r, c){
    $("add_to_list_wrapper").innerHTML = r;
}

function EditListNote(id){
    var note = $("note_" + id).innerHTML;
    if(note.length > 1){
        note = note.substring(6);
    }
    reviewID = id;
    $("add_to_list_wrapper").removeClass('hidden');
    $("SaveNote").value = note;
    $("noteforreview").innerHTML = "Note for: " + $("link_" + id).innerHTML;
}

function SaveListNote(){
    if(listID > 0){
       var msg = $("SaveNote").value.trim();
       if(msg != ''){
        $("note_" + reviewID).innerHTML = "Note: " + msg;
       }
       else{
        $("note_" + reviewID).innerHTML = "";
       }
        SaveListNoteDB(listID, reviewID, msg);
    }
    CloseListNote();
}

function CloseListNote(){
     $("add_to_list_wrapper").addClass('hidden');
}
function SaveListNoteDB (listID, reviewID, note){
    w.AddNote (listID,reviewID,note);
}

function RedirectLogin (){
    $("login_wrapper").removeClass('hidden');
    scroll(0,0);
}
function CloseLoginNote(){
     $("login_wrapper").addClass('hidden');
}
