/**
 * common.js - all the js that is used in 90% or more of the pages in the site
 * keep the functions and classes in alphabetical order
 */

/** 
 * category list
 */
var categoryList = new Class({
	Implements: Options,
    options: {
        'categories_per_column': 9
    },

    initialize: function(el, data, options){
    	this.el = el;
        this.data = data;
        this.setOptions(options);
        this.sub_categories = Array();
       	this.bindEvents();
       	
       	// set the color_type
		if (this.el.hasClass('need_service')) {
			 this.color_type = 'need_service';
		} else if (this.el.hasClass('provide_service')) {
			this.color_type = 'provide_service';
		} else if (this.el.hasClass('knowledge_base')) {
			this.color_type = 'knowledge_base';
		} else {
			this.color_type = 'home';
		}	
    },
    
    bindEvents: function() {
    	window.addEvent('resize', function(e) {
    		if ($('category_list')) {
    			$('category_list').setStyles({
					'top': this.el.getPosition().y + this.el.getSize().y,
					'left': this.el.getPosition().x
				});
			}
    	}.bind(this));
    	
    	document.addEvent('click', function(e) { 
			if (e.target.id != 'category_list' && e.target.id != this.el.id) {
				this.hideCategoryList();
			}
		}.bind(this));	
		
		this.el.addEvent('click', function(e) {
			this.showCategoryList();
		}.bind(this));
		this.el.set('readonly', true);
    },
       
    showCategoryList: function() {
    	if ($('category_list')) {
    		$('category_list').removeClass('display_none');
    	} else {
			var category_list = new Element('div', {
				'id': 'category_list',
				'class': 'category_list ' + this.color_type,
				'styles': {
					'position': 'absolute',
					'top': this.el.getPosition().y + this.el.getSize().y,
					'left': this.el.getPosition().x
				}
			}).inject(document.body);
			
			var item_column = '';
			var item_list_sub = Array();
			var i = 1;
			var j = 0;
			var last_item = '';
			this.data.each(function(item, index) {
				if (item.indexOf(' -> ') == -1) {
					if (j == 0) {
						item_column = new Element('ul', {
							'html': ''
						}).inject(category_list);
					}
					
					var item_row = new Element('li', {
						'id': item,
						'html': item,
						'events': {
							'mouseover': function(e) {
								this.showSubCategoryList(item_row.get('text'));
								item_row.addClass('hover');
							}.bind(this),
							'click': function() {				
								this.el.value = item;
							}.bind(this)
						}
					});
					item_row.inject(item_column);
					
					last_item = item;
					this.sub_categories[last_item] = Array();
					j++;
					if (j == this.options.categories_per_column) {
						j = 0;
					}
				} else {
					this.sub_categories[last_item].push(item);
				}
				i++;
			}.bind(this)); 
  		}
    },
    
    showSubCategoryList: function(parent) {
    	this.hideSubCategoryList();
    	var sub_category_list = new Element('ul', {
    		'id': 'category_list_sub',
    		'class': this.color_type,
    		'styles': {
				'position': 'absolute',
				'top': $(parent).getPosition().y,
				'left': $(parent).getPosition().x+10
			}
    	}).inject(document.body);
    	
    	this.sub_categories[parent].each(function(el) {
    		var sub_category_row = new Element('li', {
				'id': el,
				'class': 'category_list_sub',
				'html': el.substr(el.indexOf(' -> ')+4, el.length),
				'events': {
					'click': function() {				
						this.el.value = el;
					}.bind(this)
				}
			});
			sub_category_row.inject(sub_category_list);
    	}.bind(this));
    	
    },
    
    hideCategoryList: function() {
		this.hideSubCategoryList();
		if ($('category_list')) {
			$('category_list').addClass('display_none');
		}
    },
    
    hideSubCategoryList: function() {
    	$$('.category_list li.hover').removeClass('hover');
    	if ($('category_list_sub')) {
    		$('category_list_sub').destroy();
    	}
    }
});


/**
 * load ajax page 
 * used with pagination
 */
function loadAjaxPage(id, url) {
	removeSystemMessage();
	$(id+'_wrapper').addClass('invisible');
	new Request.HTML({
		url: url,
		onComplete: function(response, responseElements, responseHTML, responseJavaScript) {
			if (responseHTML.test('"success":false')) {;
				window.location = bounce_location+'?landing_location='+window.location+'&bounce=true';
			}
			else
			{
				setupPagination(id);
				
				// automatically scroll to the top of the results if scroll is greater than the top
				var top = $(id+'_wrapper').getPosition().y - 100;
				if (window.getScroll().y > top)
				{
					window.scrollTo(0,top);
				}
				
				$(id+'_wrapper').removeClass('invisible');
			}					
		},
		update: $(id+'_wrapper')
	}).send();
}


/**
 * lookup category
 */
var current_category_keyword = '';
function lookupCategory(el) {
	var category_keyword = el.value;
	if (current_category_keyword != category_keyword) {	
		new Request.JSON({
			url: '/services/category_service.php?action=get_by_keyword&category_keyword='+escape(category_keyword),
			onComplete: function(response) {
				if (response.category_id != 0) {
					$('category_default_text').set('html', '<span class="category_confirmed">' + matched_to_text + response.category_name + ' </span>');
				} else {
					$('category_default_text').set('html', category_default_text);
				}
				$('category_id').value = response.category_id;
			}
		}).send();	
	}
	current_category_keyword = category_keyword;
}

/**
 * modalWindow
 */
var objModalWindow = '';
var modalWindow = new Class({
	Implements: Options,
    options: {
        'url' : '',
        'el' : ''
    },
    initialize: function(options){
        this.setOptions(options);
        this.show();
        this.loadContent();
        
        window.addEvent('resize', function() {
			if ($('modal_background')) {
				$('modal_background').setStyles({
					width: window.getScrollWidth(),
					height: window.getScrollHeight()
				});
			}
			if ($('modal')) {
				$('modal').setStyle('left', (window.getSize().x - $('modal').getSize().x) / 2 );
			}
		});
        
    },
	show: function() {
		this.hide();
		this.coverBackground();
		var modal = new Element('div', {
			id: 'modal'
		});
		
		modal.inject($(document.body), 'top');	
		modal.setStyle('left', (window.getSize().x - modal.getSize().x) / 2);
		modal.tween('top', modal.getSize().y*-1, window.getScroll().y);
		
		var window_scroll = window.addEvent('scroll', function(e) {
			modal.setStyle('top', window.getScroll().y);
		});

	},
	hide: function() {
		if ($('modal')) {
			var slide = new Fx.Tween('modal', {property: 'top'});
			slide.start(window.getScroll().y,$('modal').getSize().y*-1).chain(
				function() { 
					if ($('modal')) {
						$('modal').dispose();
					}
					if ($('modal_background')) {
						$('modal_background').dispose();
					} 
			}); 
		}
	},
	coverBackground: function() {
		new Element('div', {
			'id': 'modal_background',
			'styles': {
				opacity : .5,
				width : window.getScrollWidth(),
				height : window.getScrollHeight()
			}
		}).inject($(document.body));
	},
	loadContent: function() {
		new Element('div', {
			id : 'modal_content'
		}).inject($('modal'),'bottom');
		
		if (this.options.el != '') {
			$('modal_content').adopt($(this.options.el));
			$(this.options.el).removeClass('display_none');
		}
		else if (this.options.url != '') {
			new Request.HTML({
				url: this.options.url,
				onSuccess: function(html) {
					$('modal_content').set('text', '');
					$('modal_content').adopt(html);
					modalInit();
				}.bind(this),
				onFailure: function() {
					alert('System Error: Failed to load the content, please refresh the page and try again.');
				}
			}).send();	
		} else {
			alert('System Error: no content to load');
		}
	}
});
function setupModalLinks() {
	$$('.modal_link').each(function(el) {
		el.addEvent('click', function(e) {
			e.stop();
			objModalWindow = new modalWindow({'url':el.href});
		});
	});
}


/**
 * pageInit is a function that is almost always called after the dom is ready on 
 * the individual pages. In common functions that are needed to run on domready
 * should be called from here.
 */
function pageInit() {
	setupMainNav();
	setupToggleList();
	setupTabs();
	setupModalLinks();
	
	new searchHeader();
	
	setupAdClickTracker();
	
	setupLogoutBtn();
		
}

/*
 * remove system message
 */
function removeSystemMessage() {
	if ($('system_message'))	{
		$('system_message').destroy();
	}
}

/** 
 * search header
 ***********
 */
var searchHeader = new Class({
    initialize: function() {
    	// make sure the search header exists
    	if ( $('search_header') ) {
    		this.bindSubmit();
    	
    		this.bindTextFieldEvents($('search_category'));
    		this.insertDefaultText($('search_category'));
    	
    		if ($('search_location')) {
    			this.bindTextFieldEvents($('search_location'));
				this.insertDefaultText($('search_location'));
			}
    	}
    },
	
	bindSubmit: function(e) {
		$('search_header_form').addEvent('submit', function(e) {
			e.stop();
			$$('#search_header_form input').each(function(el) {
				if (el.value == language[el.id + '_default']) {
					el.value = '';
				}
			});
			this.submit();
		});
	},

	bindTextFieldEvents: function(el) {
		el.addEvent('focus', function() { 
			this.clearValue(el);
		}.bind(this));
		
		document.addEvent('click', function(e) {
			if (e.target.id != el.id && e.target.id != 'search_category_arrow') {
				this.insertDefaultText(el);
			}
		}.bind(this));
	},

    clearValue: function(el) {
    	if (el.value == language[el.id + '_default']) {
			el.value = '';
			el.removeClass('default_text');	
		}
    },
    
    insertDefaultText: function(el) {
    	if (el.value == '') {
			el.addClass('default_text');
			el.value = language[el.id + '_default'];
		}
    }

}); 

/**
 * set textarea char limit
 */
function setTextareaCharLimit(id,limit) {
	$(id).addEvents({
		'keyup': function(e) {
			if (this.value.length > limit) {
				this.value = this.value.substr(0,limit);
			}
			if ($(id+'_char_count')) {
				$(id+'_char_count').set('html',this.value.length);
			}
		},
		'click': function(e) {
			if (this.value.length > limit) {
				this.value = this.value.substr(0,limit);
			}
			if ($(id+'_char_count')) {
				$(id+'_char_count').set('html',this.value.length);
			}
		},
		'blur': function (e) {
			if (this.value.length > limit) {
				this.value = this.value.substr(0,limit);
			}
			if ($(id+'_char_count')) {
				$(id+'_char_count').set('html',this.value.length);
			}
		}
	});
}

/**
 * setup ad click tracker
 */
function setupAdClickTracker() {
	$$('.advert a, .advert_cell a').each(function(el) {
		el.addEvent('click', function(e) {
			e.stop();
			var advert_type = this.id.substr(0,this.id.indexOf('_'));
			var advert_id = this.id.substr(this.id.indexOf('_')+1, this.id.length);
			var link_url = this.href;
			var target = this.target;
			var isModal = false;
			if (this.hasClass('modal_link')) {
				isModal = true;
			}
			
			new Request.JSON({
				url: '/services/advert_service.php?action=save_click_count&advert_id='+advert_id+'&advert_type='+advert_type,
				onComplete: function(response) {
					if (response.success == true) {
						//if (target == '_blank') {
						//	window.open(link_url,advert_type+advert_id);
						//} else {
							if (isModal == false) {
								window.location = link_url;
							}
						//}
					} else {
						//alert(response.error_message);
					}
				}
			}).send();
					
		});
	});
}

/**
 * setup ajax links
 */
function setupAjaxLinks(link, section) {
	$$('.'+link).each(function(el) {
		el.addEvent('click', function(e) {
			if (e) {
				e.stop();
			}
			$$('.tabs li').each(function(el) {
				el.removeClass('tab_on');
			});
			
			$$('.tab_content').each(function(el) {
				el.addClass('display_none');
			});
			
			if ($(section))
			{
				$(section).addClass('tab_on');
			}
			$$('.'+section).each(function(el) {
				el.removeClass('display_none');
			});
			
			if (this.href != 'javascript:void(0);') {
				loadAjaxPage(section, this.href);
			}
		});
	});
}

/**
 * setup ajax action
 */
function setupAjaxAction(link, confirm_text, successFunction) {
	$$('.'+link).each(function(el) {
		el.addEvent('click', function(e) {
			if (e) {
				e.stop();
			}
			var link = this;
			if (confirm_text == '' || confirm(confirm_text)) {
				new Request.JSON({
					url: link.href,
					onComplete: function(response) {
						if (response.success == true) {
							if (successFunction != '') {
								window[successFunction](response, link);
							}
						} else {
							if (response.error_message == 'unauthorized_access') {
								window.location = notice_location+'?notice_type=unauthorized_access';
							} else {
								alert(response.error_message);
							}
						}
					}
				}).send();
			}
			
		});
	});
}

function setupEditLink(edit_link, edit_content, save_link, hide_content) {
	if (edit_link) {
		edit_link.getFirst('a').addEvent('click', function(e) {
			if (e) {
				e.stop();
			}
			// hide
			edit_link.addClass('display_none');
			if (hide_content) {
				hide_content.addClass('display_none');
			}
			// show
			edit_content.removeClass('display_none');
			if (save_link) {
				save_link.removeClass('display_none');
			}
		});
	}
	
}

/**
 * setup filter options
 */
function setupFilterOptions(id, url) {
	$(id).addEvent('change', function(e) {
		window.location = url + '?status='+this.value;
	});
}

/**
 * setup form submit
 * this function allows a page to setup multiple forms to submit via ajax
 * to obtain a json response. passing root id of the elements will setup the 
 * form and button, the success function is an optional function name that will 
 * execute upon success. 
 * Note: This function expects a common naming convention and relys on the function 
 * showSystemMessage()
 */
function setupFormSubmit(id, successFunction) {
	if ($(id+'_form')) {
		$(id+'_form').addEvent('submit', function(e) {
			// stop the normal submit
			if (e)
			{
				e.stop();
			}
			
			$$('.'+id+'_btn').each(function(el) {
				//el.disabled = true;
			});
			// clear any existing errors
			$$('.field_error').each(function(item) {
				item.removeClass('field_error');
			});
			
			
			if (!$('ajax')) {
				new Element('input', {
					'type': 'hidden',
					'id': 'isAjax',
					'name': 'isAjax',
					'value': 'true'
				}).inject(id+'_form');
			}
			
			this.set('send', {
				onComplete: function(response) { 
					response = JSON.decode(response);
					if (response.success == true) {
						if ($('system_message')) {
							$('system_message').destroy();
						}
						
						if (successFunction != '') {
							window[successFunction](response);
						}
					} else {
						if (response.error_message == 'unauthorized_access') {
							window.location = notice_location+'?notice_type=unauthorized_access';
						} else if (response.error_message == 'login_required') {
							window.location = bounce_location+'?landing_location='+window.location+'&bounce=true';
						} else {
							showSystemMessage(response.error_message, id+'_form', 'error');
							if (response.errors)
							{
								for(var i=0; i<response.errors.length; i++) {
									if ($(response.errors[i]))
									{
										$(response.errors[i]).addClass('field_error');
									}
								}
							}
						}
					}
					$$('.'+id+'_btn').each(function(el) {
						el.disabled = false;
					});
				}
			});
			
			//Send the form.
			this.send();
		});
	}
}

/**
 * setup logout btn
 */
function setupLogoutBtn() {
	if ($('logout_btn')) {		
		$('logout_btn').addEvent('click', function(e) {
			window.location = '/services/user_service.php?action=logout';
		});
	}
}

/**
 * setup main nav
 * setup the main nav rollovers
 */
function setupMainNav() {	
	$$('.nav_tab a').addEvent('mouseenter', function() { 
		//Mouseover 
		if (!this.hasClass('on')) {
			this.getParent().addClass('nav_tab_middle_on');
			this.getParent().getPrevious().addClass('nav_tab_left_on');
			this.getParent().getNext().addClass('nav_tab_right_on');
		}
	});
	
	$$('.nav_tab a').addEvent('mouseleave', function() { 
		if (!this.hasClass('on')) {
			//Mouseout
			this.getParent().removeClass('nav_tab_middle_on');
			this.getParent().getPrevious().removeClass('nav_tab_left_on');
			this.getParent().getNext().removeClass('nav_tab_right_on');
		}
	});
}

/**
 * setup pagination handler
 */
function setupPagination(id) {
	$$('#pagination_'+id+' a').each(function(el) {
		el.addEvent('click', function(e) {
			if (e) {
				e.stop();
			}
			loadAjaxPage(id, this.href);
		});
	});
}

/**
 * setup toggle list
 */
function setupToggleList() {
	$$('.toggle_arrow').each(function(el) {
		el.addEvent('click', function(e) {
			if (el.getFirst().src.test('right')) {
				el.getFirst().src = el.getFirst().src.replace('right', 'down');
				el.getNext().getNext().removeClass('display_none');
			} else {
				el.getFirst().src = el.getFirst().src.replace('down', 'right');
				el.getNext().getNext().addClass('display_none');
			}
		});
	});
}

/**
 * setup the tab links to hide and show data
 */
function setupTabs() {
	$$('.tabs li').each(function(el) {
		el.addEvent('click', function(e) {
			if (e) {
				e.stop();
			}
			$$('.tabs li').each(function(el) {
				el.removeClass('tab_on');
			});
			
			$$('.tab_content').each(function(el) {
				el.addClass('display_none');
			});
			
			if (this.hasClass('loadAjax')) {
				var url = window.location.toString();
				if (url.indexOf("?")) {
					url = '&'+(url.substr(url.indexOf("?")+1));
				} 
				else
				{
					url = '';
				}	
				loadAjaxPage(this.id, '/common/'+this.id+'.php?isAjax=true'+url);
			}
			
			this.addClass('tab_on');
			$$('.'+this.id).each(function(el) {
				el.removeClass('display_none');
			});
			
			
		});
	});
}

function setupGeoInfoLookup(zip_code_el, city_state_el) {
	zip_code_el.addEvent('keyup', function(e) {
		city_state_el.set('html','');
		if (zip_code_el.value.length >= 5) {
			// get the state list for the country id selected
			new Request.JSON({
				url: '/services/utility_service.php?action=get_geo_info&zip_code='+zip_code_el.value,
				onComplete: function(response) {
					if (response.success == true && response.geo_info) {
						city_state_el.set('html', response.geo_info.geo_city + ', ' + response.geo_info.state_name);
					}
				}
			}).send();
		}
	});
}   

/**
 * show error
 * will inject a div into the identified section of the page using containing 
 * the error text passed.
 * message_type = (error, success, notice)
 */
function showSystemMessage(message_text, section, message_type) {
	removeSystemMessage();
	
	var system_message = new Element('div', {
		'id' : 'system_message',
		'class' : message_type
	});
	system_message.set('html', message_text);
	system_message.inject(section, 'top');
	if (!$('modal')) {
		window.scrollTo(0, system_message.getPosition().y-150);
	}
}

/** 
 * slideShow
 ***********
 */
var slideShow = new Class({
    initialize: function() {
       	this.slideDelay = 10000;
       	this.lineDelay = 1500;
       	this.num_of_slides = 0;
       	this.zIndex = 1;
       	this.slides = Array();
       	this.init();
    },
	
	init: function() {
		$$('#slideshow_wrapper h1, #slideshow_wrapper div').each(function(el) {
			el.setStyles({
				'opacity': 0,
				'visibility': 'visible'
			});
			
			this.num_of_slides++;
			this.slides[this.num_of_slides] = el.id;
		}.bind(this));
		
		this.start();
	},
	
	start: function() {
		this.showSlide(1);
		if (this.num_of_slides > 1) {
			for (var i = 1; i < this.num_of_slides; i++) {
				(function(i){ 
					this.showSlide(i+1)
				}).delay(i * this.slideDelay, this, i);
			}
		}
	},
	
	showSlide: function(slide_num) {
		$$('.line').each(function(el) { 
			el.setStyle('opacity', 0); 
		});
		$(this.slides[slide_num]).setStyle('zIndex', this.zIndex++);
		$(this.slides[slide_num]).fade('in');
		
		var lines = $$('#' + this.slides[slide_num] + ' .line');
		if (lines.length > 0) {
			for (var i = 0; i < lines.length; i++) {
				(function(i){ 
					lines[i].fade('in');
				}).delay(i*this.lineDelay, this, i);
			}
			
		}
		
		if (this.num_of_slides > 1) {
			if ($(this.slides[slide_num-1])) {
				$(this.slides[slide_num-1]).setStyle('opacity',0);
			}
			else
			{
				$(this.slides[this.num_of_slides]).setStyle('opacity',0);
			}
		
			if (slide_num == this.num_of_slides) {
				(function() {
					this.start();
				}).delay(this.slideDelay, this);
			}
		}
		
	}

}); 

/** 
 * teaser
 ***********
 */
var teaser = new Class({
    initialize: function() {
       	this.bindEvents();
    },
	
	bindEvents: function() {
		$$('.teaser_box').each(function(el) {
			el.getElements('.learn_more').addEvents({
				'click': function(e) {
				 	var box_num = el.id.substr(el.id.length - 1)*1;
				 	$$('#' + el.id + ' .content .contracted').each(function(item) { item.addClass('display_none'); });
				 	$$('#' + el.id + ' .content .expanded').each(function(item) { item.removeClass('display_none'); });
				 	el.setStyle('z-index', 100);
				 	var expand = new Fx.Morph(el, {duration: 'short'}); 
					expand.start({
						'left': 0,
						'width': 915
					}).chain(
						function() {
							new Element('div', {
								id: 'teaser_close',
								html: '<img src="/images/close_btn.png" alt="" />',
								styles: {
									width: 915,
									height: 60,
									zIndex: 1000,
									position: 'absolute',
									textAlign: 'right',
									cursor: 'pointer'
								},
								events: {
									'click': function(e) {
										$('teaser_close').dispose();
										expand.start({
											'left': 310 * (box_num - 1),
											'width': 295
										}).chain(
											function() {
												el.setStyle('z-index', 0);
												$$('#' + el.id + ' .content .contracted').each(function(item) { item.removeClass('display_none'); });
												$$('#' + el.id + ' .content .expanded').each(function(item) { item.addClass('display_none'); });
											}
										);
									}
								}
							}).inject('teaser_wrapper');
						}
					);
				}.bind(this)
			});
			
			
		}.bind(this));
	}

}); 

/**
 * mark message as read
 */
function markMessageAsRead(message_id) {
	// get the state list for the country id selected
	new Request.JSON({
		url: '/services/message_service.php?action=mark_message_as_read&message_id='+message_id,
		onComplete: function(response) {
			if (response.success == true) {
				updateNewMessageCount();
			}
		}
	}).send();
}

/**  
 * update the message count in the neck
 */
function updateNewMessageCount() {
	// get the state list for the country id selected
	new Request.JSON({
		url: '/services/message_service.php?action=update_new_message_count',
		onComplete: function(response) {
			if (response.success == true) {
				if (response.count > 0) {
					$$('.menu_new_message_count').each(function(el) {
						el.set('html', response.count + ' new');
						el.addClass('theme_text_red');
					});
					
				} else {
					$$('.menu_new_message_count').each(function(el) {
						el.set('html', '0');
						el.removeClass('theme_text_red');
					});
				}				
			}
		}
	}).send();
}


function nl2br (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // +   modified by: Barry Mortenson
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'

    var breakTag = '<br />';

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
