/*globals MSGV, MSGVFASDialog, polopoly, jq14, KenzanDebug, addSchool, loc, getUserData, currentRegion */
(function($) {
	/**
	 * Requires jquery
	 */
    if(window.location.search.indexOf('debug=true') !== -1){
            KenzanDebug.logger.enable();
        }
    var log = KenzanDebug.NamedLogger("window.MSGVFASDialog");
    log.debug("creating MSGV.Phts stuff");
	window.MSGVFASDialog = {
		options: {
			modalDialogClass: "fas-modal-dialog",
			modalConfirmClass: "fas-modal-confirm",
			loadSchoolsUrlFunc: function(tabRegion) {
				return "/findschool?regionCategoryId=" + tabRegion;
			},
			acceptSchoolUrlFunc: function(schoolDeptId, schoolCategoryId) {
                return '/addSchool?schoolDeptId=' + schoolDeptId +
                    '&schoolCategoryId=' + schoolCategoryId;
			},
            schoolHomePageUrlFunc: function(regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId) {
                return '/' + (regionPath ? regionPath: regionDeptId) + '/' +
                    (schoolPath ? schoolPath: schoolDeptId);
			},
            acceptSchool: function(schoolName, regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId, find_or_add) {
                log.debug('find_or_add: ' + find_or_add);
				var gotoSchoolHomePage = function(regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId) {
					loc = MSGVFASDialog.options.schoolHomePageUrlFunc(regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId);
					location.href = loc;
				};
				// post selection so save school controller
				if (find_or_add === 'add') {
					addSchool(schoolCategoryContentId);
				} else {
					// no post-back go straight to selected school's home-page
                    gotoSchoolHomePage(regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId);
				}
			},
			filterSchool: function(schoolName, schoolDeptId, schoolCategoryContentId) {
                loc = location.pathname + location.search + '&schoolCategoryId=' +
                    schoolDeptId + '&schoolName=' + schoolName;
				location.href = loc;
			},
			fasLinkElemExpr: ".findaschoollink",
            fasAddElemExpr: ".addSchool",
			fasFilterElemExpr: ".filterschoollink"
		},

		fasDialog: null,

		init: function(opts) {
			for (var key in opts) {
			    if (typeof opts != 'undefined' && opts) {
					MSGVFASDialog.options[key] = opts[key];
				}
			}

			$('.changeRegion').click(function() {
				MSGVFASDialog.showRegionDialog();
				return false;
            });

			$(MSGVFASDialog.options.fasLinkElemExpr).click(function() {
				$(this).mouseout();
				MSGVFASDialog.showFASDialog();
                window.scroll(0, 0);
				return false;
			});

            $(MSGVFASDialog.options.fasAddElemExpr).click(function() {
				$(this).mouseout();
				MSGVFASDialog.showFASDialog('add');
                window.scroll(0, 0);
				return false;
			});

			$(MSGVFASDialog.options.fasFilterElemExpr).click(function() {
				MSGVFASDialog.showFASFilter();
				$(this).mouseout();
				window.scroll(0, 0);
				return false;
			});
		},

		showFASDialog: function(find_or_add) {
            MSGVFASDialog.fasDialog = $('._find_a_school_dialog');
            if (find_or_add === 'add') {
                MSGVFASDialog.fasDialog = $('._add_a_school_dialog');
            }
			try {
                var offset = $('.main_menu').offset();
				if (offset.top == - 1) {
					offset.top = 200;
                    offset.left = 250;
				}
				var styledPopup = MSGV.StyledPopup({
					popup: MSGVFASDialog.fasDialog,
					pos: {
						top: offset.top + 20,
						left: offset.left + 350
					}
				});

				styledPopup.show();
				MSGVFASDialog.fasDialog.data("styledPopup", styledPopup);

			} catch(e) {}

			setTimeout(function() {
                MSGVFASDialog.showFASTab(find_or_add);
			},
			1);

			$(".close-button a, .closeLink").click(function() {
				MSGVFASDialog.hideFASDialog();
			});

		},

		showFASFilter: function() {

            MSGVFASDialog.fasFilter = $('._find_a_school_filter');

			try {
                var offset = $('.main_menu').offset();
				if (offset.top == - 1) {
					offset.top = 200;
                    offset.left = 250;
				}
				var styledPopup = MSGV.StyledPopup({
					popup: MSGVFASDialog.fasFilter,
					pos: {
						top: offset.top + 20,
						left: offset.left + 350
					}
				});

				styledPopup.show();
				MSGVFASDialog.fasFilter.data("styledPopup", styledPopup);

			} catch(e) {}

			setTimeout(function() {
				// region = $("._find_a_school_filter .fas-tabs div a").attr("regionId");
				var region = MSGVFASDialog.getParam("regionid");
                MSGVFASDialog.showFilterTab(region);
			},
			1);

			$(".close-button a, .closeLink").click(function() {
				MSGVFASDialog.hideFASFilter();
			});

		},

		getParam: function(name) {
			var regexS = "[\\?&]" + name + "=([^&#]*)";
			var regex = new RegExp(regexS);
			var tmpURL = window.location.href;
			var results = regex.exec(tmpURL);
            if (results === null) {
                return "";
            } else {
                return results[1];
            }
		},

		hideFASFilter: function() {
            MSGVFASDialog.fasFilter.data("styledPopup").hide();
		},

		hideFASDialog: function() {
			$('.activeFindSchool').removeClass('activeFindSchool');
			MSGVFASDialog.fasDialog.data("styledPopup").hide();
		},

		getUserData: function() {
			var userData = polopoly.cookie.get('msgvarsity-user');
			var obj = jq14.parseJSON(polopoly.base64.decode(userData));
			return obj;
		},

		showFASTab: function(find_or_add, region) {
			if (typeof region == 'undefined' || ! region) {
				var obj = getUserData();
				if (polopoly.user.isLoggedIn() && obj !== null && obj.regionCategoryId) {
					region = obj.regionCategoryId;
				} else if (currentRegion !== null && currentRegion !== "") {
					region = currentRegion;
				} else {
					region = $(".fas-tabs div a").attr("regionId");
				}
			}

			$(".fas-tabs div a").each(function() {
				if ($(this).attr("id") == "fas-tab" + region) {
					$(this).addClass("selected");
				} else {
					$(this).removeClass("selected");
				}
			});

			var theUrl = MSGVFASDialog.options.loadSchoolsUrlFunc(region);
			if (polopoly.user.isLoggedIn()) {
                $('.non-auth').hide();
			} else {
                $('.auth').hide();
			}
			// show loading indicator
			$(".fas-schoollist").html("<img class='loadingimg' src='../img/msgv/widgets/loading-1-0.gif' alt='loading schools...'/>");

			$.ajax({
				url: theUrl,
				success: function(data) {
					var jsonSchoolList = eval("(" + data + ")");
					if (!jsonSchoolList || jsonSchoolList.length === 0) {
						$(".fas-schoollist").html("<p>Sorry, your search returned no schools.</p>");
						return;
					}

					var schoolList = [];
					schoolList.push("<ul>");
					for (var i = 0; i < jsonSchoolList.length; i++) {
						var jsonSchool = jsonSchoolList[i];
                        schoolList.push("<li><a class='fas-school' href=\"javascript:MSGVFASDialog.acceptSchool" +
                        		"('" + MSGVFASDialog.replaceSQuotes(jsonSchool.schoolName) + "','" +
                        		MSGVFASDialog.replaceSQuotes(jsonSchool.regionDepartmentContentId) + "','" +
                        		MSGVFASDialog.replaceSQuotes(jsonSchool.regionDepartmentPath) + "','" +
                        		MSGVFASDialog.replaceSQuotes(jsonSchool.schoolDepartmentContentId) + "','" +
                        		MSGVFASDialog.replaceSQuotes(jsonSchool.schoolDepartmentPath) + "','" +
                        		MSGVFASDialog.replaceSQuotes(jsonSchool.schoolCategoryContentId) + "','" + find_or_add +  "')\" >" + jsonSchool.schoolName + "</a></li>");
					}
					schoolList.push("</ul>");
					$(".fas-schoollist").html(schoolList.join('\n'));
				}
			});
		},

		showFilterTab: function(region) {
			if (region == "All") {
				region = $(".fas-tabs div a").attr("regionId");
			} else if (typeof region === 'undefined' || ! region) {
				var obj = getUserData();
				if (polopoly.user.isLoggedIn() && obj !== null && obj.regionCategoryId) {
					region = obj.regionCategoryId;
				} else {
					region = $(".fas-tabs div a").attr("regionId");
				}
			}

			$(".fas-tabs div a").each(function() {
				if ($(this).attr("id") == "fas-tab" + region) {
					$(this).addClass("selected");
				} else {
					$(this).removeClass("selected");
				}
			});

			var theUrl = MSGVFASDialog.options.loadSchoolsUrlFunc(region);

			// show loading indicator
			$(".fas-schoollist").html("<img class='loadingimg' src='../img/msgv/widgets/loading-1-0.gif' alt='loading schools...'/>");

			$.ajax({
				url: theUrl,
				success: function(data) {
					var jsonSchoolList = eval("(" + data + ")");

					if (!jsonSchoolList || jsonSchoolList.length === 0) {
						$(".fas-schoollist").html("<p>Sorry, your search returned no schools.</p>");
						return;
					}

					var schoolList = [];
					schoolList.push("<ul>");
					for (var i = 0; i < jsonSchoolList.length; i++) {
						var jsonSchool = jsonSchoolList[i];

						schoolList.push("<li><a class='fas-school' href=\"javascript:MSGVFASDialog.filterSchool(" + "'" + MSGVFASDialog.replaceSQuotes(jsonSchool.schoolName) + "', '" + MSGVFASDialog.replaceSQuotes(jsonSchool.regionDepartmentContentId) + "', '" + MSGVFASDialog.replaceSQuotes(jsonSchool.regionDepartmentPath) + "', '" + MSGVFASDialog.replaceSQuotes(jsonSchool.schoolDepartmentContentId) + "', '" + MSGVFASDialog.replaceSQuotes(jsonSchool.schoolDepartmentPath) + "', '" + MSGVFASDialog.replaceSQuotes(jsonSchool.schoolCategoryContentId) + "'" + ")\" " +
								">" + jsonSchool.schoolName + "</a></li>");
					}

					schoolList.push("</ul>");
					$(".fas-schoollist").html(schoolList.join('\n'));
				}
			});
		},

		replaceSQuotes: function(str) {
			str = str.replace(/'/g, "\\'");
            return str;
		},

		confirmSchool: function(schoolName, regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId) {

			MSGVFASDialog.hideFASDialog();

			MSGVFASDialog.fasDialog = $("<div class='styledPopup _fas_confirm_dialog' id='_find_a_school_dialog' style='position:absolute; width: 500px; height: 250px;'></div>").html("<div class='closeLink'></div>" + "<div class='fas-confirm-main'>" + "  <p>Do you want to save " + schoolName + " to your list of Favorite Schools?</p>" + "</div>" + "<div class='fas-confirm-btns'><div class='button yes'><span class='text'>Yes</span></div>" + "<div class='button no'><span class='text'>Not Now</span></div>" + "</div>").appendTo("body");

			MSGVFASDialog.fasDialog.find(".fas-confirm-btns .yes").click(function() {
				MSGVFASDialog.acceptSchool(
                    MSGVFASDialog.replaceSQuotes(schoolName),
                    MSGVFASDialog.replaceSQuotes(regionDeptId),
                    MSGVFASDialog.replaceSQuotes(regionPath),
                    MSGVFASDialog.replaceSQuotes(schoolDeptId),
                    MSGVFASDialog.replaceSQuotes(schoolPath),
                    MSGVFASDialog.replaceSQuotes(schoolCategoryContentId)
                );
            });

            MSGVFASDialog.fasDialog
                .find(".fas-confirm-btns .no")
                .click(MSGVFASDialog.rejectSchool);

			try {
				var styledPopup = MSGV.StyledPopup({
					popup: MSGVFASDialog.fasDialog,
					pos: {
						top: 200,
						left: 500
					}
				});
				styledPopup.show();
				MSGVFASDialog.fasDialog.data("styledPopup", styledPopup);
			} catch(e) {
				alert(e);
			}
		},

		acceptSchool: function(schoolName, regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId, find_or_add) {
			MSGVFASDialog.options.acceptSchool(schoolName, regionDeptId, regionPath, schoolDeptId, schoolPath, schoolCategoryContentId, find_or_add);
			MSGVFASDialog.hideFASDialog();
		},

		filterSchool: function(schoolName, regionDeptId, regionDepartmentPath, schoolDeptId, schoolDepartmentPath, schoolCategoryContentId) {
			//MSGVFASDialog.options.acceptSchool(schoolName, regionDeptId, schoolDeptId, schoolCategoryContentId);
			var search = location.search;
			search = search.replace("?", "");
			var params = search.split(/&/);
			search = "";
			for (var i = 0; i < params.length; i++) {
                var str = params[i];
				if (str.indexOf("schoolid") < 0 && str.indexOf("currentPage")) {
					search += params[i] + "&";
				}
			}

			loc = location.pathname + "?" + search + 'schoolid=' + schoolDeptId;

			location.href = loc;
			MSGVFASDialog.hideFASDialog();
		},

		rejectSchool: function() {
			MSGVFASDialog.hideFASDialog();
		},

		buildUsersSchools: function() {
			var menuList = '',
			filterList = '',
			search = window.location.search,
			_userschools = polopoly.cookie.get('user-schools'),
			obj = jq14.parseJSON(polopoly.base64.decode(_userschools));
			jq14.each(obj, function(i, s) {
				menuList += '<li class=\"schoolLink\"><a href=\"/' + (s.rp ? s.rp: s.r) + '/' + (s.sp ? s.sp: s.s) + '\">' + s.n + '</a></li>';
				filterList += '<li><a href=\"' + search + '&schoolid=' + s.s + '\">' + s.n + '</a></li>';
			});
			jq14('.main_menu .myschools').after(menuList).remove();
			// jq14('.filter .myschools').after(filterList).remove();
        },
        showRegionDialog: function() {

            MSGVFASDialog.fasDialog = $('._find_a_region_dialog');

            try {
                var offset = $('.changeRegion').offset();
                if (offset.top == - 1) {
                    offset.top = 200;
                    offset.left = 250;
                }
                var styledPopup = MSGV.StyledPopup({
                    popup: MSGVFASDialog.fasDialog,
                    pos: {
                        top: offset.top - 20,
                        left: offset.left - 10
                    }
                });

                styledPopup.show();
                MSGVFASDialog.fasDialog.data("styledPopup", styledPopup);

            } catch(e) {}

            $("._find_a_region_dialog .closeLink").click(function() {
                $("._find_a_region_dialog").hide();
            });
        }
    };


})(jq14);


