//Define Kpw object only if it's not already defined
if ("undefined" == typeof Kpw) {Kpw = {};}

//Initialize ImageClick
$().ready(function(){
	Kpw.Vendor.init();
	if (typeof Sys != "undefined" && Sys.WebForms && Sys.WebForms.PageRequestManager && Sys.WebForms.PageRequestManager.getInstance() != null) {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Kpw.Vendor.Gallery.bindEvents);
    }
});

//Kpw Vendor Object
Kpw.Vendor = {
    bindEvents: function() {

        $('div.editingToolbar div.vendorToolbar ul li.editingMode').attr('display', 'none');

        //init photo editing
        if (Kpw.Vendor.Editable == "true") {

            //initialize button hover
            $("a.ui-button").hover(function() {
                $(this).addClass("ui-state-hover");
            }, function() {
                $(this).removeClass("ui-state-hover");
            });

            //initialize scroll button hover
            $("a.scrollLeft").hover(function() {
                $(this).children("span")
					.addClass("ui-icon-circle-arrow-w")
					.removeClass("ui-icon-arrowthick-1-w");
            }, function() {
                $(this).children("span")
					.addClass("ui-icon-arrowthick-1-w")
					.removeClass("ui-icon-circle-arrow-w");
            });
            $("a.scrollRight").hover(function() {
                $(this).children("span")
					.addClass("ui-icon-circle-arrow-e")
					.removeClass("ui-icon-arrowthick-1-e");
            }, function() {
                $(this).children("span")
					.addClass("ui-icon-arrowthick-1-e")
					.removeClass("ui-icon-circle-arrow-e");
            });

            //show profile pic link to upload.
            $("div.picture div.uploadPicLink").removeClass("hide");
            $("div.picture img").css({ opacity: 0.9 });

        }
    },
    Data: {
        clear: function() {
            Kpw.Data.data = {};
            $("div.kpw div.vendor input.data").attr("value", "");
        },
        update: function() {
            //re-initialize data array
            Kpw.Vendor.Data.data = new Array();

            var photo;

            //populate primary photo data
            photo = {
                Position: 0,
                Id: $("div.kpw div.vendor div.primaryPhoto input.photoId").attr("value"),
                Alt: $("div.kpw div.vendor div.primaryPhoto img").attr("alt"),
                Title: $("div.kpw div.vendor div.primaryPhoto img").attr("title"),
                ThumbnailPath: $("div.kpw div.vendor div.primaryPhoto input.thumbnailPath").attr("value"),
                FullsizePath: $("div.kpw div.vendor div.primaryPhoto input.fullsizePath").attr("value")
            }
            Kpw.Vendor.Data.data.push(photo);

            //populate secondary photo data
            $("div.kpw div.vendor div.gallery div.thumbnails li.thumbnail img").each(function(i) {
                photo = {
                    Position: i + 1,
                    Id: $(this).parent().find("input.photoId").attr("value"),
                    Alt: $(this).attr("alt"),
                    Title: $(this).attr("title"),
                    ThumbnailPath: $(this).parent().find("input.thumbnailPath").attr("value"),
                    FullsizePath: $(this).parent().find("input.fullsizePath").attr("value")
                }
                Kpw.Vendor.Data.data.push(photo);
            });

            $("div.kpw div.vendor input.data").attr("value", JSON.stringify(Kpw.Vendor.Data.data));
        }
    },
    Edit: {
        Blog: {
            click: function() {
                $("div.editBlog").dialog('open');
            },
            init: function() {
                //init tabs
                $("div.editBlogOptions").tabs();

                //init post dialog
                $("div.editBlog").dialog({
                    title: 'Edit Blog',
                    autoOpen: false,
                    resizable: false,
                    height: 500,
                    width: 600,
                    modal: true,
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.5
                    },
                    open: function() {
                        $(this).parent().appendTo($("form:first"));
                        Kpw.Vendor.Edit.TinyMce.init();
                        $("textarea.post").focus();
                    },
                    buttons: {
                        'Publish Post': function() {
                            Kpw.Vendor.Edit.Blog.save();
                        },
                        'Save Post': function() {
                            Kpw.Vendor.Edit.Blog.save();
                        },
                        'Preview': function() {
                            Kpw.Vendor.Edit.Blog.save();
                        },
                        'Cancel': function() {
                            $(this).dialog('close');
                        }
                    },
                    closeOnEscape: true
                });

                $("div.editBlog").prev().addClass("editBlogHeader");
                $("div.editBlog").next().addClass("editBlogFooter");
                $("div.editBlog").parent().addClass("editBlogWrapper");
                $("div.editBlogHeader span.ui-dialog-title").after('<span class="caption">Create & edit your blog posts / Import Blog Settings</span>');


                var blogHistory = $("#blogHistory");
                if (blogHistory.length > 0) {
                    blogHistory.jqGrid({
                        url: '/KpwSite/handlers/GetBlogPosts.ashx',
                        datatype: "json",
                        colNames: ['Id', 'Title', 'Status', 'Last Edit Date'],
                        colModel: [{ name: 'Id', index: 'Id', width: 25 },
                                    { name: 'Title', index: 'Title', width: 150 },
                                    { name: 'Status', index: 'Status', width: 50 },
                                    { name: 'Last Edit Date', index: 'Edited', width: 40 }
                                    ],
                        rowNum: 10,
                        rowList: [10, 20, 30],
                        pager: '#blogHistoryPager',
                        viewrecords: true,
                        rownumbers: true,
                        gridview: true,
                        sortname: 'Id',
                        sortorder: "desc",
                        caption: "",
                        toolbar: [true, "top"],
                        width: 700
                    })
                    .navGrid("#blogHistoryPager", { add: false, edit: false, del: false, search: false });
                }

            },
            save: function() {
                __doPostBack('ctl00$phContent$ucEditPageText$lbMainDescriptionTextSave', '');
            },
            show: function(ui) {
                switch (ui) {
                    case "NewPost":
                        $("div.editBlog div#post div.newPost").show();
                        $("div.editBlog div#post div.editPosts").hide();
                        $("div.editBlog div#post div.commentModeration").hide();
                        break;
                    case "EditPosts":
                        $("div.editBlog div#post div.newPost").hide();
                        $("div.editBlog div#post div.editPosts").show();
                        $("div.editBlog div#post div.commentModeration").hide();
                        break;
                    case "CommentModeration":
                        $("div.editBlog div#post div.newPost").hide();
                        $("div.editBlog div#post div.editPosts").hide();
                        $("div.editBlog div#post div.commentModeration").show();
                        break;
                }
            }
        },
        EditPageText: {
            click: function() {
                $("div.editPageText").dialog('open');
            },
            init: function() {

                //init dialog
                $("div.editPageText").dialog({
                    title: 'Edit Your Page',
                    autoOpen: false,
                    resizable: false,
                    height: 500,
                    width: 600,
                    modal: true,
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.5
                    },
                    open: function() {
                        $(this).parent().appendTo($("form:first"));
                        //Kpw.Vendor.Edit.TinyMce.init();
                        $("textarea.mainDescriptionText").focus();
                    },
                    buttons: {
                        'Save': function() {
                            Kpw.Vendor.Edit.EditPageText.save();
                        },
                        'Cancel': function() {
                            $(this).dialog('close');
                        }
                    },
                    closeOnEscape: true
                });

                $("div.editPageText").prev().addClass("editPageTextHeader");
                $("div.editPageText").next().addClass("editPageTextFooter");
                $("div.editPageText").parent().addClass("editPageTextWrapper");
                $("div.editPageTextWrapper span.ui-dialog-title").after('<span class="caption">Edit your description text &amp; contact info</span>');

                //apply phone mask
                $("div.contactAndInfo td.phone input").mask("(999) 999-9999");
            },
            save: function() {
                __doPostBack('ctl00$phContent$ucEditPageText$lbMainDescriptionTextSave', '');
            }
        },
        ProfilePic: {
            click: function() {

                var proceed = true;
                if (Kpw.Vendor.Data.changed && Kpw.Vendor.Data.changed == true) {
                    proceed = confirm("You have unsaved changes to your gallery.  Click OK to continue without saving or click Cancel to stop and save your Gallery changes.");
                }
                if (proceed) {
                    Kpw.ProfilePic.init();
                    $("div.profilePicTool").dialog('open');
                }
            },
            init: function() {

                //init dialog
                $("div.profilePicTool").dialog({
                    title: 'Upload Your Profile Picture',
                    autoOpen: false,
                    resizable: false,
                    height: 600,
                    width: 700,
                    modal: true,
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.5
                    },
                    open: function() {
                        $(this).parent().appendTo($("form:first"));
                    },
                    closeOnEscape: true
                });

                $("div.profilePicTool").prev().addClass("profilePicToolHeader");
                $("div.profilePicTool").next().addClass("profilePicToolFooter");
                $("div.profilePicTool").parent().addClass("profilePicToolWrapper");
                $("div.profilePicToolWrapper span.ui-dialog-title").after('<span class="caption">Crop Your Profile Picture</span>');

            }
        },
        init: function() {
            Kpw.Vendor.Edit.Blog.init();
            Kpw.Vendor.Edit.EditPageText.init();
            Kpw.Vendor.Edit.ProfilePic.init();

            //if the editPageMode element is visible, then go right to edit mode...
            if ($(".editPageMode").length > 0) {
                Kpw.Vendor.Edit.EditPageText.click();
            }
        },
        TinyMce: {
            init: function() {
                tinyMCE.init({
                    // General options
                    mode: "textareas",
                    theme: "advanced",
                    plugins: "safari,pagebreak,style,layer,save,advimage,advlink,preview,contextmenu,paste,spellchecker",

                    // Theme options
                    theme_advanced_buttons1: "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,blockquote,|,link,unlink,image,|,spellchecker,code",
                    theme_advanced_buttons2: "",
                    theme_advanced_buttons3: "",
                    theme_advanced_disable: "hr,sub, sup, charmap, visualaid",
                    theme_advanced_toolbar_location: "top",
                    theme_advanced_toolbar_align: "left",
                    theme_advanced_statusbar_location: "bottom",
                    theme_advanced_resizing: true,

                    //Spellchecker
                    spellchecker_languages: "English=en",
                    spellchecker_rpc_url: "TinyMCE.ashx?module=SpellChecker",

                    // Example content CSS (should be your site CSS)
                    content_css: "/KpwSite/css/kpw.css,/KpwSite/Editor/tinymce/examples/css/word.css"
                });
            }
        }
    },
    init: function() {
        //get editable status
        Kpw.Vendor.Editable = $("div.kpw div.vendor input.isEditable").attr("value");

        //bind events
        Kpw.Vendor.bindEvents();

        //initialize photo editing
        Kpw.Vendor.Photos.init();

        //init photo tray
        Kpw.Vendor.Photos.Tray.init(true);

        //init blog
        Kpw.Vendor.Blog.init();

        //User tools - print, save, email.
        Kpw.Vendor.UserTools.init();

        //init edit dialogs
        Kpw.Vendor.Edit.init();

        //bind Gallery events
        Kpw.Vendor.Gallery.bindEvents();

        Kpw.Vendor.Contact.init();
    },
    Contact: {
        init: function() {

            //init dialog
            $("div.vendorContact").dialog({
                title: 'Contact Vendor',
                autoOpen: false,
                resizable: false,
                height: 550,
                width: 600,
                modal: true,
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.5
                },
                open: function() {
                    $(this).parent().appendTo($("form:first"));
                    //$("textarea.post").focus();
                },
                closeOnEscape: true
            });

            $("div.vendorContact").prev().addClass("vendorContactHeader");
            $("div.vendorContact").next().addClass("vendorContactFooter");
            $("div.vendorContact").parent().addClass("vendorContactWrapper");
            $("div.vendorContactHeader span.ui-dialog-title").after('<span class="caption">Message</span>');

        },
        Open: function() {
            $("div.vendorContact").dialog('open');
        }
    },
    PageContent: {
        Text: {
            edit: function() {
                alert("edit page content!");
            },
            update: function() {
                alert("update page content!");
            }
        }
    },
    Photos: {
        init: function() {
            Kpw.Vendor.Data.changed = false;

            // there's the gallery and the trash
            var $thumbnails = $("div.photoTray ul.thumbnails")
            var $gallery = $("div.gallery ul.photos");

            // let the gallery items be draggable
            $('li', $thumbnails).draggable({
                cancel: 'a.ui-icon',
                revert: 'invalid',
                helper: 'clone',
                appendTo: 'body',
                zIndex: '99',
                cursor: 'move'
            });

            // let the trash be droppable, accepting the gallery items
            $("div.gallery div.primaryPhoto, div.gallery div.thumbnails li.thumbnail").droppable({
                activeClass: 'ui-state-highlight',
                hoverClass: 'ui-drophover',
                drop: function(ev, ui) {
                    $(this).html("");

                    var removeImage = '<a href="#Remove" class="removePhoto" title="remove" onclick="Kpw.Vendor.Photos.remove(this);return false;"></a>';
                    $(this).prepend(removeImage);
                    $("a.removePhoto").fadeIn("fast");

                    var image = $(ui.draggable).clone();
                    $(this).find("a.removePhoto").after(image.html());
                    image.remove();

                    var fullsizePath = $(this).find("span input.fullsizePath").attr("value");
                    var thumbnailPath = $(this).find("span input.thumbnailPath").attr("value");

                    if ($(this).hasClass("thumbnail")) {
                        $(this).find("span img")
					        .attr("src", thumbnailPath)
					        .css("width", "100%");
                    }
                    else {
                        $(this).find("span img")
					        .attr("src", fullsizePath)
					        .css("width", "100%");
                    }


                    //re-init photo tray
                    Kpw.Vendor.Photos.Tray.init(false);

                    Kpw.Vendor.Data.update();

                    Kpw.Vendor.Data.changed = true;
                }
            });
        },
        remove: function(el) {
            $(el).fadeOut("fast", function() {
                $(el).parent().children("span").children("img").remove();
                $(this).remove();
            });
            $(el).parent().children("span").children("img").fadeOut("fast");
        },
        Tray: {
            init: function(setLeft) {
                //debugger;

                //set width of widget bar
                var menuWidth;
                var menu;
                var thumbnails;
                var thumbnailClone;
                var oneEm;
                var buffer;
                var photoItemWidth = 0;

                //get em size and set buffer
                oneEm = $("body").css("font-size").replace(/px/g, "");
                buffer = oneEm;

                //get thumbnails
                $("li.thumbnail:first").addClass("thumbnailFirst");
                $("li.thumbnail:last").addClass("thumbnailLast");
                thumbnails = $("li.thumbnail");
                thumbnailClone = $("li.thumbnail:first").clone();
                $("body").prepend(thumbnailClone);
                thumbnailClone
					.css("position", "absolute")
					.css("left", "-10000px")
					.css("display", "block");

                if (thumbnails.length === 0) {
                    menuWidth = 52 + buffer;
                } else {
                    thumbnailWidth = parseInt(thumbnailClone.outerWidth(true));
                    menuWidth = (thumbnails.length + 2) * thumbnailWidth;
                }

                thumbnailClone.remove();

                menu = $("div.photoTray ul.thumbnails");
                menu.css("width", menuWidth);
                if (setLeft)
                    menu.css("left", menuWidth + "px");
            },
            Scroll: {
                left: function() {
                    var thumbnails = $("ul.thumbnails");
                    var thumbnailsWidth = parseInt(thumbnails.width());
                    var thumbnailsWrapperWidth = parseInt(thumbnails.parent().width());
                    var left = parseInt(thumbnails.css("left").replace(/px/g, ""));  //remove the "px"
                    var thumbnailsRightEdge = thumbnailsWidth + left;

                    left = left + (left <= -Kpw.Vendor.Photos.Tray.slideDistance ? Kpw.Vendor.Photos.Tray.slideDistance : -left);
                    var newLeft = left + "px";
                    thumbnails.animate({ left: newLeft });
                },
                right: function() {
                    var thumbnails = $("ul.thumbnails");
                    var thumbnailsWidth = parseInt(thumbnails.width());
                    var thumbnailsWrapperWidth = parseInt(thumbnails.parent().width());
                    var left = parseInt(thumbnails.css("left").replace(/px/g, ""));  //remove the "px"
                    var thumbnailsRightEdge = thumbnailsWidth + left;

                    if (thumbnailsRightEdge > thumbnailsWrapperWidth)
                        left = left - (thumbnailsRightEdge > thumbnailsWrapperWidth + Kpw.Vendor.Photos.Tray.slideDistance ? Kpw.Vendor.Photos.Tray.slideDistance : (thumbnailsWidth - thumbnailsWrapperWidth) + left);
                    var newLeft = left + "px";
                    thumbnails.animate({ left: newLeft });
                }
            },
            slideDistance: 500,
            toggle: function() {
                var tray = $("div.photoTray");
                var thumbnailList = tray.find("ul.thumbnails")
                var removeImage = '<a href="#Remove" class="removePhoto" title="remove" onclick="Kpw.Vendor.Photos.remove(this);return false;"></a>';
                if (tray.is(":hidden")) {
                    tray.slideDown("fast", function() {
                        tray.find("p.scrollWrapper a").fadeIn("fast");
                        thumbnailList.animate({ left: "0" });
                        if ($("div.vendor div.primaryPhoto img").length != 0)
                            $("div.vendor div.primaryPhoto").prepend(removeImage);
                        $("div.gallery div.thumbnails li.thumbnail").each(function() {
                            if ($(this).find("img").length != 0)
                                $(this).prepend(removeImage);
                        });
                        $("a.removePhoto").fadeIn("fast");
                        $("div.primaryPhoto, div.gallery div.thumbnails li.thumbnail").addClass("ui-dropReady");
                    });
                } else {
                    var tray = $("div.photoTray");
                    var thumbnailList = tray.find("ul.thumbnails");
                    $("a.removePhoto").fadeOut("fast", function() {
                        $(this).remove();
                    });
                    tray.find("p.scrollWrapper a").fadeOut("fast");
                    $("div.primaryPhoto, div.gallery div.thumbnails li.thumbnail").removeClass("ui-dropReady");
                    thumbnailList.animate({ left: parseInt(thumbnailList.outerWidth(true)) }, function() {
                        tray.slideUp("fast");
                    });
                }

            }
        }
    },
    UserTools: {
        init: function() {
            $("#toolsSave").bind("click", function(e) {

                //center loading div
                var buttonTop = $("#toolsSave").offset().top;
                var buttonLeft = $("#toolsSave").offset().left;

                $("#savePopup").css({
                    "position": "absolute",
                    "top": buttonTop - 11,
                    "left": buttonLeft - 90
                });

                $("#savePopup").show("blind", null, 500);

            });

            $("#savePopup").hover(
                  function() {
                  },
                  function() {
                      $("#savePopup").hide("blind", 500);
                  }
            );

            $("#savePopup").hide();
        }
    },
    Blog: {
        clickWwwBlog: function() {

            if ($("#wwwBlogTabView").html() != "") {
                Kpw.Vendor.Blog.showWwwBlog();
                return;
            }

            //center loading div
            var windowTop = $("div.blogContent").offset().top;
            var windowLeft = $("div.blogContent").offset().left;
            var windowWidth = $("div.blogContent").width();
            var popupWidth = $("#wwwLoading").width();

            $("#wwwLoading").css({
                "position": "absolute",
                "top": windowTop + 20,
                "left": windowLeft + (windowWidth / 2 - popupWidth / 2)
            });

            $("#wwwLoading").fadeIn("slow");
            var url = $(".externalBlogUrl").val();
            url += " div.wwwblog"
            $("#wwwBlogTabView").load(url, { 'rss': $(".wwwRssUrl").val() }, function() {
                $("#wwwLoading").fadeOut("slow");

                //switch tabs
                Kpw.Vendor.Blog.showWwwBlog();
            });
        },
        clickEditorialContent: function() {

            if ($("#editorialContributions").html() != "") {
                Kpw.Vendor.Blog.showEditorialContributions();
                return;
            }

            //center loading div
            var windowTop = $("div.blogContent").offset().top;
            var windowLeft = $("div.blogContent").offset().left;
            var windowWidth = $("div.blogContent").width();
            var popupWidth = $("#wwwLoading").width();

            $("#wwwLoading").css({
                "position": "absolute",
                "top": windowTop + 20,
                "left": windowLeft + (windowWidth / 2 - popupWidth / 2)
            });

            $("#wwwLoading").fadeIn("slow");
            var url = $(".editorialContribUrl").val();
            url += " div.blog"
            $("#editorialContributions").load(url, {}, function() {
                $("#wwwLoading").fadeOut("slow");

                //switch tabs
                Kpw.Vendor.Blog.showEditorialContributions();
            });
        },
        showWwwBlog: function() {
            $("#kpwBlogTabView").addClass("hide");
            $("li.myKpwBlog a").removeClass("selected");

            $("#editorialContributions").addClass("hide");
            $("li.editorialContributions a").removeClass("selected");

            $("#wwwBlogTabView").removeClass("hide");
            $("li.wwwBlog a").addClass("selected");

            $("li.myKpwBlog a").bind("click", Kpw.Vendor.Blog.showKpwBlog);
            $("li.editorialContributions a").bind("click", Kpw.Vendor.Blog.clickEditorialContent);
            $("li.wwwBlog a").unbind("click");
        },
        showKpwBlog: function() {
            $("#kpwBlogTabView").removeClass("hide");
            $("li.myKpwBlog a").addClass("selected");

            $("#editorialContributions").addClass("hide");
            $("li.editorialContributions a").removeClass("selected");

            $("#wwwBlogTabView").addClass("hide");
            $("li.wwwBlog a").removeClass("selected");

            $("li.wwwBlog a").bind("click", Kpw.Vendor.Blog.clickWwwBlog);
            $("li.editorialContributions a").bind("click", Kpw.Vendor.Blog.showEditorialContributions);
            $("li.myKpwBlog a").unbind("click");
        },
        showEditorialContributions: function() {
            $("#kpwBlogTabView").addClass("hide");
            $("li.myKpwBlog a").removeClass("selected");

            $("#wwwBlogTabView").addClass("hide");
            $("li.wwwBlog a").removeClass("selected");

            $("#editorialContributions").removeClass("hide");
            $("li.editorialContributions a").addClass("selected");

            $("li.myKpwBlog a").bind("click", Kpw.Vendor.Blog.showKpwBlog);
            $("li.wwwBlog a").bind("click", Kpw.Vendor.Blog.clickWwwBlog);
            $("li.editorialContributions a").unbind("click");
        },
        init: function() {

            //blog tabs
            $("li.wwwBlog a").bind("click", Kpw.Vendor.Blog.clickWwwBlog);
            $("li.editorialContributions a").bind("click", Kpw.Vendor.Blog.clickEditorialContent);

            if ($("ul.contentTabs li.myKpwBlog").length == 0) {
                Kpw.Vendor.Blog.clickWwwBlog();
            }

        }
    },
    Gallery: {
        bindEvents: function() {

            $('span.photoWrapper img.galleryThumb').css({ filter: 'alpha(opacity=100)', opacity: '1' });

            $('span.photoWrapper img.galleryThumb').mouseover(
                function() {
                    $(this).css({ filter: 'alpha(opacity=55)', opacity: '0.55' });
                }
             );

            $('span.photoWrapper img.galleryThumb').mouseout(
                function() {
                    $(this).css({ filter: 'alpha(opacity=100)', opacity: '1' });
                }
             );

            //bind thumb/main swap
            $('img.galleryThumb').click(
                function() {
                    //Get the path for the fullsize image
                    var filepath = $(this).parent().find("input.fullsizePath").attr("value");
                    //Get the content id for media popup
                    var contentId = $(this).parent().find("input.photoId").attr("value");
                    //Get the file extension of the gallery item
                    var extension = Kpw.Vendor.Gallery.getFileExtension(filepath);
                    //Get the media type based on the file extension
                    var mediaPlayer = Kpw.Vendor.Gallery.getPlayerFromExtension(extension);
                    //Swap based on type
                    if (mediaPlayer == 'image') {
                        Kpw.Vendor.Gallery.imageSwap(filepath, contentId);
                    }
                    else {
                        Kpw.Vendor.Gallery.mediaSwap(mediaPlayer, filepath, contentId);
                    }

                    if ("undefined" != typeof Kpw.Analytics) {
                        Kpw.Analytics.logContent(contentId);
                    }
                }
            );
        },
        imageSwap: function(largeSource, contentId) {
            var image = new Image();
            var imgHtml = "<img class='imgGalleryPrimary' id='imgGalleryPrimary' src='" + largeSource + "' alt='Main Photo' runat='server'/>";
            var html = $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media').html();

            //If the media html is already an image, just change the src - else, change the markup altogether...
            if (html.indexOf('<img') != -1 || ($.browser.msie && html.indexOf('<IMG') != -1)) {
                //don't switch the image til its been loaded.

                $(image).load(function() {
                    //fade out - fade in after load.
                    $("div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media").fadeOut("slow", function() {
                        $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media img').attr('src', largeSource);
                        $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media').parent().find("input.photoId").attr("value", contentId)
                        $("div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media").fadeIn("slow");
                    });
                });

                image.src = largeSource;

            }
            else {

                //fade in after image is loaded load.
                $(image).load(function() {
                    $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media').fadeIn("slow");
                    $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media').html(imgHtml);
                    $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media').parent().find("input.photoId").attr("value", contentId);
                });

                image.src = largeSource;
            }
        },
        mediaSwap: function(mediaPlayer, filePath, contentId) {
            var markup = Kpw.Vendor.Gallery.getMarkUp(mediaPlayer, filePath);
            $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media').html(markup);
            $('div.kpw div.vendor div.primaryPhoto span.photoWrapper span.media').parent().find("input.photoId").attr("value", contentId);
        },
        getFileExtension: function(file) {
            var dot = file.lastIndexOf(".");
            var extension = "";
            if (dot != -1) {
                extension = file.substr(dot + 1, file.length).toLowerCase();
            }
            return extension;
        },
        getPlayerFromExtension: function(extension) {
            var winmedia = 'asx,asf,avi,wma,wmv';
            var flash = 'flv,swf,mov';
            var quicktimeAudio = 'mp3,wav,mid,midi';
            var quicktimeVideo = 'mpg,mpeg,m4a';
            var quicktimeMP4 = 'mp4';
            var real = 'ra,ram,rm,rpm,rv,smi,smil';
            var image = 'jpg,bmp,gif,png,jpeg';

            if (winmedia.indexOf(extension) != -1) {
                return 'winmedia';
            }
            else if (image.indexOf(extension) != -1) {
                return 'image';
            }
            else if (flash.indexOf(extension) != -1) {
                return 'flash';
            }
            else if (quicktimeAudio.indexOf(extension) != -1) {
                return 'quicktimeAudio';
            }
            else if (quicktimeVideo.indexOf(extension) != -1) {
                return 'quicktimeVideo';
            }
            else if (quicktimeMP4.indexOf(extension) != -1) {
                return 'quicktimeMP4';
            }
            else if (real.indexOf(extension) != -1) {
                return 'real';
            }
            else {
                return 'none';
            }
        },
        getMarkUp: function(playerType, filePath) {
            var markup = "";

            switch (playerType) {
                case 'winmedia':
                    markup = "<object type='video/x-ms-wmv' data=\"" + filePath + "\" width='713' height='528'>" +
                                   "<param name='src' value=\"" + filePath + "\" />" +
                                   "<param name='autostart' value='true' />" +
                                   "<param name='pluginurl' value='http://port25.technet.com/pages/windows-media-player-firefox-plugin-download.aspx' />" +
                               "</object>"
                    break;
                case 'flash':
                    markup = "<object width='713' height='528' " +
                                "data='http://releases.flowplayer.org/swf/flowplayer-3.1.5.swf' type='application/x-shockwave-flash'>" +
                                "<param name='movie' value='http://releases.flowplayer.org/swf/flowplayer-3.1.5.swf' />" +
                                "<param name='allowfullscreen' value='true' />" +
                                "<param name='allowscriptaccess' value='always' />" +
                                "<param name='flashvars' value='config={\"plugins\":{\"pseudo\":{\"url\":\"flowplayer.pseudostreaming-3.1.3.swf\"},\"controls\":{\"backgroundColor\":\"#46301b\",\"sliderColor\":\"#46301b\",\"sliderGradient\":\"none\", \"volumeSliderColor\":\"#362008\",\"buttonColor\":\"#362008\",\"durationColor\":\"#362008\",\"progressColor\":\"#999999\",\"timeColor\":\"#ffffff\",\"timeBgColor\":\"#999999\",\"bufferColor\":\"#46301b\",\"backgroundGradient\":\"low\"}}, \"play\":{\"opacity\":\"0\"} ,\"canvas\": {\"backgroundColor\": \"#000000\",\"backgroundGradient\":\"none\"},\"clip\":{\"provider\":\"pseudo\",\"scaling\":\"fit\",\"url\":\"" + filePath + "\"},\"playlist\":[{\"provider\":\"pseudo\",\"url\":\"" + filePath + "\"}]}' />" +
                             "</object>"
                    break;
                case 'quicktimeAudio':
                    markup = "<!--[if !IE]><!-->" +
                                "<object type='audio/x-mpeg' data=\"" + filePath + "\" width='713' height='528'>" +
                                "<param name='src' value=\"" + filePath + "\" />" +
                                "<param name='controller' value='true' />" +
                                "<param name='autoplay' value='false' />" +
                                "<param name='autostart' value='0' />" +
                                "<param name='pluginurl' value='http://www.apple.com/quicktime/download/' />" +
                                "</object>" +
                            "<!--<![endif]-->" +
                            "<!--[if gte IE 7]>" +
                                "<object  classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab' width='713' height='528'>" +
                                "<param name='src' value=\"" + filePath + "\" />" +
                                "<param name='controller' value='true' />" +
                                "<param name='autoplay' value='false' />" +
                                "<param name='autostart' value='0' />" +
                                "<param name='pluginurl' value='http://www.apple.com/quicktime/download/' />" +
                                "</object>" +
                            "<![endif]-->" +
                            "<!--[if lt IE 7]>" +
                                "<object  classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab' width='713' height='528'>" +
                                "<param name='src' value=\"" + filePath + "\" />" +
                                "<param name='controller' value='true' />" +
                                "<param name='autoplay' value='false' />" +
                                "<param name='autostart' value='0' />" +
                                "<embed src=\"" + filePath + "\" type='audio/x-mpeg' width='713' height='528' autostart='false' controller='true' ></embed>" +
                                "<param name='pluginurl' value='http://www.apple.com/quicktime/download/' />" +
                                "</object>" +
                            "<![endif]-->"
                    break;
                case 'quicktimeVideo':
                    markup = "<!--[if !IE]><!-->" +
                                "<object type='video/quicktime' data=\"" + filePath + "\" width='713' height='528'>" +
                                "<param name='controller' value='true' />" +
                                "<param name='autoplay' value='false' />" +
                                "<param name='autostart' value='0' />" +
                                "<param name='pluginurl' value='http://www.apple.com/quicktime/download/' />" +
                                "</object>" +
                            "<!--<![endif]-->" +
                            "<!--[if gte IE 7]>" +
                                "<object classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' width='713' height='528'>" +
                                "<param name='src' value=\"" + filePath + "\" />" +
                                "<param name='controller' value='true' />" +
                                "<param name='autoplay' value='false' />" +
                                "<param name='autostart' value='0' />" +
                                "<param name='pluginurl' value='http://www.apple.com/quicktime/download/' />" +
                                "</object>" +
                            "<![endif]-->" +
                            "<!--[if lt IE 7]>" +
                                "<object classid='clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b' width='713' height='528' codebase='http://www.apple.com/qtactivex/qtplugin.cab'>" +
                                "<param name='src' value=\"" + filePath + "\">" +
                                "<param name='controller' value='true'>" +
                                "<param name='autoplay' value='false'>" +
                                "<param name='autostart' value='0' /> " +
                                "<embed src=\"" + filePath + "\" width='713' height='528' autoplay='false' controller='true' pluginspage='http://www.apple.com/quicktime/download/'></embed>" +
                                "<param name='pluginurl' value='http://www.apple.com/quicktime/download/' />" +
                                "</object>" +
                            "<![endif]-->"
                    break;
                case 'quicktimeMP4':
                    markup = "<object classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' width='713' height='528'" +
                             "codebase='http://www.apple.com/qtactivex/qtplugin.cab'>" +
                             "<param name='src' value=\"" + filePath + "\"/>" +
                             "<param name='autoplay' value='false' />" +
                             "<param name='controller' value='true'/>" +
                             "<embed src=\"" + filePath + "\" width='713' height='528' autoplay='false' controller='true'" +
                             "pluginspage='http://www.apple.com/quicktime/download/'></embed></object>"
                    break;
                case 'real':
                    markup = "";
                    break;
            }

            return markup;
        }
    }
}
