var INITIAL_LOAD = true;

// Clears current cookies if there is data in database to replace them with
function clear_cookies() {
    var cookies = {};

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
        }
    }

    for (var i in cookies) {
        if (i.match("tabs") || i.match("widget")) {
            $.cookie(i, null, { expires: 100 });
        }
    }    
}

// Get cookies that track tabs and widgets
function get_cookies_array() {
    if (INITIAL_LOAD) {
        $.ajax({
            url: '/Custom/secc/widgets/ajax/LoadCookies.aspx',
            async: false,
            success: function(data) {
                if (data.replace(/\s+/, '') != '') {
                    clear_cookies();
                    var cookieLines = data.split("\n");
                    for (var x = 0; x < cookieLines.length; x++) {
                        var keyValue = cookieLines[x].split("\t");
                        $.cookie(keyValue[0], keyValue[1], { expires: 100 });
                    }
                }
            },
            dataType: "text"
        });
    }

    var cookies = { };

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
        }
    }

    return cookies;

}

// saves current widgets and tab positions to database
function save_cookies() {
    var myCookies = get_cookies_array();
    var dataOut = '';
    for (var i in myCookies) {
        if (i.match("tabs") || i.match("widget")) {
            dataOut += i + "\t" + myCookies[i] + "\n";
        }
    }
    $.post('/Custom/secc/widgets/ajax/SaveCookies.aspx',
        { data: dataOut }
        );
}

var LEFT_COUNT = 0;
var RIGHT_COUNT = 0;
var TAB_COUNT = 0;
var TABS_LOADED = true;
var CAMPUS_ID;

$(function () {
	CAMPUS_ID = $('#campusID').text();

	// display loading graphic
	$('body').block({
		fadeIn: 0,
		centerY: 0,
		css: { border: 'none', backgroundColor: '' },
		overlayCSS: { backgroundColor: '#F4F0EA' },
		message: '<div class="LoadingModulesContainer"><img src="/Custom/secc/widgets/images/ajax-loader.gif" alt="Loading..." width="54" height="54" /></div>'

	});


	// formats page tabs
	$('.MiddleCont').tabs(
        {
        	tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a><span class="ui-icon ui-icon-close remove-tab"></span></li>'

        }

        );

	// Clicked to remove on of the page tabs
	$('.remove-tab').live('click', function () {
		$.cookie(CAMPUS_ID + '_tabs_' + $(this).parent().children('a').attr('href').replace('#', ''), 'REMOVE', { expires: 100 });
		save_cookies();
		$(this).parent().remove();
		if ($('.PageTabs li').length == 1) {
			$('.Addtab').removeClass('HasUserTabs');
		}

	});

	// adds a page tab
	$('.add-tab').click(function () {
		window.location = "#";
		if ($('.PageTabs').children('li').length < 5) {
			TAB_COUNT++;
			$('.Addtab').addClass('HasUserTabs');
			$('.MiddleCont').prepend('<div id="page-tab' + TAB_COUNT + '" class="content"><div class="column columnleft"></div><div class="column columnright"></div></div>');

			$('.MiddleCont').tabs('add', '#page-tab' + TAB_COUNT, "NEW TAB");
			//var tabs_cookie = $.cookie('tabs') == null ? '' : $cookie('tabs');


			$(".MiddleCont > ul > li:last a span").editable(function (value, settings) {
				var retValue = value.substring(0, 17);
				$.cookie(CAMPUS_ID + '_tabs_' + $(this).parent().attr('href').replace('#', ''), retValue, { expires: 100 });
				save_cookies();
				return retValue;
			},
            {
            	tooltip: "Doubleclick to edit...",
            	event: "dblclick",
            	select: true,
            	onblur: 'submit',
            	style: "inherit"
            }).dblclick();

			sortableCols();

			return false; //'page-tab' + TAB_COUNT;
		}
		else {
			return false;  //'';
		}

	});


	// URL base depending on the current campus
	//    var URL_BASE = CAMPUS_ID == "BB" ? '/Custom/secc/widgets/BB/' : '/Custom/secc/widgets/IND/';
	var URL_BASE;
	if (CAMPUS_ID == "BB" || CAMPUS_ID == "IND" || CAMPUS_ID == "OC")
		URL_BASE = '/Custom/secc/widgets/' + CAMPUS_ID + '/';
	else
		URL_BASE = '/Custom/secc/widgets/BB/';
	var loadDefault = true;


	var cookies = get_cookies_array();
	INITIAL_LOAD = false;

	// parses cookies for tabs and widget positions in the tabs
	var tabs = {};
	for (var i in cookies) {
		if (i.match(CAMPUS_ID + "_tabs")) {

			tabid = i.split('_')[2];

			TAB_COUNT++;
			if (cookies[i].match('REMOVE') == null) {
				$('.MiddleCont').prepend('<div id="' + tabid + '" class="content"><div class="column columnleft"></div><div class="column columnright"></div></div>');
				$('.MiddleCont').tabs('add', '#' + tabid, cookies[i]);
			}

		}

		// parses out widgets
		if (i.match(CAMPUS_ID + "_widget")) {
			loadDefault = false;

			widgetname = i.split('-')[1];
			pos = cookies[i].split(',');
			tabkey = pos[0];
			columnname = pos[1];
			row = pos[2];

			if (tabs[tabkey] == undefined) {
				tabs[tabkey] = {};
			}
			if (tabs[tabkey][columnname] == undefined) {
				tabs[tabkey][columnname] = Array();
			}

			tabs[tabkey][columnname][row] = widgetname;

		}
	}

	// gets widgets and displays them in their tab
	for (var t in tabs) {
		for (var c in tabs[t]) {
			for (x = 0; x < tabs[t][c].length; x++) {
				var test = tabs[t][c][x];
				/// added 8/25/10 by JOSHM, in some cases [test] would be undefined, which 
				/// loaded undefined.aspx, which returned a NotFound error.
				if (test !== undefined && test !== null && test !== "") {
					$.ajax({
						url: URL_BASE + tabs[t][c][x] + '.aspx',
						async: false,
						success: function (data, textStatus) {
							$data = $(data).appendTo('#' + t + ' > .' + c);
							$data.find('.module-panes').tabs({ cache: true });
						}
					});
				}
			}
		}
	}


	// loads default if there are no cookies tracking widgets 
	if (loadDefault) {
		var columnleft = Array();
		var columnright = Array();

		columnright.push({
			row: 0,
			name: 'welcome',
			widget: null
		});

		columnright.push({
			row: 0,
			name: 'sermons',
			widget: null
		});

		//        var upcomingToLoad = CAMPUS_ID == "BB" ? '' : 'ind';
		columnleft.push({
			row: 0,
			name: 'upcoming', 	// name: 'upcoming' + upcomingToLoad,
			widget: null
		});

		for (x = 0; x < columnleft.length; x++) {
			$.ajax({
				url: URL_BASE + columnleft[x].name + '.aspx',
				async: false,
				success: function (data) {
					$data = $(data).appendTo('#page-tabhome > .columnleft');
					$data.find('.module-panes').tabs({ cache: true });
					$.cookie(CAMPUS_ID + '_widget-' + $data.attr('class').split(' ')[1], 'page-tabhome,columnleft,' + LEFT_COUNT, { expires: 100 });
					LEFT_COUNT++;
				}
			});
		}

		for (x = 0; x < columnright.length; x++) {
			$.ajax({
				url: URL_BASE + columnright[x].name + '.aspx',
				async: false,
				success: function (data) {
					$data = $(data).appendTo('#page-tabhome > .columnright');
					$data.find('.module-panes').tabs({ cache: true });
					$.cookie(CAMPUS_ID + '_widget-' + $data.attr('class').split(' ')[1], 'page-tabhome,columnright,' + RIGHT_COUNT, { expires: 100 });
					RIGHT_COUNT++;
				}
			});
		}


	}

	// Have user added tab if the clicked "add-tab somewhere else"
	var loc = document.location.toString();
	if (loc.match('#add-tab')) {
		$('.add-tab').click();
		$('.MiddleCont').tabs('select', 'page-tab' + TAB_COUNT);
		$('.PageTabs li.ui-tabs-selected span:first').dblclick();
	}

	// shows the modules as already on the page
	$('.homepageModule').each(function (index) {
		$this = $(this);
		var moduleid = $this.attr('class').split(' ')[1];

		$('#' + moduleid).children('a').addClass('moduleAdded');
	});

	// Change look of "Add tab" button if there are already tabs
	if ($('.MiddleCont').tabs('length') > 1) {
		$('.Addtab').addClass('HasUserTabs');
	}

	// save widget positions and stop displaying the loading graphic
	save_cookies();
	$('body').unblock();

	// Add new widget to the current tab or remove it if it is already being displayed
	$('.button:not(.theme)').click(function () {
		$this = $(this);
		// remove if already on the page
		if ($this.find('a').hasClass('moduleAdded')) {
			$('.' + $this.attr('id')).remove();
			$this.find('a').removeClass('moduleAdded');
			$.cookie(CAMPUS_ID + '_widget-' + $this.attr('id'), null, { expires: 100 });
			save_cookies();
		}
		else {
			$this.addClass('widget-button-adding');
			$.get(URL_BASE + $(this).attr('id') + '.aspx', function (data) {
				var col;
				$widgetButton = $('.widget-button-adding');
				$('.homepageModule.' + $widgetButton.attr('id')).remove();
				$widgetButton.removeClass('widget-button-adding');
				$widgetButton.find('a').addClass('moduleAdded');
				$activePanel = $('.content:not(.ui-tabs-hide)');
				//Enabled column balancing - Maxim S 07/16/2010
				//                if ($activePanel.attr('id') == 'page-tabhome') {
				//                    col = '.columnright';
				//                    $data = $(data).prependTo('.content:not(.ui-tabs-hide) > ' + col);
				//                }
				//                else {
				var leftcount = $activePanel.children('.columnleft').children('.homepageModule').length;
				if ($activePanel.attr('id') == 'page-tabhome')
					leftcount = leftcount + 1; //Include spotlight in the count

				var rightcount = $activePanel.children('.columnright').children('.homepageModule').length;
				col = leftcount > rightcount ? '.columnright' : '.columnleft';
				$data = $(data).prependTo('.content:not(.ui-tabs-hide) > ' + col);
				//                }

				$data.find('.module-panes').tabs({ cache: true });

				var rowCount = 0;
				$activePanel.children(col).children('.homepageModule').each(function () {
					var colLabel = col == '.columnright' ? 'columnright' : 'columnleft';
					$.cookie(CAMPUS_ID + '_widget-' + $(this).attr('class').split(' ')[1], $activePanel.attr('id') + ',' + colLabel + ',' + rowCount, { expires: 100 });
					rowCount++;
				});
				save_cookies();
			});
		}
	});


	// make page tab names editable
	$(".MiddleCont > ul > li  a  span").editable(function (value, settings) {
		var retValue = value.substring(0, 17);
		$.cookie(CAMPUS_ID + '_tabs_' + $(this).parent().attr('href').replace('#', ''), value, { expires: 100 });
		save_cookies();
		return retValue;
	},

      {

      	tooltip: "Doubleclick to edit...",
      	event: "dblclick",
      	select: true,
      	onblur: 'submit',
      	style: "inherit"
      });

});

// sets up sorting and dragging of the modules
$(function() {

    sortableCols();

    /*$(".homepageModule")
    .find(".homepageModule-header")
    .prepend('<span class="ui-icon ui-icon-close"></span>')
    .end()
    .find(".homepageModule-content");
    */
    $(".homepageModule-header .ui-icon-close").live('click', function() {
        $module = $(this).parents(".homepageModule:first");
        var moduleid = $module.attr('class').split(' ')[1];
        $.cookie(CAMPUS_ID + '_widget-' + moduleid, null);
        save_cookies();
        $('#' + moduleid).children('a').removeClass('moduleAdded');
        $module.remove();
    });

    /*$(".homepageModule a").live('click', function() {
    $('.ui-tabs-panel').not('.ui-tabs-hide').find('.column:first').prepend($(this).parents('.homepageModule:first').clone());
    });
    */

    $(".module-select .homepageModule").draggable({
        connectToSortable: '.column',
        helper: 'clone',
        opacity: 0.7
    })

    $(".column"); //.disableSelection();
    $(".module-select").disableSelection();

});

/* Makes the columns sortable
*/
function sortableCols() {
    $(".column").sortable({
        connectWith: '.column',
        placeholder: 'placeholder',
        forcePlaceholderSize: true,
        forceHelperSize: true,
        opacity: 0.7,
        revert: '100',
        update: function(event, ui) {
            $column = $(this);
            incolumn = $column.hasClass('columnleft') ? 'columnleft' : 'columnright';
            tabkey = $column.parent().attr('id');
            row = 0;
            $(this).children(".homepageModule").each(function() {
                $.cookie(CAMPUS_ID + '_widget-' + $(this).attr('class').split(' ')[1], tabkey + ',' + incolumn + "," + row, { expires: 10 });
                row++;
            });
            save_cookies();
        },
        handle: '.homepageModule-header',
        items: '.homepageModule'
    });
}
