﻿
/*
* Copyright (C) 2009-2012 Solmead Productions
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
*  - GNU General Public License Version 2 or later (the "GPL")
*    http://www.gnu.org/licenses/gpl.html
*
*  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
*    http://www.gnu.org/licenses/lgpl.html
*
*  - Mozilla Public License Version 1.1 or later (the "MPL")
*    http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*/
Namespace.Register("System.SevenHills.Video");

System.Later = function (msec, method) {
        var that = this;
        args = Array.prototype.slice.apply(arguments, [2]);
        if (typeof method === 'string') {
            method = that[method];
        }
        if (method == undefined) {
            return;
        }
        setTimeout(function () {
            method.apply(that, args);
        }, msec);
        return that;
    }

System.ServerDateTime = "";
System.Offset = 0;

System.Generic = function () {
    $(".button, .button_destructive").button();

    $(".button_destructive").click(function () {
        var del = confirm("Really delete this item? You can not undo this action.");
        if (del) {
            return true;
        } else {
            return false;
        }
    });

    $("td .DeleteForm").submit(function () {
        var form = $(this);
        $(form).find("input[type='submit']").attr("disabled", "disabled").css(disable);
        var post_url = $(this).attr("action") + '?Format=JSON';
        var form_data = $(this).serialize();
        $(form).parents("tr").fadeOut(2000, function () {
            $(form).parents("tr").remove();
        });
        $.post(post_url, form_data, function (data, status) {
            data = data.Item;
        }, "json");
        return false;
    });

    $(".datepicker").datepicker();
    $("#ui-datepicker-div").addClass("promoteZ");


    $("#DebugArea").dialog({
        autoOpen: false,
        height: 200,
        width: 450
    });

    $("#DebugConsole").click(function () {
        $("#DebugArea").dialog("open");
        return false;
    });


    $(".UseFancyBox").click(function () {
        var Area = $(this).attr("href");
        var Width = $(this).attr("Width");
        var Height = $(this).attr("Height");
        if (Area == "") {
            return;
        }
        if (Area.indexOf("?") != -1) {
            Area = Area + "&Format=CleanHTML";
        } else {
            Area = Area + "?Format=CleanHTML";
        } 
        if (Width == null || Width == "") {
            //alert("Width=" + Width);
            Width = "75%";
        }
        if (Height == null || Height == "") {
            //alert("Height=" + Height);
            Height = "75%";
        }
        //alert("Width=" + Width);
        var Settings = {
            'autoScale': false,
            'padding': 0,
            'href': Area,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'type': 'iframe',
            'width' : parseInt(Width),
            'height' : parseInt(Height)
        };
//        Settings = {
//            'width': parseInt('770'),
//            'height': parseInt('440'),
//            'href': Area,
//            'autoScale': false,
//            'transitionIn': 'none',
//            'transitionOut': 'none',
//            'type': 'iframe'
//        }
        
        //alert(Settings);
        //alert(Area);
        $.fancybox(Settings);
        return false;
    });
}
System.RefreshServerTime = function () {
    var Now = new Date();
    var Cnt = Cnt = parseInt(Now.getTime());
    var URL = "/Home/GetServerTime?Format=JSON"
    $.getJSON(URL + "&Cnt=" + Cnt, function (data) {
        System.ServerDateTime = Date.parse(data.Item.Date);
        System.Offset = (System.ServerDateTime - (new Date()).getTime());
    });
}
$(function () {
    System.Generic();
    System.RefreshServerTime();
});
System.DebugWrite = function (Message) {

    var Now = new Date();
    $("#DebugArea").append("<div>" + Now + " - " + Message + "</div>");
    try {
        var item = $("#DebugArea div:last-child");
        t = (item.position().top + item.height()) - $("#DebugArea").height() + $("#DebugArea").scrollTop();
        $("#DebugArea").scrollTop(t);
    }
    catch (err) {

    }
}
System.FillValue = function (Value, Item) {
    $(Item).append(Value);
    System.ShowHideParent((Value!=""), Item);
}
System.ShowHideParent = function (Value, Item) {
    //System.DebugWrite("ShowHideParent Value=" + Value);
    if (Value) {
        $(Item).parent().show();
    } else {
        $(Item).parent().hide();
    }
}
System.fakeClick = function (id, fn) {
    var $a = $('<a href="#" id="fakeClick_' + id + '"></a>');
    $a.bind("click", function (e) {
        e.preventDefault();
        fn();
    });

    $("body").append($a);


    var evt, el = $('#fakeClick_' + id + '').get(0);

    if (document.createEvent) {
        evt = document.createEvent("MouseEvents");
        if (evt.initMouseEvent) {
            evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            el.dispatchEvent(evt);
        }
    }

    $(el).remove();
}

System.IsIphone = function () {
    var IsI = ((navigator.userAgent.indexOf('iPhone') > 0) || (navigator.userAgent.indexOf('iPod') > 0) || (navigator.userAgent.indexOf('iPad') > 0));
    return IsI;
}

System.DisableElements = function (elems) {
    //alert("disable");
    $(elems).attr("disabled", "disabled");
    $(elems).addClass("disabled_item");

}

System.EnableElements = function (elems) {
    //alert("enable");
    $(elems).removeAttr("disabled");
    $(elems).removeClass("disabled_item");

}

System.IsIpad = function () {

    var IsI = ( (navigator.userAgent.indexOf('iPad') > 0));
    return IsI;
}



System.SevenHills.VideoTracker = function (V_ID) {
    var Obj = {
        Running: false,
        ShouldStop: false,
        Video_ID: 0,
        Init: function (Vid_ID) {
            Obj.Video_ID = Vid_ID;
            if (!Obj.ShouldStop && (Vid_ID != 0)) {
                Obj.Start();
            } else {
                Obj.ShouldStop = false;
                Obj.Running = false;
            }
        },
        Event: function () {
            if (Obj.ShouldStop) {
                Obj.ShouldStop = false;
                Obj.Running = false;
                return;
            }
            //var URL = "/Video/TrackingEvent/" + Video_ID + "?Format=JSON";
            var URL = "/Video/TrackingEvent?Format=JSON";
            $.post(URL, { "ID": Obj.Video_ID }, function (data) {
                data = data.Item;
            });
            System.Later(15000, Obj.Event);
        },
        Start: function () {
            Obj.Running = true;
            var URL = "/Video/TrackingStart?Format=JSON";
            $.post(URL, { "ID": Obj.Video_ID }, function (data) {
                data = data.Item;
            });
            System.Later(15000, Obj.Event);
        },
        Stop: function () {
            Obj.ShouldStop = true;
            return;
        }
    };
    $(function () {
        Obj.Init(V_ID);
    });
    return Obj;
}

System.SevenHills.Video = {
    GetVideo: function (Video_ID, CallWhenLoaded) {
        var URL = "/Video/Details/" + Video_ID + "?Format=JSON";
        $.getJSON(URL, function (data) {
            if (CallWhenLoaded != null) {
                CallWhenLoaded(data.Item);
            }
        });
    },
    Create: function (ID, AutoPlay, Video_ID, RequireClick, CallWhenLoaded) {
        System.SevenHills.Video.GetVideo(Video_ID, function (data) {
            System.SevenHills.Video.CreateWithVideo(ID, AutoPlay, data, RequireClick);
            if (CallWhenLoaded != null) {
                CallWhenLoaded();
            }
        });
    },
    PlayFromLightcast: function (ID, VidData, First, Autoplay) {
        var LightCastEmbedCode = VidData.LightCastEmbedCode;
        var LightCastVideo_ID = VidData.LightCastVideo_ID;
        System.Lightcast.PlayVideo(ID, LightCastEmbedCode, LightCastVideo_ID, VidData.LightCast_Client_ID, VidData.LightCast_BaseURL, Autoplay);
    },
    CreateWithVideo: function (ID, AutoPlay, Video, RequireClick) {
        //alert("CreateWithVideo called");
        if (Video == null) {
            return;
        }
        if (Video.length == 0) {
            return;
        } else {
            var Area = $("#" + ID);

            if (System.IsIphone() || System.IsIpad()) {
                System.SevenHills.Video.Create_HTML5(ID, AutoPlay, Video, RequireClick);
            } else {
                if (RequireClick) {
                    $(Area).click(function () {
                        $(function () {
                            System.SevenHills.Video.PlayVideo(ID, Video, true);
                        });
                        return false;
                    });
                } else {
                    if (!AutoPlay) {
                        System.SevenHills.Video.PlayVideo(ID, Video, false);
                    }
                }

                if (AutoPlay) {
                    System.SevenHills.Video.PlayVideo(ID, Video, true);
                }
            }
        }
    },
    PlayVideo: function (ID, Video, Autoplay) {
        //alert("PlayVideo called");
        if (Video.AddToLightcast) {
            if (Video.LightCastEmbedCode != "") {
                System.SevenHills.Video.PlayFromLightcast(ID, Video, true, Autoplay)
            } else {
                System.SevenHills.Video.Create_FlowPlayer(ID, Autoplay, Video, false)
            }
        } else {
            System.SevenHills.Video.Create_FlowPlayer(ID, Autoplay, Video, false)
        }
        if (System.SevenHills.Video.Tracker == null) {
            System.SevenHills.Video.Tracker = new System.SevenHills.VideoTracker(Video.ID);
        }
        System.SevenHills.Video.Tracker.Video_ID = Video.ID;
        //alert("10");
        //System.Video.Tracker.Start(Video.ID);
    },
    Create_FlowPlayer: function (ID, Autoplay, Video, RequireClick) {
        //alert("Create_FlowPlayer called");
        //alert("ID=" + ID);
        //alert("Autoplay=" + Autoplay);
        //alert("RequireClick=" + RequireClick);
        if (System.IsIphone() || System.IsIpad()) {
            return System.SevenHills.Video.Create_HTML5(ID, Autoplay, Video, RequireClick);
        }

        //alert("1");
        var Area = $("#" + ID);
        var Width = $(Area).width() + 0;
        var Height = $(Area).height() + 0;
        //Area = $(Area).parent();
        var Image = Video.Thumbnail;
        if (Autoplay) {
            Image = Video.ImageURL;
        }
        //alert("2");
        var SubStr = 'autoplay="autoplay"';
        if (!Autoplay) {
            SubStr = '';
        }

        var m4v = Video.PodcastFile;
        var m4v_File = "";
        if (m4v != null) {
            m4v_File = m4v.URL;
        }
        var mp3 = Video.AudioFile;
        var mp3_File = "";
        if (mp3 != null) {
            mp3_File = mp3.URL;
        }
        var flv = Video.FLVFile;
        var flv_File = "";
        if (flv != null) {
            flv_File = flv.URL;
        }
        var ogv_File = "";
        var webm_File = "";
        $.each(Video.Alternates, function (i, item) {
            if (item.Type == "WebM") {
                webm_File = item.Video.URL;
            }
            if (item.Type == "Ogg_Theora") {
                ogv_File = item.Video.URL;
            }
        });
        if (m4v_File == "") {
            m4v_File = mp3_File;
        }
        if ((System.IsIphone() && !System.IsIpad()) && (Video.LightCastEmbedCode != "")) {
            m4v_File = 'http://' + 'customers.lightcastmedia.com/cupertino/' + Video.LightCast_Client_ID + '/' + Video.LightCastVideo_ID + '.m3u8';
        }
        //alert(m4v_File);
        var Poster = '"poster="' + Image + '" preload="preload" autobuffer="autobuffer" ';
        if (Autoplay) {
            Poster = "";
        }
        //alert("3");
        var VidStr = '';

        VidStr = VidStr + "  <object id='" + ID + "_api' width='" + Width + "' height='" + Height + "' type='application/x-shockwave-flash'";
        VidStr = VidStr + "    data='/Content/Flash/flowplayer-3.2.5.swf?0.9715260110727094'> ";
        VidStr = VidStr + "    <param name='movie' value='/Content/Flash/flowplayer-3.2.5.swf?0.9715260110727094' /> ";
        VidStr = VidStr + "    <param name='allowfullscreen' value='true' /> ";
        VidStr = VidStr + "    <param name='allowscriptaccess' value='always' /> ";
        VidStr = VidStr + "    <param name='quality' value='high' /> ";
        VidStr = VidStr + "    <param name='cachebusting' value='true' /> ";
        VidStr = VidStr + "    <param name='wmode' value='transparent'> ";
        VidStr = VidStr + "    <param name='bgcolor' value='#000000' /> ";
        VidStr = VidStr + "    <param name=\"flashvars\" value=\"config={'canvas':{'backgroundGradient':'none'}, 'clip':{'scaling': 'fit', 'url':'" + flv_File + "','provider':'lighttpd', 'autoplay' : " + Autoplay + ", 'autoBuffering':true},'plugins':{ 'lighttpd':{'url':'/Content/Flash/flowplayer.pseudostreaming-3.2.5.swf', 'rangeRequest' : true}},'playerId':'lighty','playlist':[{'url':'" + flv_File + "','provider':'lighttpd'}]}\"/>";
        VidStr = VidStr + "    <p>Download video as <a href='" + m4v_File + "'>MP4</a>, <a href='" + webm_File + "'>WebM</a>, or <a href='" + ogv_File + "'>Ogg</a>.</p> ";
        VidStr = VidStr + "  </object>";
        $(Area).attr('href', m4v_File);

        //alert("4");
        if (!RequireClick || !System.IsIphone()) {
            //alert("5");
            $(Area).html(VidStr);
        }
        if (Autoplay) {
            if (!(!RequireClick || !System.IsIphone())) {
                //alert("6");
                $(Area).html(VidStr);
            }
            //alert("7");
            //$(Area).html(VidStr);
            $(Area).unbind('click');
            $(Area).click(function () {
                return false;
            });
            //alert("8");
            //$(Area).html(VidStr);
            //        $(Area).click(function () {
            //            return false;
            //        });
            if (System.IsIpad()) {
                //alert('IsiPad');
                var video = $("#someVideo_" + ID).get(0);
                //alert("Calling fakeclick");
                setTimeout(fakeClick, 5000, ID, function () {
                    //alert('fake click called');
                    video.load();
                    video.play();
                });
            }
            //alert("9");
        }
        return;
    },
    Create_HTML5: function (ID, Autoplay, Video, RequireClick) {
        //alert("Create_HTML5 called");
        var Area = $("#" + ID);
        var Width = $(Area).width() + 0;
        var Height = $(Area).height() + 0;
        //Area = $(Area).parent();
        var Image = Video.Thumbnail;
        if (Autoplay) {
            Image = Video.ImageURL;
        }

        var SubStr = 'autoplay="autoplay"';
        if (!Autoplay) {
            SubStr = '';
        }

        var m4v = Video.PodcastFile;
        var m4v_File = "";
        if (m4v != null) {
            m4v_File = m4v.URL;
        }
        var mp3 = Video.AudioFile;
        var mp3_File = "";
        if (mp3 != null) {
            mp3_File = mp3.URL;
        }
        var flv = Video.FLVFile;
        var flv_File = "";
        if (flv != null) {
            flv_File = flv.URL;
        }
        var ogv_File = ""; //(From AV In V.Alternates Where AV.Type.ToUpper = "OGG_THEORA" Select AV.Video).FirstOrDefault;
        var webm_File = ""; // (From AV In V.Alternates Where AV.Type.ToUpper = "WEBM" Select AV.Video).FirstOrDefault;
        $.each(Video.Alternates, function (i, item) {
            if (item.Type == "WebM") {
                webm_File = item.Video.URL;
            }
            if (item.Type == "Ogg_Theora") {
                ogv_File = item.Video.URL;
            }
        });


        if (m4v_File == "") {
            m4v_File = mp3_File;
        }



        if ((System.IsIphone() && !System.IsIpad()) && (Video.LightCastEmbedCode != "")) {
            m4v_File = 'http://customers.lightcastmedia.com/cupertino/' + Video.LightCast_Client_ID + '/' + Video.LightCastVideo_ID + '.m3u8';
        }
        //alert(m4v_File);
        var Poster = '"poster="' + Image + '" preload="preload" autobuffer="autobuffer" ';
        if (Autoplay) {
            Poster = "";
        }

        //var VidStr = '<video id="someVideo_' + ID + '" width="' + Width + '" height="' + Height + '" ' + Poster + ' controls="controls" preload="preload" ' + SubStr + '">';
        var VidStr = '<video id="someVideo_' + ID + '" width="' + Width + '" height="' + Height + '" ' + Poster + ' controls="controls" ' + SubStr + '">';
        VidStr = VidStr + "  <source src='" + m4v_File + "' />";
        VidStr = VidStr + "  <source src='" + webm_File + "' type='video/webm; codecs=\"vp8, vorbis\"' />";
        VidStr = VidStr + "  <source src='" + ogv_File + "' type='video/ogg; codecs=\"theora, vorbis\"' />";
        VidStr = VidStr + "  <object width='" + Width + "' height='" + Height + "' type='application/x-shockwave-flash'";
        VidStr = VidStr + "    data='/Content/Flash/flowplayer-3.2.5.swf?0.9715260110727094'> ";
        VidStr = VidStr + "    <param name='movie' value='/Content/Flash/flowplayer-3.2.5.swf?0.9715260110727094' /> ";
        VidStr = VidStr + "    <param name='allowfullscreen' value='true' /> ";
        VidStr = VidStr + "    <param name='allowscriptaccess' value='always' /> ";
        VidStr = VidStr + "    <param name='quality' value='high' /> ";
        VidStr = VidStr + "    <param name='cachebusting' value='true' /> ";
        VidStr = VidStr + "    <param name='wmode' value='transparent'> ";
        VidStr = VidStr + "    <param name='bgcolor' value='transparent' /> ";
        //VidStr = VidStr + "    <param name='flashvars' value='config={\"canvas\":{\"backgroundcolor\":\"transparent\",\"backgroundGradient\":\"none\"},\"clip\": {\"url\": \"" + flv_File + "\", \"autoPlay\":" + Autoplay + ", \"autoBuffering\":true}}' /> ";
        //'canvas':{'backgroundcolor':'transparent','backgroundGradient':'none'},
        VidStr = VidStr + "    <param name=\"flashvars\" value=\"config={'clip':{'scaling': 'fit', 'url':'" + flv_File + "','provider':'lighttpd', 'autoplay' : " + Autoplay + ", 'autoBuffering':true},'plugins':{'lighttpd':{'url':'/Content/Flash/flowplayer.pseudostreaming-3.2.5.swf', 'rangeRequest' : true}},'playerId':'lighty','playlist':[{'url':'" + flv_File + "','provider':'lighttpd'}]}\"/>";
        VidStr = VidStr + "    <p>Download video as <a href='" + m4v_File + "'>MP4</a>, <a href='" + webm_File + "'>WebM</a>, or <a href='" + ogv_File + "'>Ogg</a>.</p> ";
        VidStr = VidStr + "  </object>";
        VidStr = VidStr + '</video>';
        //alert(VidStr);
        $(Area).attr('href', m4v_File);
        //$(Area).attr('href', '');
        //alert(VidStr);
        if (!RequireClick || !System.IsIphone()) {
            $(Area).html(VidStr);
        }
        if (Autoplay) {
            if (!(!RequireClick || !System.IsIphone())) {
                $(Area).html(VidStr);
            }
            //$(Area).html(VidStr);
            $(Area).unbind('click');
            $(Area).click(function () {
                return false;
            });
            //$(Area).html(VidStr);
            //        $(Area).click(function () {
            //            return false;
            //        });
            if (System.IsIpad()) {
                //alert('IsiPad');
                var video = $("#someVideo_" + ID).get(0);
                //alert("Calling fakeclick");
                setTimeout(fakeClick, 5000, ID, function () {
                    //alert('fake click called');
                    video.load();
                    video.play();
                });
            }
        }
    }




}


System.SevenHills.LiveVideo = {
    Create_Flowplayer: function (ID, BaseURL, StreamName) {
        flowplayer(ID, "/Content/Flash/flowplayer-3.1.1.swf", {
            canvas: {
                backgroundcolor: 'transparent',
                backgroundGradient: 'none'
            },
            clip: {
                url: StreamName,
                live: true,
                provider: 'influxis'
            },
            plugins: {
                influxis: {
                    url: 'flowplayer.rtmp-3.1.0.swf',
                    netConnectionUrl: BaseURL
                }
            }
        });
    },
    Create_Lightcast: function (ID, Video_ID, SecondsIntoVideo, FinishFunc) {

        if (System.IsIphone() || System.IsIpad()) {
            //System.SevenHills.Video.Create(ID, true, Video_ID, false);
            //document.location.replace("http://customers.lightcastmedia.com/cupertinoconsole/" + Client_ID + "/" + Console_ID + ".m3u8");
            //return true;
        }

        var URL = '/LiveMessage/LightCastInfo/' + Video_ID + "?Format=JSON";
        $.getJSON(URL, function (data) {
            //data = data.Item;
            if (data.length == 0) {
                System.DebugWrite("Error on get LightCastInfo");
            } else {
                data = data.Item;
                System.DebugWrite("Showing Lightcast Video");
                System.Lightcast.PlayLiveVideo(ID, data.pHeight, data.FlashVars, data.Console.Type, data.URL, data.Client_ID, data.Console.ID, SecondsIntoVideo);
                if (FinishFunc != null) {
                    FinishFunc();
                }
            }
        });
    },
    Create_LightcastFrom_Video: function (ID, Video, Console_ID, SecondsIntoVideo) {
        System.Lightcast.PlayLiveVideoWithCall(ID, Video.LightCast_Client_ID, Console_ID, Video.LightCastVideo_ID, SecondsIntoVideo);
    }
}

    System.SevenHills.AJAXForm = function (TheForm, ThankYouArea, DialogArea) {
        var PreSaveCall = null;
        var PostSaveCall = null;
        var Obj = {
            Form: "",
            ThankYou: "",
            Dialog: "",
            ItemID: "",
            Submitting: false,
            SetPreSaveCall: function (Func) {
                PreSaveCall = Func;
            },
            SetPostSaveCall: function (Func) {
                PostSaveCall = Func;
            },
            SetItemID: function (ID) {
                System.DebugWrite("SetItemID called ID=" + ID);
                Obj.ItemID = ID;
            },
            GetItemID: function () {
                System.DebugWrite("GetItemID called");
                return Obj.ItemID;
            },
            Init: function (TheForm, ThankYouArea, DialogArea) {
                System.DebugWrite("Init called");
                Obj.Form = TheForm;
                Obj.ThankYou = ThankYouArea;
                Obj.Dialog = DialogArea;

                $(Obj.Form).unbind("submit");
                $(Obj.Form).submit(function () {
                    //                    if (Obj.ItemID == "") {
                    //                        return true;
                    //                    }
                    if (Obj.Submitting) {
                        return false;
                    }
                    Obj.Submitting = true;
                    System.DisableElements($(Obj.Form).find("input[type='submit']"));
                    var post_url = $(Obj.Form).attr("action") + '?Format=JSON';
                    System.DebugWrite(post_url);
                    var replacetext = 'replaceme';
                    System.DebugWrite("Obj.ItemID=" + Obj.ItemID);
                    post_url = post_url.replace(replacetext, Obj.ItemID);
                    System.DebugWrite(post_url);
                    if (PreSaveCall != null) {
                        PreSaveCall($(Obj.Form));
                    }
                    var form_data = $(Obj.Form).serialize();
                    $.post(post_url, form_data, function (data, status) {
                        //data = data.Item;
                        Obj.Submitting = false;
                        if (status == "success" && data.IsError == false) {
                            Obj.ShowThankYou(data);
                            if (PostSaveCall != null) {
                                PostSaveCall(data.Item);
                            }
                        } else {
                            Obj.ShowErrors(data);
                        }
                    }, "json");
                    return false;
                });
                Obj.Clear();
            },
            ShowThankYou: function (data) {
                System.DebugWrite("ShowThankYou called");
                //$("#signupdialog").dialog('close');
                $(Obj.ThankYou).html(data.Message);
                $(Obj.Form).fadeOut();
                $(Obj.ThankYou).fadeIn();
            },
            ShowErrors: function (data) {
                System.DebugWrite("ShowErrors called");
                $(Obj.Form).find(".applicationerrors").html("");
                $(Obj.Form).find(".error").html("");
                $(Obj.Form).find(".error").fadeOut();
                System.EnableElements($(Obj.Form).find("input[type='submit']"));

                $(Obj.Form).find(".applicationerrors").append("Errors saving<br/>");
                $(Obj.Form).find(".applicationerrors").append(data.Message);
                $(Obj.Form).find(".applicationerrors").fadeIn();
                $.each(data.FieldList, function (i, item) {
                    //alert("#registerdialog #" + item.PropertyName + "_Error");
                    $(Obj.Form).find("#" + item.PropertyName + "_RegError").append("* " + item.Message);
                    $(Obj.Form).find("#" + item.PropertyName + "_RegError").fadeIn();

                });
                if (Obj.Dialog != null) {
                    $(Obj.Dialog).scrollTop(0);
                    var top = 1000000;
                    $.each(data.FieldList, function (i, item) {
                        //alert('Item:' + item.PropertyName);
                        //alert(' Pos:' + $("#" + item.PropertyName).position().top);
                        if ($(Obj.Form).find("#" + item.PropertyName + "_RegError").position().top < top) {
                            top = $(Obj.Form).find("#" + item.PropertyName + "_RegError").position().top;
                        }
                    });
                    //alert('setting top to:' + top);
                    $(Obj.Dialog).animate({ scrollTop: (top - 50) }, 'slow');
                }
            },
            Clear: function () {
                System.DebugWrite("Clear called");
                //alert('SetupSignUpForm');
                $(Obj.Form).find(".applicationerrors").html("");
                $(Obj.Form).find(".error").html("");
                $(Obj.Form).find(".error").fadeOut();
                $(Obj.Form).fadeIn();
                $(Obj.ThankYou).fadeOut();
                $(Obj.Form).find("input[type=text]").val("");
                $(Obj.Form).find("textarea").val("");
                $(Obj.Form).find("input[type=checkbox]").removeAttr("checked");
                $(Obj.Form).find("input[type=radio]").removeAttr("checked");
                $(Obj.Form).find("option").removeAttr("selected");

                System.EnableElements($(Obj.Form).find("input[type='submit']"));
            }
        }
        $(function () {
            Obj.Init(TheForm, ThankYouArea, DialogArea);
        });
        return Obj;
    }
