(function($)  {
    $.relic = {};
    
    $.relic.ajax_url = ajaxify(window.location.toString())
    
    $.relic.redirect = function(location)  {
        if (!isset(location))  {
            window.location.reload();
        } else {
            window.location = location;
        }
    };
})(jQuery);

$(function()  {
    
    
    
});

$.fn.addErrorMessage = function(message) {
    return $(this).addMessage(message, 'error');
}

$.fn.addMessage = function(message, type) {
    
    var iconClass = '';
    var messageClass = '';
    
    switch (type) {
        case 'error':
            iconClass = 'ui-icon-alert';
            messageClass = 'ui-state-error';
            break;
        case 'success':
            iconClass = 'ui-icon-check';
            messageClass = 'ui-state-success';
            break;
        case 'status':
        default:
            iconClass = 'ui-icon-info';
            messageClass = 'ui-state-highlight';
            break;
    }
    
    $('div#alpha div.StatusMessages').append(
        $('<div></div>').addClass('ui-widget').html(
            $('<div></div>').addClass('status_messages').addClass(messageClass).addClass('ui-corner-all').html(
                $('<span></span>').addClass('ui-icon').addClass(iconClass).css('float', 'left').css('margin-right', '0.3em')
            ).append(
                $('<div></div>').addClass(type).html(message)
            )
        )
    );
    
    return true;

}

$.fn.addStatusMessage = function(message) {
    return $(this).addMessage(message, 'status');
}

$.fn.addSuccessMessage = function(message) {
    return $(this).addMessage(message, 'success');
}

function ajaxify(url) {
    
    var url_pieces = url.replace('#', '').split('/');
    
    url_pieces[3] += '-';
    
    return url_pieces.join('/');
    
}

// http://php.net/manual/en/function.date.php

function daysInMonth(month, year) {
    
    var days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    
    if (month == 2) {
        if (isLeapYear(year)) {
            return 29;
        }
    }
    
    if (month < 1 || month > 12) {
        return 0;
    }
    
    return days_in_month[(month-1)];
    
}

$.fn.displaySubscription = function() {
    
    if (!subscribed() && $(this).tagName() == 'a') {
        
        $(this).attr('href', '#SubscriptionDialog');
        
        $(this).fancybox({
            speedIn: 0,
            speedOut: 0,
            overlayColor: '#000',
            overlayOpacity: 0.5,
            titleShow: false
        });
        
        // $(this).click();
        
    }
    
    return true;
    
}

/* 
function initSubscriptionOnlyFancybox() {
    
    if (!subscribed()) {
        
        $('a.SubscriptionOnly').fancybox({
            speedIn: 0,
            speedOut: 0,
            overlayColor: '#000',
            overlayOpacity: 0.5,
            titleShow: false,
            type: 'ajax',
            href: 'http://' + window.location.host + '/subscribe/',
            ajax: {
                cache: false
            }
        });
        
    }
    
    return true;
    
}
//*/

// http://php.net/manual/en/function.date.php

function isLeapYear(year) {
    
    if ((year % 4) != 0) {
        
        return false;
        
    }
    
    if ((year % 100) == 0) {
        
        if ((year % 400) == 0 ) {
            
            return true;
            
        } else {
            
            return false;
            
        }
    } else {
        
        return true;
        
    }
    
}

function isset(value) { 
    
    return typeof value != 'undefined' && value != null;
    
}

function stitchAndAjaxify(incompleteUrl) {
    
    return ajaxify(stitchUrl(incompleteUrl));
    
}

// Combines relative or absolute href with current window location based on a folder match

function stitchUrl(incompleteUrl) {
    
    if (incompleteUrl.substr(0,1) == '/') {
        
        return 'http://'+window.location.host+incompleteUrl;
        
    }
    
    var base = window.location.href.split('/');
    
    var href = $.trim(incompleteUrl).split('/');
    
    if (href.length < 1) return base.join('/');
    
    if (href[0].length == 0) href.shift();
    
    var completeUrl = '';
    
    for (var i in base) {
        
        if (base[i] == href[0]) {
            
            break;
            
        } else {
            
           completeUrl += base[i] + '/'
           
        }
        
    }
    
    return completeUrl+href.join('/');
    
}

function subscribed() { 
    
    return isset($('body').data('subscribed')) ? $('body').data('subscribed') : false;
    
}

// http://stackoverflow.com/questions/411688/how-to-extend-jquery-to-make-it-easier-to-retrieve-the-tagname

$.fn.tagName = function() {
    return this.get(0).tagName.toLowerCase();
}

$.fn.registerResizeToFitPage = function(arguments) {
	arguments = $.extend({
		stretch: ""
	}, arguments);
	
	if (!$(this).exists()) {
		return false;
	}
	
	var element = $(this);
	var resizeArgs = arguments
	
	if (element.exists()) {
		if (windowHasLoaded()) {
			element.resizeToFitPage(resizeArgs);
		}
		else {
			$(window).load(function() {
				element.resizeToFitPage(resizeArgs);
			})
		}
		$(window).bind("resize", function(){
			element.resizeToFitPage(resizeArgs);
		});
	}
	
	return true;
	
}

$.fn.resizeToFitPage = function(arguments) {
	arguments = $.extend({
		stretch: ""
	}, arguments);

	if (!$(this).exists()) {
		return false;
	}
	
	var stretch = arguments.stretch.substr(0,1); 
		
	if (stretch == "h" || stretch == "b") {
		
		var ch = ($(this).attr("id")=="Container")?$(this).getTotalHeight():$("div#Container").getTotalHeight();
		var wh = $(window).height();
		
		$(this).height(ch);
		if (ch < wh) {
			$(this).height(wh);
		}
		
	}
	
	if (stretch == "w" || stretch == "b") {
		
		var cw = ($(this).attr("id")=="Container")?$(this).getTotalWidth():$("div#Container").getTotalWidth();
		var ww = $(window).width();
		
		$(this).width(ww);
		if (cw > ww) {
			$(this).width(cw);
		}
		
	}
	
	return true;
	
}

$.fn.exists = function() {
	
	return ($(this).length > 0)?true:false;
	
}

windowLoaded = false;
function registerWindowHasLoaded() {
	windowLoaded = true;
}

function windowHasLoaded() {
	return windowLoaded;
}
