var mvcc = {};

mvcc.config = {
	signinUrl: "signin.aspx", //user account login url
	registerUrl: "register.aspx", //register account url
	manageLinksURL: 'manage-profile-links.aspx' //url for profile links ajax calls
}

//calendar widget
mvcc.calendarWidget = function(calendarEl){
		
		//determine which calendar we're using (important if there is more than 1 on a page)
		this.calendar = calendarEl;
		this.id = this.calendar.selector;
		
		//if the calendar exists then set it up
		if(isset(this.calendar)){
			
			var _this = this;
			
			//these vars reference the calendar's content tabs and not the button tabs at the top
			this.tab1 = $(this.id+' .tab1');
			this.tab2 = $(this.id+' .tab2');
				
			
			//show button tabs if javascript is on
			$(this.id+' .module-inner .calendar-tabs').css('display', 'block');
		
			//hide usability headings if javascript is on
			$(this.id+' .calendar-title').css('display', 'none');
			
			//hide the second tab initially, if javascript is on
			this.tab2.css('display', 'none');
			
			//set up listeners for button tabs
			this.tab1Tab = $(this.id+' .calendar-tabs ul li:eq(0) a'),
			this.tab2Tab = $(this.id+' .calendar-tabs ul li:eq(1) a');
			
			//set the first button tab to active
			this.tab1Tab.addClass('active');
			
			//attach listeners to the button tabs
			this.attachTabListeners();
			
		}
}

//attaches listeners to calendar tabs
mvcc.calendarWidget.prototype.attachTabListeners = function(){
			var _this = this;
			
			//click event for the first button tab
			this.tab1Tab.click(function(e){									
				e.preventDefault();
				_this.tab1Tab.addClass('active');
				_this.tab2Tab.removeClass('active');
				_this.tab1.css('display', 'block');
				_this.tab2.css('display', 'none');				
			});	
			
			//click event for the second button tab
			this.tab2Tab.click(function(e){									   
				e.preventDefault();
				_this.tab2Tab.addClass('active');
				_this.tab1Tab.removeClass('active');
				_this.tab2.css('display', 'block');
				_this.tab1.css('display', 'none');				
			});	
}

//text-size function
mvcc.textSize = {
	
	//create an empty var to store data in (used later)
	currentFontSize: '',
	
	init: function(){	
		
		//define font size array with all required font sizes
		this.fontSizes = ['10px', '11px', '12px', '13px', '14px', '15px'];
		var _this = this;
			
		//determine current body font size
		this.currentFontSize = $('body').css('font-size');			
		
		//check if there is a cookie with a specified font size		
		var textCookie = mvcc.cookie.read('text_size');
		
		//and set font size to it if there is
		if(textCookie){
			this.currentFontSize = textCookie;
			this.setCurrentFontSize(this.currentFontSize);
		}
		
		//set up plus/minus button listeners
		this.initButtons();
		
	},	
	
	//returns current font size
	getCurrentFontSize: function(){
		return this.currentFontSize;
	},
	
	//sets font size/line-height
	setCurrentFontSize: function(size){
		this.currentFontSize = size;
		
		//set value of cookie to latest font size
		mvcc.cookie.create('text_size', size, 10*365);
		$('#content, #footer').css('font-size', size);
		$('#content, #footer').css('line-height', (parseInt(size) * 1.4) + 'px');
		
		//re-adjust image/content rotator heights to fit in the new font sizes
		mvcc.contentRotator.prototype.reAdjustHeight();
	},
	
	initButtons: function(){
		_this = this;
		
		//set up events for the text-size buttons in the top nav
		var li = $('.text-size'),
			liWidth = $('.text-size').width(),
			ul = $('.text-size ul'),
			maxWidth = liWidth + 38 + 'px';
		
		$('.text-size').hover(function(){
			ul.css('visibility', 'visible');
			//li.animate({width: maxWidth});
			li.css('width', liWidth + ul.width() + 'px');
		}, function(){
			ul.css('visibility', 'hidden');
			//li.animate({width: liWidth});
			li.css('width', liWidth+'px');
		});

		//set up button listerners
		$('#inc-text-size').click(function(e){
			e.preventDefault();
			for(var i = 0, l = _this.fontSizes.length; i < l; i++){
				if(_this.fontSizes[i] == _this.getCurrentFontSize() && i !== (_this.fontSizes.length - 1)){
					_this.setCurrentFontSize(_this.fontSizes[i + 1]);
					break;
				}
			}
		});
		
		$('#dec-text-size').click(function(e){
			e.preventDefault();
			for(var i = 0, l = _this.fontSizes.length; i < l; i++){
				if(_this.fontSizes[i] == _this.getCurrentFontSize() && i !== 0){
					_this.setCurrentFontSize(_this.fontSizes[i - 1]);
					break;
				}
			}
		});
	}
}

//cookie functions
mvcc.cookie = {
	create: function(name, value, daysTillExpire){
		if (daysTillExpire) {
			var date = new Date();
			date.setTime(date.getTime()+(daysTillExpire*24*60*60*1000));
			var expires = '; expires='+date.toGMTString();
		} else {
			var expires = '';	
		}
		
		document.cookie = name + '=' + value + expires + '; path=/';
	},
	
	read: function(name){
		var nameEq = name + '=',
			ca = document.cookie.split(';');
			for(var i = 0; i < ca.length; i++) {
				var 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;
			}		
	},
	
	remove: function(name){
		this.create(name, '', -1);
	}
}

//ajax functions
mvcc.request = {

	ajax: function(url, success, error){		
		$.ajax({
			url: url,
			success: success,
			error: error			
		});
	}

}

mvcc.profile = {
	
	quicklinks: {
		
		//sets up event handlers for edit button and add link button
		init: function(){			
			var _this = this;
			
			if(isset($('#edit-ql')) && isset($('#add-link'))){
				$('#edit-ql').click(function(e){
					e.preventDefault();							
					_this.editList();
				});
				
				$('#add-link-submit').click(function(e){
					e.preventDefault();
					
					var url = $('#paste-link-field').val() || $('#add-link-select').val();
					var title = $('#paste-link-title').val() || $('#add-link-select').val();					
					_this.saveLink(url, title);
				});
			}
			
			/*if(isset($('.save-current-page'))){
				$('.save-current-page').click(function(e){
					e.preventDefault();
					
					if(typeof(mvcc.profile.user.loggedIn) !== 'undefined' && mvcc.profile.user.loggedIn == true){
						var url = (this.href !== '') ? this.href : window.location,
							title = $('#main-content h2:eq(0)').html();
							
						_this.saveLink(url, title);
					} else {
						mvcc.profile.logReq(this);
					}
					
				});
			}*/
			
		},		
		
		//switch the profile page side list to edit mode
		editList: function(){
			var _this = this;
			$('#add-link').css('display', 'block');
			$('#add-link-submit').css('display', 'inline');
			$('#edit-ql').html('Save').click(function(e){
				e.preventDefault();
				_this.cancelList();
			});
			$('#my-quicklinks li').addClass('delete').click(function(e){
				e.preventDefault();
				_this.deleteLink(this);
			});			
			
		},
		
		//switch the profile page side list to non-edit mode
		cancelList: function(){
			var _this = this;
			$('#add-link').css('display', 'none');
			$('#add-link-submit').css('display', 'none');
			$('#edit-ql').html('Edit').click(function(e){
				e.preventDefault();
				_this.editList();
			});
			$('#my-quicklinks li').removeClass('delete').unbind('click');
		},
		
		//delete a link from both the side list (if available) and the save list (if available)
		deleteLink: function(_this){
			//convert to jquery object
			_this = $(_this);
			_this.remove();
			mvcc.request.ajax(mvcc.config.manageLinksURL + '?delete='+_this.children('a').attr('href'), function(){
				
			}, function(){
				try {
					console.log('There was an error with the request: ' + error);
				} catch(e){}
			});
			
		},
		
		//saves a specific link to the list
		saveLink: function(url, pageTitle){
			_this = this;
			var titleQS = '&title='+pageTitle || '',
				title = pageTitle || 'url';
			this.updateList(url, title);
			mvcc.request.ajax(mvcc.config.manageLinksURL + '?save='+url+titleQS, function(){
				
			});
		},
		
		//updates both the side list (if available) and the save list (if available) with the new link
		updateList: function(url, pageTitle){
			
			//if pageTitle is too long then chop it down		
			
			//add item to profile page side list (if available)
			if($('#my-quicklinks')){
				var pageTitle = pageTitle.toString();					
					pageTitleStripped = (pageTitle.length > 18) ? pageTitle.substr(0, 18) + '...' : pageTitle;
				
				var newLink = $('<li><a href="'+url+'">'+pageTitleStripped+'</a></li>').appendTo('#my-quicklinks');
				
				if($('#add-link').css('display') == 'block'){
					newLink.addClass('delete');
				}
				//attached event handler to new link
				newLink.click(function(e){
					e.preventDefault();
					_this.deleteLink(this);
				});
			}
			
			//add item to save list (if available)
			if(isset($('#controls .save'))){				
				var newLink = $('<li><a href="'+url+'">'+pageTitle+'</a></li>').insertBefore('#controls .save ul li.save-footer');				
			}
			
			this.pageSaved();
			
		},
		
		//this function should run on pages that have already been saved
		pageSaved: function(){
			$('.save-current-page').css({background: 'none', 'padding-left': 0, color: '#999'}).removeAttr('href').unbind('click').html('Page saved');	
		}
		
	},
	
	//notifies user that they have to sign in or register before they can save a page
	logReq: function(self){
		var _this = $(self);
		var lor = $('<span class="lor">You must <a href="'+mvcc.config.signinUrl+'">Sign-in</a> or <a href="'+mvcc.config.registerUrl+'">Register</a> before you can do that.</span>');
		lor.insertBefore(_this);
		_this.remove();
	},
	
	user: {}
	
}

mvcc.contentRotator = function(el, type, rand, delay, nav){
		
		if(isset(el)){
			this.el = el;
			this.type = type;
			this.rand = rand || false;
			this.delay = delay || 6000; //default 6 seconds
			this.length = el.children(type).length;		
			this.nav = nav || false;
			this.timer;
			this.timeout;
			var _this = this;
			var _templength = 0; //used in image load function below to prevent multiple loops from occuring
			
			//intended to make page load a bit prettier
			this.el.css({height: '0px', overflow: 'hidden'});
					
			//executes height correction code once all the rotator images are loaded
			$(window).load(function(){					
				_this.height = _this.getMaxHeight();	
				el.css('height', _this.height);
			});
			
			//set initial css styles for elements		
			el.children(type).css({position: 'absolute', display: 'none'});
			
			//set properties
			if(rand == false){
				this.current = 0;
				var e = el.children(type+':eq(0)').css('display', 'block');
			} else {
				this.current = Math.floor(Math.random()*this.length);
				var e = el.children(type+':eq('+this.current+')').css('display', 'block');
			}
			
			this.el.css({overflow: 'visible'});
				
			//execute prototype functions if there is more than 1 item
			if(this.length > 1){
				this.autoRotate();
				//generate navigation if it is set to true
				if(this.nav){
					this.populateNav();
					this.nav.css('display', 'block');				
				}
			}
		}		
}

//rotates the items depending on this.current or a defined index arguement
mvcc.contentRotator.prototype.rotate = function(index){	
	var _this = this;		
	_this.el.children(_this.type+':eq('+_this.current+')').fadeOut(1000);		
	if(index){
		index = parseInt(index);
		_this.current = index;
	} else if(_this.current == _this.length - 1){
		_this.current = 0;
	} else {
		_this.current++;
	}		
	
	if(this.nav){
		this.changeNavActiveClass(this.current);				
	}
	
	_this.el.children(_this.type+':eq('+_this.current+')').fadeIn(1000);	
}

//auto executes the rotate function on a timer
mvcc.contentRotator.prototype.autoRotate = function(){	
	var _this = this;
	this.timer = null;	
	this.timer = setInterval(function(){						  
		_this.rotate();
	}, _this.delay);
}

//clears the timer and resets it after a period of time (default 0 milliseconds + this.delay)
mvcc.contentRotator.prototype.clearAndResetTimer = function(){	
	var _this = this;
	clearInterval(this.timer);
	this.autoRotate();
}

//gets the height of the highest element in the list and returns it
mvcc.contentRotator.prototype.getMaxHeight = function(){
	var height = 0;
	for(var i = 0, l = this.length; i < l; i++){
		var elHeight = this.el.children(this.type+':eq('+i+')').height();
		if(elHeight > height){
			height = elHeight;
		}
	}
	return height + 'px';
}

//reset height
mvcc.contentRotator.prototype.reAdjustHeight = function(){
	if(isset($('.rotator'))){	
		for(var i = 0, l = $('.rotator').length; i < l; i++){			
			var height = 0;
			for(var ii = 0, ll = $('.rotator:eq('+i+') .rotator-item').length; ii < ll; ii++){
				var elHeight = $('.rotator:eq('+i+') .rotator-item:eq('+ii+')').height();
				if(elHeight > height){
					height = elHeight;
				}
			}
			$('.rotator:eq('+i+')').css('height', height + 'px');
		}		
	}
}

//populates the nav item with buttons and sets their event handlers
mvcc.contentRotator.prototype.populateNav = function(){
	var _this = this;
	
	this.nav = $('<ul>').insertBefore(this.el).attr('id', this.el.attr('id')+'-nav').addClass('rotator-nav');
	
	for(var i = 0, l = this.length; i < l; i++){
		if(i == this.current){
			var li = this.nav.append('<li class="active"><a href="" i="'+i+'" class="i-rep">.<span></span></a></li>');
		} else {
			var li = this.nav.append('<li><a href="" i="'+i+'" class="i-rep">.<span></span></a></li>');
		}
	}
	
	li.children('li').children('a').click(function(e){
		e.preventDefault();
		_this.clearAndResetTimer();
		_this.rotate($(this).attr('i'));
	});
}

mvcc.contentRotator.prototype.changeNavActiveClass = function(index){
	this.nav.children('li').removeClass('active');	
	this.nav.children('li:eq('+this.current+')').addClass('active');
}

// ie6 hover function
sfHover = function() {
	var sfEls = document.getElementById("main-navigation").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" hover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" hover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

var saveHover = function(){
	$('#controls .save').hover(function(){
		$(this).addClass('hover');							
	}, function(){
		$(this).removeClass('hover');
	});
}

//click clear function
var clickClear = function(inputEl, value, obj){
	if(inputEl){
		if(typeof obj !== 'undefined'){
			for(el in obj){
				if(obj[el].type == 'input'){
					element = jQuery('#'+obj[el].id+'');
					new clickClear(element, obj[el].def_value);
				}
			}
		} else {
			var currentValue = value || inputEl.val();
			if(value){
				inputEl.val(value);
			}
			inputEl.message = currentValue;
			inputEl.click(function(){
				if(inputEl.val() == currentValue){
					inputEl.val('');
				}
			});
			inputEl.blur(function(){
				if(inputEl.val() == ''){
					inputEl.val(currentValue);
				}
			});
		}
	}
}

var isset = function(el){
	if(el.length > 0){
		return true;
	} else {
		return false;
	}
}

$(document).ready(function() {

    clickClear($('.main-search-field'), 'Search...');
    clickClear($('#search-form .re-search'), 'Enter another keyword...');
    clickClear($('#side-search-form .search-field'), 'Enter keyword...');
    saveHover();

    //calendar widget
    var sideCal = new mvcc.calendarWidget($('#side-calendar'));
    var mainCal = new mvcc.calendarWidget($('#main-calendar'));

    // show the tab in the calendar
    $('#main-calendar .tab1').show();

    //nav delay
    //mvcc.navigation.delay(1000);

    //profile
    mvcc.profile.quicklinks.init();

    //text size
    mvcc.textSize.init();

    //rotator widgets
    var homepageHero = new mvcc.contentRotator($('#hero-slideshow'), 'div', true, 8000, $('#hero-nav'));
    var homepageRotator2 = new mvcc.contentRotator($('#rotator2'), 'div', true, 8000, $('#rotator2-nav'));

    $(".ratepayer-account-box input").keyup(function() {
        if ($(this).val() != '') {
            $(".ratepayer-account input").attr("checked", "checked");
        }
    });

    $("#page-controls #controls li.sharethis").show();
    $("#page-controls #controls li.save").show();
    $("#page-controls #controls li.save a.save-btn.attach-to-me").click(function() {
        // get the title and link
        var url = $(this).attr('href');
        var title = $(this).attr('title').replace('Save ', '');

        if (document.all)
            window.external.AddFavorite(url, title);
        else if (window.sidebar)
            window.sidebar.addPanel(title, url, "");
        else
            alert('Press CTRL-D to bookmark this page using your browser.');

        return false;
    });

    // check if the map div is available (this will be placed on page via shortcode in silverstripe) and there is an address
    // if the GMap2 constructor doesn't exist, then there is no API key defined in SiteConfig page
    // if the address is undefined, then there is either no address defined (duh!) or there is no API key defined in SiteConfig page		
    if (document.getElementById("map_canvas") && GMap2) {
        NOWGMap.init();

        if (NOWGMap.lat && NOWGMap.lon) {
            NOWGMap.showMap(parseFloat(NOWGMap.lat), parseFloat(NOWGMap.lon)); //GMap.lat/lon is defined in Page.php
        } else if (NOWGMap.kml) {
            NOWGMap.showKML(NOWGMap.kml); //GMap.kml is defined in Page.php
        } else if (NOWGMap.address) {
            NOWGMap.showAddress(NOWGMap.address); //GMap.address is defined in Page.php
        }
    }

    $("#page-rating .title a.disabled").click(function() {
        e.preventDefault();
    });

    //.$("#content #page-rating .module-inner #submit-reason").css("display", "none !important");

    $("#page-rating .title input.vote-no").click(function(e) {
        
        $(this).addClass("active");

        $("#page-rating .module").animate({
            height: 'toggle'
        }, 700, function() {
            // Animation complete.
        });
    });

});

