// Site Wide Global Objects
var SiteUser = {
    UserEmail: "",
    User_ID: 0,
    UserLevel: 0,
    UserName: "",
    UserVerified: false
}
var SiteParams = {
    Login: {
        Div: "#loginBar",
        UserInfoURL: "/section/sun&template=userinfo"
    }
}

// Site wide support object
function SiteScripts() {

	this.InitGuides = function() {
        $('#guideList').accordion();
    }
	
    this.Init = function() {
		this.InitGuides();
    }

}

// ####### Most Read/Most Commented Tabs
function MostNews() {
	$("div.most-com").hide();
	$("a.mostReadTab").bind("click", function(e) {
		e.preventDefault();
		$("a.mostReadTab").parent().addClass('selected'); // Show the tab
		$("div.most-pop").show(); // Show the Content
		$("a.mostComTab").parent().removeClass('selected');  // Hide other tab(s) 
		$("div.most-com").hide(); // Hide other Content
	});
	$("a.mostComTab").bind("click", function(e) {
		e.preventDefault();
		$("a.mostComTab").parent().addClass('selected'); // Show the tab
		$("div.most-com").show(); // Show the content
		$("a.mostReadTab").parent().removeClass('selected'); // Hide other Tab(s)
		$("div.most-pop").hide(); // Hide other content
	});
};
// #######################################################################

// ####### Hot Ads Tabs
function HotAds() {
	$("div.hotProperties").hide();
	$("div.hotMerchandise").hide();
	$("a.adJobsTab").bind("click", function(e) {
		e.preventDefault();
		$("a.adJobsTab").parent().addClass('selected'); // Show the tab
		$("div.hotJobs").show(); // Show the Content
		$("a.adPropertiesTab").parent().removeClass('selected');  // Hide other tab(s) 
		$("div.hotProperties").hide(); // Hide other Content
		$("a.adMerchandiseTab").parent().removeClass('selected');  // Hide other tab(s) 
		$("div.hotMerchandise").hide(); // Hide other Content
	});
	$("a.adPropertiesTab").bind("click", function(e) {
		e.preventDefault();
		$("a.adPropertiesTab").parent().addClass('selected'); // Show the tab
		$("div.hotProperties").show(); // Show the content
		$("a.adJobsTab").parent().removeClass('selected'); // Hide other Tab(s)
		$("div.hotJobs").hide(); // Hide other content
		$("a.adMerchandiseTab").parent().removeClass('selected');  // Hide other tab(s) 
		$("div.hotMerchandise").hide(); // Hide other Content
	});
	$("a.adMerchandiseTab").bind("click", function(e) {
		e.preventDefault();
		$("a.adMerchandiseTab").parent().addClass('selected'); // Show the tab
		$("div.hotMerchandise").show(); // Show the content
		$("a.adJobsTab").parent().removeClass('selected'); // Hide other Tab(s)
		$("div.hotJobs").hide(); // Hide other content
		$("a.adPropertiesTab").parent().removeClass('selected');  // Hide other tab(s) 
		$("div.hotProperties").hide(); // Hide other Content
	});
};
// #######################################################################


// ####### Hot Ads Tabs
function Galleries() {
	$("div.galleryVideo").hide();
	$("a.photoTab").bind("click", function(e) {
		e.preventDefault();
		$("a.photoTab").parent().addClass('selected'); // Show the tab
		$("div.galleryPhoto").show(); // Show the Content
		$("a.videoTab").parent().removeClass('selected');  // Hide other tab(s) 
		$("div.galleryVideo").hide(); // Hide other Content
	});
	$("a.videoTab").bind("click", function(e) {
		e.preventDefault();
		$("a.videoTab").parent().addClass('selected'); // Show the tab
		$("div.galleryVideo").show(); // Show the content
		$("a.photoTab").parent().removeClass('selected'); // Hide other Tab(s)
		$("div.galleryPhoto").hide(); // Hide other content
	});
};
// #######################################################################


// ####### Hot Properties - Show's a tooltip on mouseover with the contents of the object
function HotPropertiesTips() {
	$("a.hotproperty").each(function() {
		var link = this;
		$(this).bind("click", function(e) { e.preventDefault(); });
		$(this).qtip({
			content: { url: link.href },
			style: { width: 300, border: { width: 2, radius: 3, color: '#3c3c3c' } },
			show: { when: 'mouseover', solo: true },
			position: { corner: {	target: 'leftMiddle', tooltip: 'rightMiddle' } }
		});
	});
};

// #######################################################################


// ####### Hot Jobs - Show's a tooltip on mouseover with the contents of the object
function HotJobsTips() {
	$("a.hotjob").each(function() {
		var link = this;
		$(this).bind("click", function(e) { e.preventDefault(); });
		$(this).qtip({
			content: { url: link.href },
			style: { width: 300,	border: { width: 2, radius: 3, color: '#3c3c3c'	} },
			show: { when: 'mouseover', solo: true },
			position: { corner: { target: 'leftMiddle', tooltip: 'rightMiddle' } }
		});
	});
};
// #######################################################################

// ####### Hot Merchandise - Show's a tooltip on mouseover with the contents of the object
function HotMerchandiseTips() {
	$("a.hotmerchandise").each(function() {
		var link = this;
		$(this).bind("click", function(e) { e.preventDefault(); });
		$(this).qtip({
			content: { url: link.href },
			style: { width: 300,	border: { width: 2, radius: 3, color: '#3c3c3c'	} },
			show: { when: 'mouseover', solo: true },
			position: { corner: { target: 'leftMiddle', tooltip: 'rightMiddle' } }
		});
	});
};
// #######################################################################

// ####### Global Utility Functions
function AjaxFormAction(Form) {  // Redirects Form Actions to AJAX Templates and objects.
    var AjaxURL = $(Form).attr("action");
    if (AjaxURL.indexOf("&") == -1) { AjaxURL += "&"; }
    var AjaxURL = AjaxURL.replace(/section\/\w+&/, "section/AJAX&").replace(/Category=\w+&/, "Category=AJAX&");
    $(Form).attr("action", AjaxURL);
    var Redirect = $(Form).find("input[name='RedirectURL']");
    if ($(Redirect).length > 0) {
        var AjaxRedirect = $(Redirect).val();
        if (AjaxRedirect.indexOf("&") == -1) { AjaxRedirect += "&"; }
        AjaxRedirect = AjaxRedirect.replace(/section\/\w+&/, "section/AJAX&").replace(/Category=\w+&/, "Category=AJAX&");
        $(Redirect).val(AjaxRedirect);
    }
}

function AjaxURL(URL) {
    if (URL.indexOf("&") == -1) { URL += "&"; }
    return URL.replace(/section\/\w+&/, "section/AJAX&").replace(/Category=\w+&/, "Category=AJAX&");
}

function gup( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
};
// ############################################################

// ####### Site Registration Form
function RegistrationForm(form, responseID) {
	$(form).ajaxForm({
		beforeSubmit: function() {
			$(form).mask("Please wait..");
		},
		success: function(responseText, statusText) {
			if (responseText.indexOf(responseID) != -1) {
				$(form).find("#"+responseID).replaceWith(responseText);
			} else {
				$("#regArea").replaceWith(responseText);
			}
			$(form).unmask();
		}
	});
};
// ############################################################


// ####### User Maintenance Functions
function LoginTools() {
    var Targets = new Array();
    $.map(arguments, function(n, i) {
        if ($(n).length > 0) {
            var Details = $(n).attr("title").split("|");
            var TargetObj = {
                Element: $(n),
                Title: Details[0],
                URL: Details[1],
                ButtonClass: Details[2]
            };
            Targets.push(TargetObj);
        };
    });
    
    function CreateTip(target) {
        $(target.Element).qtip({
            content: { title: { text: "<h3>"+target.Title+"</h3>", button: "Close" }, url: target.URL },
            position: { target: $(document.body), corner: 'center' },
            show: { when: 'click', solo: true },
            hide: false,
            style: { name: 'light', width: 500, border: { width: 2, radius: 8, color: '#3C3C3C'} },
            api: {
                onHide: function() { ResetTip(target); }
            }
        });
    };

    function ResetTip(target) {
        $(target.Element).qtip("destroy");
        CreateTip(target);
    };
    
    $.map(Targets, function(n, i) {
        CreateTip(n);
        $(n.ButtonClass).live("click", function(e) {
            e.preventDefault();
            $(n.Element).trigger("click");
        });
    });
};
function PrepLogin(settings) {
    var Options = {
        tipWrapper: $("div#MainWrapper"),
        loginWrapper: $("div#MainWrapper").children("div#loginWrapper"),
        loginForm: $("div#MainWrapper").children("div#loginWrapper").children("#loginForm"),
        emailWrapper: $("div#MainWrapper").children("div#emailWrapper"),
        emailForm: $("div#MainWrapper").children("div#emailWrapper").children("#emailForm")
    };

    function AjaxLoginForm() {
        AjaxFormAction(Options.loginForm);
        $(Options.loginForm).ajaxForm({
            beforeSubmit: function() {
                $(Options.loginForm).mask("Logging in");
            },
            success: function(responseText, statusText) {
                $(Options.loginForm).unmask();
                var Response = JSON.parse(responseText);
                if (Response.Data.Status) {
                    UserLoggedIn(Options.tipWrapper, Response.Data.UserInfo);
                } else {
                    $(Options.loginForm).find("#errorBox").removeClass('hide');
                }
                //                if (responseText.length > 0) {
                //                    $(Options.loginForm).find("#errorBox").removeClass('hide');
                //                } else {
                //                    $(Options.loginForm).find("#errorBox").addClass('hide');
                //					LoginObj.LoginComplete();
                //                }
            }
        });
    };

    function AjaxEmailForm() {
        $(Options.emailForm).ajaxForm({
            beforeSubmit: function() {
                $(Options.emailForm).mask("Please wait..");
            },
            success: function(responseText, statusText) {
                $(Options.emailForm).unmask();
                var redirect = responseText.replace("<script>setTimeout(\"location.href='", "").replace("'\",1000);</script>", "");
                $(Options.emailWrapper).find("#responseMsg").load(redirect);
            }
        });
    };

    function PrepButtons() {
        $(Options.loginForm).find("#bttn-password").bind("click", function(e) {
            e.preventDefault();
            $(Options.loginWrapper).addClass('hide');
            $(Options.emailWrapper).removeClass('hide');
        });
        $(Options.emailWrapper).find("#bttn-return").bind("click", function(e) {
            e.preventDefault();
            $(Options.emailWrapper).addClass('hide');
            $(Options.loginWrapper).removeClass('hide');
        });
    };

    PrepButtons();
    AjaxLoginForm();
    AjaxEmailForm();
};
function PrepEditUserForm() {
    var FormWrapper = $("#editUserFormWrapper");
    var UserForm = $("#editUserForm");
    $(UserForm).ajaxForm({
        beforeSubmit: function() {
            $(UserForm).mask("Please wait...");
            return true;
        },
        success: function(responseText, statusText) {
            $(UserForm).unmask();
            var msg = $(responseText).find(".ureg-msg").html();
            $(FormWrapper).find(".ureg-msg").html(msg);
            if (msg.indexOf("saved") == -1) {
                $(FormWrapper).find("#errorWrap").addClass("ui-state-error");
                $(FormWrapper).find("#errorWrap").removeClass("ui-state-highlight");
                $(FormWrapper).children("#errorBox").removeClass('hide');
            } else {
                $(FormWrapper).find("#errorWrap").removeClass("ui-state-error");
                $(FormWrapper).find("#errorWrap").addClass("ui-state-highlight");
                $(FormWrapper).children("#errorBox").removeClass('hide');
            }
        }
    });
}
function PrepProfileForm() {
    var FormWrapper = $("#profileWrapper");
    var ProfileForm = $("#forumpreffrm");
    $(ProfileForm).ajaxForm({
        beforeSubmit: function() {
            $(ProfileForm).mask("Please wait...");
            return true;
        },
        success: function(responseText, statusText) {
            $(ProfileForm).unmask();
            var rn = Math.floor(Math.random() * 99999999);
            $.post("/apps/pbcs.dll/forumoptions?category=sun", { R: rn },
				function(data, status) {
				    $(FormWrapper).replaceWith(data);
				    $("#profileWrapper").children("div#message").load("/apps/pbcs.dll/misc&url=/misc/prefsSaved.pbs");
				}
			);
        }
    });
}
function UserLoggedIn(Form, UserInfo) {
    $(Form).parents(".qtip").qtip("hide");
    var rn = Math.floor(Math.random() * 99999999);
    $(SiteParams.Login.Div).load(SiteParams.Login.UserInfoURL, { R: rn });
    SiteUser = UserInfo;
    CommentsVisibility();
	PhotoSharingVisibility();
	ContestsVisibility();
	eEditionVisibility();
};
function UserLoggedOut(UserInfo) {
    var rn = Math.floor(Math.random() * 99999999);
    $(SiteParams.Login.Div).load(SiteParams.Login.UserInfoURL, { R: rn });
    SiteUser = UserInfo;
    CommentsVisibility();
	PhotoSharingVisibility();
	ContestsVisibility();
	eEditionVisibility();
};
// Self Executing Logout Ajax - targets any '.logoutBttn' click.
function Logout() {
    this.EatAndRun = function(link) {
        document.cookie = "usernamepassword=;Path=/";
        document.cookie = "UserRegID=;Path=/";
        var rn = Math.floor(Math.random() * 99999999);
        $.post("/section/AJAX&template=userreglogin&RegLogout=1", { R: rn }, function(responseText) {
            var Response = JSON.parse(responseText);
            UserLoggedOut(Response.Data.UserInfo);
        }, "html");
    };

    $(".logoutBttn").live("click", function(e) {
        e.preventDefault();
        EatAndRun(e.currentTarget);
    });
};
$(document).ready(function() { Logout(); });
// ############################################################################

// ####### Small Calendar (displayed anywhere on the site except the events page)
function SmallCalendar() {
	function RenderCalendar(cURL) {
		var Calendar = $("div#CalendarSmall");
		$.ajax({
			type: "GET",
			url: cURL,
			dataType: "html",
			cache: false,
			beforeSend: function() { $(Calendar).mask("Loading ..."); },
			success: function(responseHTML) {
				$(Calendar).unmask();
				$(Calendar).find(".events-calendar .calendar-holder:first").html($(responseHTML).find(".calendar-holder:first").html());
				$(Calendar).find(".events-calendar .calendar-controls:first").html($(responseHTML).find(".calendar-controls:first").html());
				$(Calendar).find(".events-calendar .calendar-list:first").html($(responseHTML).find(".calendar-list:first").html());
			}
		});
	};
	
	var Calendar = $("div#CalendarSmall");
	if ($(Calendar).length != 0) {
		$(Calendar).find("a.calday").live("click", function(e) {
			e.preventDefault();
			RenderCalendar(this.href);
		});
		$(Calendar).find(".calendar-controls a").live("click", function(e) {
			e.preventDefault();
			RenderCalendar(this.href);
		});
		$(Calendar).find("a.eventDetails").live("click", function(e) {
			e.preventDefault();
			$(Calendar).mask();
			var $tip = $("<div></div>");
			$tip.appendTo("body");
			$tipContent = $(this).parent("span").find("div.eventTipContent").html();
			$($tip).qtip({
				content: { title: { text: "<h1>"+this.title+"</h1>", button: "Close" }, text: $($tipContent) },
				position: { target: $(Calendar), corner: { target: 'topMiddle', tooltip: 'rightMiddle' } },
				show: { when: 'click', solo: true },
				hide: false,
				style: {name: 'light', width: 500, border: { width: 2, radius: 8, color: '#3C3C3C' } },
				api: {
					onShow: function() {
						var evtDates = $($tip).qtip("api").elements.content.find("span.eventDates").html();
						var $Cal = $($tip).qtip("api").elements.content.find("div.Calendar").Calendar();
						$Cal.Calendar().parseDates(evtDates);
					},
					onHide: function() { $(Calendar).unmask(); DestroyTip($tip); }
				}
			});
			$tip.trigger("click");
		});
	};
	
	function DestroyTip(t) {
		$(t).qtip("destroy");
		$(t).remove();
	};
}; 
// ##########################################################

// ####### Event Calendar (displayed on the main events page)
function DatesCalendar() {
	var $Events = $("#eventsWrapper");
	var $Calendar = $("#CalendarDates");
	var $Col = $("div.col-a:first");
	var $Form = $("#CalendarDates form#eventsSearch");
	
	$("#CalendarDates a.calday").live("click", function(e) {
		e.preventDefault();
		$.ajax({
			type: "GET",
			url: this.href,
			dataType: "html",
			cache: false,
			beforeSend: function() { $($Col).mask("Please wait..."); },
			success: function(responseHTML) { $($Events).html(responseHTML); $($Col).unmask(); }
		});
	});
	
	$("#CalendarDates .calendar-controls a").live("click", function(e) {
		e.preventDefault();
		$.ajax({
			type: "GET",
			url: this.href,
			dataType: "html",
			cache: false,
			beforeSend: function() { $($Calendar).mask("Loading ..."); },
			success: function(responseHTML) {
				$($Calendar).unmask();
				$($Calendar).find(".events-calendar .calendar-holder:first").html($(responseHTML).find(".calendar-holder:first").html());
				$($Calendar).find(".events-calendar .calendar-controls:first").html($(responseHTML).find(".calendar-controls:first").html());
			}
		});
	});

	this.SearchValid = function() {
		var ret = false;
		$($Form).find(":input").each(function() {
			if ($(this).val()!="") { ret = true; };
		});
		if (ret) {
			var FromDate = $($Form).find("input[Name='evt_FromDate']").val();
			var ToDate = $($Form).find("input[Name='evt_ToDate']").val();
			if ((FromDate!="" && ToDate=="") || (FromDate=="" && ToDate!="")) {
				alert("Please enter both a From and To Date to search");
				ret = false;
			};
		} else {
			alert("Please enter some search criteria");
		};
		return ret;
	};

	$dpElements = $($Form).find(".dp");
	$dpElements.datepicker({
		showOn: 'both',
		buttonImage: '/images/calendar.png',
		buttonImageOnly: true,
		minDate: new Date(),
		dateFormat: 'yymmdd'
	});
	
	this.Search = function() {
		$($Form).ajaxForm({
			beforeSend: function() { $($Form).mask(); $($Col).mask("Searching Events"); },
			success: function(responseHtml) { $($Form).unmask(); $($Col).unmask(); $($Events).html(responseHtml); }
		});
		$($Form).submit();
	};
	
	$($Form).find("#bttnSearch").bind("click", function() {
		if (SearchValid()) {
			Search();
		};
		return false;
	});
};
// ##########################################################

function DateCalendarSearchInitialize(){
	var $Form = $("form#formSearch");
		$dp = $($Form).find(".dp");
		$dp.datepicker({
			showOn: 'both',
			buttonImage: '/images/calendar.png',
			buttonImageOnly: true,
			dateFormat: 'yy/mm/dd'
		});
}
// ####### Events List (displayed on the main events page)
function EventsList() {
	$("a.eventListItem").live("click", function(e) {
		e.preventDefault();
		var $tip = $("<div></div>");
		$tip.appendTo("body");
		var $tipParent = $(this).parents("li:first");
		var $tipContent = $($tipParent).find("div.eventTipContent").html();
		$($tip).qtip({
			content: { title: { text: "<h1>"+this.title+"</h1>", button: "Close" }, text: $($tipContent) },
			position: { target: $($tipParent), corner: { target: 'leftMiddle', tooltip: 'leftMiddle' }, adjust: { x: 90, y: 0 } },
			show: { when: 'click', solo: true },
			hide: false,
			style: {name: 'light', width: 500, border: { width: 2, radius: 8, color: '#3C3C3C' } },
			api: {
				onShow: function() {
					var evtDates = $($tip).qtip("api").elements.content.find("span.eventDates").html();
					var $Cal = $($tip).qtip("api").elements.content.find("div.Calendar").Calendar();
					$Cal.Calendar().parseDates(evtDates);
				},
				onHide: function() { DestroyTip($tip); }
			}
		});
		$tip.trigger("click");
	});
	
	function DestroyTip(t) {
		$(t).qtip("destroy");
		$(t).remove();
	};
};

// ##########################################################

// ####### Events Submission (displayed on the main events page)
function EventSubmission() {
	$form = $("#eventForm");
	$("input[SRMField*='FromDate'],input[SRMField*='ToDate']").datepicker({
		showOn: 'both',
		buttonImage: '/images/calendar.png',
		buttonImageOnly: true,
		minDate: new Date()
	});
	$("input[Name='sPattern']").bind("change", function(e) {
		$("div#Pattern1").addClass('hide');
		$("div#Pattern2").addClass('hide');
		$("div#Pattern3").addClass('hide');
		$("div#Pattern"+this.value).toggleClass('hide');
	});
	$("input[Name='dSM']").bind("change", function(e) {
		$("span#dSM0").addClass('hide');
		$("span#dSM1").addClass('hide');
		$("span#dSM"+this.value).toggleClass('hide');
	});
	$("input[Name='wSM']").bind("change", function(e) {
		$("span#wSM0").addClass('hide');
		$("span#wSM1").addClass('hide');
		$("span#wSM"+this.value).toggleClass('hide');
	});
	$("input[Name='mSM']").bind("change", function(e) {
		$("span#mSM0").addClass('hide');
		$("span#mSM1").addClass('hide');
		$("span#mSM"+this.value).toggleClass('hide');
	});
	$("input.TimeType").bind("change", function(e) {
		$("#Times").addClass('hide');
		if (Number(this.value) == 0) { $("#Times").toggleClass('hide'); }
	});
	$("#FT,#TT").timeEntry({ spinnerImage: '/images/time/spinnerOrange.png', show24Hours: true, separator: '' });
	window.$RM = new SaxotechRecurrenceModel("eventForm",true);
	
	this.EventValid = function() {
		var ret = true;
		$form.find("div.required :input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass("white");
			};
		});
		return ret;
	};
		
	this.SubmitForm = function() {
		window.$RM.WriteFields();
		$($form).ajaxForm({
			beforeSend: function() { $($form).mask("Submitting Event"); },
			success: function(responseHtml) {
				$($form).unmask();
				$($form).replaceWith(responseHtml);
				window.$RM.Destroy();
				window.$RM = undefined;
			}
		});
		$($form).submit();
	};
	
	$($form).find("#submitBttn").bind("click", function(e) {
		if (EventValid()) {
			SubmitForm();
		}
		return false;
	});
}
// ##########################################################

function PhotoSharingVisibility() {
	$("#post").addClass('hide');
    $("#notValid").addClass('hide');
    $("#notLoggedIn").addClass('hide');
	
    if (SiteUser.User_ID > 0) {
        if (SiteUser.UserVerified) { $("#post").removeClass('hide'); }
        else { $("#notValid").removeClass('hide'); }
    } else {
        $("#notLoggedIn").removeClass('hide');
    };
};

// ####### Article Jumps
function ArticleJumps() {
	$("a.jumpLink").each(function() {
		$(this).bind("click", function(e) {
			$.scrollTo( $(this.target), 500);
			e.preventDefault();
		});
	});
};
// ##########################################################

// ####### Contests 
function ContestsVisibility() {
	var url = document.location.href+"&Template=AjaxArticle";
	var Contest = $("#ContestAjax");
	$(Contest).mask();
	$(Contest).load(url, function() { $(Contest).unmask(); });
};
// ##########################################################

// ####### eEditions
function eEditionVisibility() {
	var url = document.location.href+"&Template=AjaxeEdition";
	var Wrapper = $("#eEditionWrap");
	$(Wrapper).mask();
	$(Wrapper).load(url, function() { $(Wrapper).unmask(); });
};

// ##########################################################


// ####### Article Forums
function CommentsVisibility() {
    $("#postCommentArea #post").addClass('hide');
    $("#postCommentArea #notValid").addClass('hide');
    $("#postCommentArea #notLoggedIn").addClass('hide');
    if (SiteUser.User_ID > 0) {
        if (SiteUser.UserVerified) { $("#postCommentArea #post").removeClass('hide'); }
        else { $("#postCommentArea #notValid").removeClass('hide'); }
    } else {
        $("#postCommentArea #notLoggedIn").removeClass('hide');
    }
};

function ArticleForums() {
	this.FormValid = function(Form) {
		var ret = true;
		$(Form).find("p.required :input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().addClass("error");
				$(this).parent().children("em").removeClass('hide');
				ret = false;
			} else {
				$(this).parent().removeClass("error");
				$(this).parent().children("em").addClass("hide");
			};
		});
		return ret;	
	};
	
    this.SubmitPost = function() {
        var form = $("form#newmessageform");
        $(form).mask("Please wait..");
        var NewUrl = $("#newMessageLink").val();
        if (NewUrl) {
            $.get(NewUrl, null, function(responseText, textStatus) {
                var Data = JSON.parse(responseText).Data;
                if (Data.PostMessageLink) {						   
					if (Data.Canpost) {
	                    $(form).attr("action", Data.PostMessageLink);
	                    $(form).find("#Author").val(Data.Author);
	                    $(form).find("#Email").val(SiteUser.UserEmail);
	                    $(form).ajaxForm({
	                        success: function(response) {
	                            $(form).unmask();
	                            $("div#commentsArea").mask();
	                            $("div#commentsArea").replaceWith(response);
	                            $("div#commentsArea").unmask();
								$(form).resetForm();
								$(form).replaceWith("<p>Thank you for posting, your comments are appreciated</p>");
	                        }
	                    });
	                    $(form).submit();  
					} else {
						alert("A problem has occured and your comments could not be posted.\nPlease refresh the page and try again.\nIf the problem persists, please contact the site administrator.");
						$(form).unmask();
					};
                };
            });
        };
    };

	$("#postBttn").live("click", function(e) {
		if (FormValid("form#newmessageform")) {
			if (confirm("Have you reviewed your post for content, spelling and grammar?\nOnce you post, only the site administrator can remove a comment.\n\nPost comment?")) {
				SubmitPost();	
			};
		};
		return false;		
	});
};
// ##########################################################

// ####### Article Image Gallery
function ArticleGallery(Imageholder) {
    var Images = $(Imageholder);
    if ($(Images).find("a").length > 0) {
        $(Images).find("a").overlay({
            target: '#gallery',
            expose: '#f1f1f1'
        }).gallery({
            speed: 800,
            prev: '.imgPrev',
            next: '.imgNext',
            info: '.imgInfo',
            progress: '.imgProgress'
        });
        var moreLink = $("#artMorePictures");
        $(moreLink).html($(moreLink).html().replace('-count-', $(Images).find("a").length));
        $(moreLink).removeClass('hide');
        $(moreLink).bind("click", function(e) {
            e.preventDefault();
            $(Images).find("a:first").trigger("click");
        });
        $("a.openGallery").bind("click", function(e) {
            e.preventDefault();
            $(Images).find("a:first").trigger("click");
        });
    };
};
// ##########################################################
// ####### Article Paragraph Fact Boxes
function ArticleParagraphFacts() {
	$("div.paragraph-fact-box").each(function() {
		var fID = this.id;
		var Link = $("div#"+fID + " a");
		$(Link).qtip({
			content: { title: $(Link).html(), text: $("div#" + fID + " div.factText").html() },
			style: { border: { width: 2, radius: 3, color: '#3C3C3C' } },
			position: { corner: { target: 'bottomRight', tooltip: "topMiddle" }	},
			hide: { fixed: true }
		});
	});
};
// ##########################################################

// ####### Validation Utility
function ValidationUtils() {
	this.UserReg = function(regForm) {
		var ret = true;
		$(regForm).find("div.required input:not(\"#password2\")").each(function() {
			if ($(this).val() == "") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass('white');
			}
		});
		$(regForm).find("#password2").each(function() {
			if ($(this).val() != $(regForm).find("#password").val()) {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass('white');
			}
		});
		$(regForm).find("div.required select").each(function() {
			if ($(this).val() == "") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass('white');
			}
		});	   
		return ret;
	}
}					 
// ##########################################################

// ############# Sites you like popup submission form
function SitesYouLike(tipFormUrl) {
	this.FormValid = function(Form) {
		var ret = true;
		$(Form).find("p.required :input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().addClass("error");
				$(this).parent().children("em").removeClass('hide');
				ret = false;
			} else {
				$(this).parent().removeClass("error");
				$(this).parent().children("em").addClass("hide");
			};
		});
		return ret;	
	};
	
	this.SubmitForm = function() {
		var Form = $("#SiteSubmission");
		$(Form).ajaxForm({
			beforeSend: function() { $(Form).mask("Please wait..."); },
			success: function(response) { $(Form).unmask(); $(Form).replaceWith(response); }
		});
		$(Form).submit();
	};
	
	function CreateTip(target) {
		$(target).qtip({
			content: { title: { text: "<h1>Submit a site</h1>", button: "Close" }, url: tipFormUrl },
			position: { target: $(document.body), corner: 'center' },
			show: { when: 'click', solo: true },
			hide: false,
			style: {name: 'light', width: 500, border: { width: 2, radius: 8, color: '#3C3C3C' } },
			api: {
				onHide: function() { ResetTip(target); }
			}
		});
	};
	
	function ResetTip(target) {
		$(target).qtip("destroy");
		CreateTip(target);
	};					  
	
	$(document.body).append("<div id=\"siteSubmitTip\" style=\"display: none;\"></div>");
	CreateTip($("div#siteSubmitTip"));
	
	$("#tipSiteSubmit").live("click", function() {
		$("div#siteSubmitTip").trigger("click");
		return false;
	});	
	
	$("#siteSubmitBttn").live("click", function() {
		if (FormValid($("#SiteSubmission"))) {
			SubmitForm();
		};
		return false;
	});

};
// ##########################################################

// Contact Us email form
function ContactUsForm(){
	this.FormValid = function(Form){
		var ret = true;
		$(Form).find("div.required > input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass("white");
			};
		});
		return ret;	
	};
	
	this.SubmitForm = function() {
		var Form = $("#contact_form");
		var MailTo = $(Form).find("#regarding option:selected").val();
		$(Form).find("#to").val(MailTo);
	 	$(Form).ajaxForm({
			beforeSend: function() { $(Form).mask("Please wait..."); },
			success: function(response) { $(Form).unmask(); $(Form).replaceWith(response); }
		});
		$(Form).submit();
	};
	
	$("#contactSubmitBttn").bind("click", function(e) {
		if (FormValid($("#contact_form"))) {
			SubmitForm();
		};
		return false;
	});
};
				   
// Carrier Application Form
function CarrierAppForm() {
	this.FormValid = function(Form){
		var ret = true;
		$(Form).find("div.required > input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
					$(this).parent().children("div.errorMessage").addClass("white");
			};
		});
		return ret;
	};
	
	this.SubmitForm = function() {
		var Form = $("#CarrierApp_form");
		$(Form).ajaxForm({
			beforeSend: function() { $(Form).mask("Please wait..."); },
			success: function(response) { $(Form).unmask(); $(Form).replaceWith(response); }
		});
		$(Form).submit();
	};
	
	$("#CarrierAppSubmitBttn").bind("click", function(e) {
		if (FormValid($("#CarrierApp_form"))) {
			SubmitForm();
		};
		return false;
	});
};
//##################################################################

// ####### Delivery Concern Form
function DeliveryConcernForm() {
	this.FormValid = function(Form){
		var ret = true;
		$(Form).find("div.required > input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass("white");
			};
		});
		return ret;
	};
	
	this.SubmitForm = function() {
		var Form = $("#DeliveryConcern_form");
		$(Form).ajaxForm({
			beforeSend: function() { $(Form).mask("Please wait..."); },
			success: function(response) { $(Form).unmask(); $(Form).replaceWith(response); }
		});
		$(Form).submit();
	};
	
	$("#DeliveryConcernSubmitBttn").bind("click", function(e) {
		if (FormValid($("#DeliveryConcern_form"))) {
			SubmitForm();
		};
		return false;
	});
};
//##################################################################

// ####### Delivery Concern Form
function SubscriptionForm() {
	this.FormValid = function(Form){
		var ret = true;
		$(Form).find("div.required > input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass("white");
			};
		});
		return ret;
	};
	
	this.SubmitForm = function() {
		var Form = $("#Subscription_form");
		$(Form).ajaxForm({
			beforeSend: function() { $(Form).mask("Please wait..."); },
			success: function(response) { $(Form).unmask(); $(Form).replaceWith(response); }
		});
		$(Form).submit();
	};
	
	$("#SubscriptionSubmitBttn").bind("click", function(e) {
		if (FormValid($("#Subscription_form"))) {
			SubmitForm();
		};
		return false;
	});
};
//##################################################################

// ####### Delivery Concern Form
function VacationForm() {
	this.FormValid = function(Form){
		var ret = true;
		$(Form).find("div.required > input").each(function() {
			if ($(this).val()=="") {
				$(this).parent().children("div.errorMessage").removeClass('white');
				ret = false;
			} else {
				$(this).parent().children("div.errorMessage").addClass("white");
			};
		});
		return ret;
	};
	
	this.SubmitForm = function() {
		var Form = $("#Vacation_form");
		$(Form).ajaxForm({
			beforeSend: function() { $(Form).mask("Please wait..."); },
			success: function(response) { $(Form).unmask(); $(Form).replaceWith(response); }
		});
		$(Form).submit();
	};
	
	$("#VacationSubmitBttn").bind("click", function(e) {
		if (FormValid($("#Vacation_form"))) {
			SubmitForm();
		};
		return false;
	});
};
//##################################################################

// ####### Top story teaser adjustment

function adjustTopStoryTeaser() {
	var adjustmentHeight = 30;
	var divTopStoryTeaser = $("#divTopStoryTeaser").get(0);
	var divTopStoryImage = $("#divTopStoryImage").get(0);
	var divTopStory = $("#divTopStory").get(0);
	var headerTopStory = $("#headerTopStory").get(0);

	if ((divTopStoryTeaser.clientHeight + adjustmentHeight) < divTopStoryImage.height)
	{
		divTopStoryTeaser.style.height = (divTopStoryImage.height - adjustmentHeight) + 'px';
	};
	if (divTopStoryImage.width < 250)
	{
		divTopStory.style.width = (250 - divTopStoryImage.width + divTopStory.clientWidth) + 'px';
		headerTopStory.style.width = "100%";
	};
};
//##################################################################

// ####### Staff Directory (contact us page)
function StaffDirectory() {
	$('#directory-list').accordion();
	$('#directory-list a.StaffLink').each(function() {
		var link = this;
		$(this).bind("click", function(e) { e.preventDefault(); });
		$(this).qtip({
			content: {
				title: { text: "<h1>"+ link.title + "</h1>", button: "Close" },
				url: link.href
			},
			position: {
				target: $(document.body),
				corner: 'center'
			},
			hide: { fixed: true },
			style: {
				name: 'light',
				width: 500,
				border: {
					width: 2,
					radius: 3,
					color: '#3c3c3c'
				}
			},
			show: { when: 'click', solo: true },
			hide: false
		});
	});
};
//##################################################################

//############# Guide Directory ########################
	function GuideDirectory() {$('#guide-list').accordion();};
//##################################################################

// ####### Terms of Use/Privacy Policy Tip
function Policies() {
	$("a.Policies").each(function() {
		var link = this;
		$(this).bind("click", function(e) { e.preventDefault(); });
		$(this).qtip({
			content: { title: { text: "<h1>"+link.title+"</h1>", button: "Close" }, url: link.href },
            position: { target: $(document.body), corner: 'center' },
            show: { when: 'click', solo: true },
            hide: false,
            style: { name: 'light', width: 700, border: { width: 2, radius: 8, color: '#3C3C3C'}, classes: { content: "qtip-content privPolicy" } }
		});
	});
}

//##################################################################

//################ Obituaries & In Memoriams #######################
function ObitsAndInMemoriamOnLoad(section){
		$("#pubDate").datepicker({
			showOn: 'both',
			buttonImage: '/images/calendar.png',
			buttonImageOnly: true,
			dateFormat: 'yy-mm-dd',
			onSelect:function(){}
		});
		
		$("#lastName").val(gup('lastName'));
		$("#pubDate").val(gup('pubDate'));
		$("#obitClassLink").attr("href",  $("#obitClassLink").attr("href") + '&lastName=' + gup('lastName') + '&pubDate=' + gup('pubDate'));
		$("#inMemClassLink").attr("href",  $("#inMemClassLink").attr("href") + '&lastName=' + gup('lastName') + '&pubDate=' + gup('pubDate'));
		if($("#previousPageLink"))
		{
			$("#previousPageLink").attr("href",  $("#previousPageLink").attr("href") + '&lastName=' + gup('lastName') + '&pubDate=' + gup('pubDate') + '&classId=' + gup('classId'));
		}
		if($("#nextPageLink"))
		{
			$("#nextPageLink").attr("href",  $("#nextPageLink").attr("href") + '&lastName=' + gup('lastName') + '&pubDate=' + gup('pubDate') + '&classId=' + gup('classId'));
		}
		
		if($("#searchResultsFilterLabel")) {
			var label = "";
		
			if(gup('lastName')) {
				label = label + ', ' + gup('lastName');
			}
			if(gup('pubDate')) {
				label = label + ', ' + unescape(gup('pubDate'));
			}
			if(gup('classId')) {
				if (gup('classId') == '0100'){
					label = label + ', Obituaries';
				}
				if (gup('classId') == '0110'){
					label = label +  ', In Memoriams';
				}
			}
			if (label.length > 1){
				label = label.substring(2);
			}
			else label = 'Obituaries & In Memoriams';
			
			$("#searchResultsFilterLabel").text(label);
		}
		$('#btnSearch').click(function(e) {
			e.preventDefault();
			window.location.href = "/section/" + section + "/&lastName=" + $("#lastName").val() + "&pubDate=" + $("#pubDate").val();
			return false;
		});
		$('#btnClear').click(function(e) {
			e.preventDefault();
			window.location.href = "/section/" + section + "/";
			return false;
		});
}

//##################################################################

function ReportAbuse(msgId) {
	var $form = $("form#ReportAbuse");
	var $msg = $("div#Abuse-"+msgId);
	$form.find("input#msg").val($msg.html());
	
	$($form).ajaxForm({
		success: function() {
			alert("Success!");
		}
	});
	
	$($form).submit();
}

/*---------- Poll Mini -------------------------------------------------*/

function loadPollMini() {
	window.$pollMini = {
		polls			: 	$("div.PollMini"),
		divIndex	:	0,
		count		: 	0,
		loadPolls	: function() {
			var $t = this;
			if (($t.polls.length > 0) && ($t.divIndex < $t.polls.length)) {
				var form = $($t.polls[$t.divIndex]).find("form.pollSource");
				var target = $($t.polls[$t.divIndex]).find("div.pollResult");
				$t.divIndex++;
				$(form).ajaxForm({
				success: function(r) {
					$(target).html(r);
					$t.count++;
					$t.loadPolls();
					}
				});
				$(form).submit();
			};
			$t.bindEvents();
		},
		bindEvents : function() {
			var $t = this;
			$($t.polls).each(function() {
				var $b = $(this).find(".pollSubmit");
				$($b).bind("click", function(e) {
					var poll = $($b).parents("div.PollMini:first");
					$t.submitPoll(poll);
				});
			});
		},
		submitPoll : function(p) {
			var form = $(p).find("form.pollForm");
			var target = $(p).find("div.pollResult");
			$(form).ajaxForm({
				beforeSend: function() { $(form).mask(); },
				success: function(r) {
					$(form).unmask();
					$(target).html(r);
				}
			});
			if (this.isValid(form)) {
				$(form).submit();
			} else {
				alert("Please select a response");
			};
		},
		isValid : function(f) {
			return $(f).find(":input:checked").length > 0;
		}
	};
	
	window.$pollMini.loadPolls();
};

/*---------- End Poll Mini -------------------------------------------------*/

/* --------------- Site.js ------------------------------------
    Created by Darren Pearce    
    darren@darrenpearce.com  |  www.darrenpearce.com
    
    ------------------------------------------------------------------------------------------
    
    suns Albertan Online Newspaper
    
    created: Jan 23rd 2009
    ------------------------------------------------------------------------------------------
    
    
    Requires:
     - google ajax libraries api => http://code.google.com/apis/ajaxlibs/
     - jquery => http://jquery.com 1.3.2 latest version as of imlementaion
    
*/

var Polls;
var Site;
var Validation;

// wait for page to load
$(document).ready(function() {
    Site = new SiteScripts();
    Site.Init();
    Policies();
    Validation = new ValidationUtils();
	loadPollMini();
});  // end google callback

function getToday() {
    var dt = new Date();
    var month = dt.getMonth() + 1;
    var day = dt.getDate();
    var year = dt.getFullYear();
    return (month + "/" + day + "/" + year);
    
}
/*---------- End Site.js -------------------------------------------------*/

/*---------- Util.js -------------------------------------------------*/
/**
* Returns an XMLHttp instance to use for asynchronous
* downloading. This method will never throw an exception, but will
* return NULL if the browser does not support XmlHttp for any reason.
* @return {XMLHttpRequest|Null}
*/
function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};

/**
* This functions wraps XMLHttpRequest open/send function.
* It lets you specify a URL and will call the callback if
* it gets a status code of 200.
* @param {String} url The URL to retrieve
* @param {Function} callback The function to call once retrieved.
*/
function downloadUrl(url, callback) {
 var status = -1;
 var request = createXmlHttpRequest();
 if (!request) {
   return false;
 }

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     try {
       status = request.status;
     } catch (e) {
       // Usually indicates request timed out in FF.
     }
     if (status == 200) {
       callback(request.responseXML, request.status);
       request.onreadystatechange = function() {};
     }
   }
 }
 request.open('GET', url, true);
 try {
   request.send(null);
 } catch (e) {
   changeStatus(e);
 }
};

/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string.
 * @return {Element|Document} DOM.
 */
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

/**
 * Appends a JavaScript file to the page.
 * @param {string} url
 */
function downloadScript(url) {
  var script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
}
/*-------------- Util.js --------------------------------------*/

/* ---------- Community Page ---------------------------- */

function CharityModule() {
	$("div.charityDonate").hide();
	$("a.volunteerTab").bind("click", function(e) {
		e.preventDefault();
		$("a.volunteerTab").parent().addClass('selected'); // Show the tab
		$("div.charityVolunteer").show(); // Show the Content
		$("a.donateTab").parent().removeClass('selected');  // Hide other tab(s) 
		$("div.charityDonate").hide(); // Hide other Content
	});
	$("a.donateTab").bind("click", function(e) {
		e.preventDefault();
		$("a.donateTab").parent().addClass('selected'); // Show the tab
		$("div.charityDonate").show(); // Show the content
		$("a.volunteerTab").parent().removeClass('selected'); // Hide other Tab(s)
		$("div.charityVolunteer").hide(); // Hide other content
	});
};
// #######################################################################
