﻿
    var info = [];
    var selPhotoClass = '.photos .selected';
    document.createElement("p0");
    document.createElement("p1");
    document.createElement("p2");
    document.createElement("p3");


    var locked = false;
    function movePhoto(photoId, th) {
        //$('.desc').fadeOut(4);
        $('.desc').hide();
        $('<div id="loadinggif" style="top:150px;left:300px;position:absolute;">Loading ...<img src="/images/loading.gif"/></div>').appendTo($('.desc').parent());
        $(selPhotoClass).removeClass('selected');
        var el = $('[pid="' + photoId + '"] img');
        var mp = $('.mainphoto');
        $('[pid="' + photoId + '"]:first').parent().addClass('selected');
        mp.show();

        if (!mp.data("isvisible")) {
            mp.center().data("isvisible", true);
        }

        var f = th.replace('Thumbs', '');
        $(imgFull).attr('src', f);
        $(imgPhoto).attr('src', el.attr('src'));
        setTimeout(function() {
            $(imgPhoto).attr('src', th).fadeIn(200).attr('src', f);
        }, 10);

        if (!info[photoId]) {
            DSInfo.Client.Web.Services.GetPhotoDisplayDetails(photoId, '', photoDetailsLoaded,
                function(a, b) {
                    locked = false;
                    alert('Requesting data from the sever failed. Please try to click on another photo');
                    $('#loadinggif').remove();
                }
);
        }
        else {
            setTimeout(function() { photoDetailsLoaded(info[photoId]); }, 10);
        }
        return false;
    }


    function moveCurrent(el) {
        if (locked) { return false; }
        locked = true;
        el = el || this;
        var id = parseInt($(el).find('a').attr('pId'), 10);
        var fn = $(el).find('img').attr('src');
        return movePhoto(id, fn);
    }

    function nextprevPhoto(e) {
        return moveCurrent(e);
    }

    function stopBubbling(e) {
        var evt = window.event || e;
        if (!evt) { return; }

        evt.cancelBubble = true;
        if (evt.stopPropagation) { evt.stopPropagation(); } if (evt.preventDefault) { evt.preventDefault(); }
    }
    function firstPhoto() {
        var c = $(selPhotoClass).parent().children(':first');
        return nextprevPhoto(c);
    }
    function lastPhoto() {
        var c = $(selPhotoClass).parent().children(':last').prev();
        return nextprevPhoto(c);
    }

    var ssTimer;
    function slideshow() {
    }

    function refreshPhoto() {
        var c = $(selPhotoClass);
        return nextprevPhoto(c);
    }

    function nextPhoto(e) {
        stopBubbling(e);
        var c = $('[pid="' + $('.selected a').attr('pid') + '"]:first').parent().next();
        if (c.length === 0) {
            c = $(selPhotoClass).parent().parent().children(':first a');
        }

        return nextprevPhoto(c);
    }
    function prevPhoto(e) {
        stopBubbling(e);
        var c = $('[pid="' + $('.selected a').attr('pid') + '"]:first').parent().prev();
        if (c.length === 0) {
            c = $(selPhotoClass).parent().parent().children(':last a').prev();
        }
        return nextprevPhoto(c);
    }

    jQuery.fn.center = function() {
        this.css({
                top: ($(window).height() - this.outerHeight()) / 2 + $(window).scrollTop() + "px",
                left: ($(window).width() - this.outerWidth()) / 2 + $(window).scrollLeft() + "px"
            });
        return this;
    };



    var C_PHOTOPATH = "http://photos.dancesportinfo.net/Gallery/{0}";
    var C_GALLERYEVENTLINK = "/Gallery/{0}/Competition/{1}/Photos.aspx";

    function clrCache(id) { info[id] = null; }
    function failure() {
        alert('Call to the server failed. Please repeat your action');
        refreshPhoto();
    }

    function addGallery(id) {
        clrCache(id);
        DSInfo.Client.Web.Services.AddToGallery(id, function() { refreshPhoto(); alert("Photo added back to the gallery"); }, failure);
    }
    function removeGallery(id) {
        clrCache(id);
        DSInfo.Client.Web.Services.RemoveFromGallery(id, function() { refreshPhoto(); alert("Photo removed from the gallery"); }, failure);
    }
    function addFavourite(id) {
        clrCache(id);
        DSInfo.Client.Web.Services.AddToFavourites(id, function() { refreshPhoto(); alert("Photo added to your favourites"); }, failure);
    }
    function removeFavourite(id) {
        clrCache(id);
        DSInfo.Client.Web.Services.RemoveFromFavourites(id, function() { refreshPhoto(); alert("Photo removed from your favourites"); }, failure);
    }

    function addProfile(id, coupleId) {
        clrCache(id);
        DSInfo.Client.Web.Services.AddToProfile(id, coupleId, function() { refreshPhoto(); alert("Photo added to the profile"); }, failure);
    }
    function removeProfile(id) {
        clrCache(id);
        DSInfo.Client.Web.Services.RemoveFromProfile(id, coupleId, function() { refreshPhoto(); alert("Photo removed from the profile"); }, failure);
    }

    function setLikes(photoId, val) {
        var t = $('.desc .likeButton');
        t.attr('likeId', photoId);
        t.attr('likes', val);
        info[photoId].Likes = val;
        LikeControl_setDisp(t);
    }
    function setProfileButtons(photoProf) {
        var canBeProfilePhoto = photoProf.CanBeProfile && CoupleId > 0;
        var id = photoProf.ID;
        var cid = photoProf.CoupleId;

        $(ProfilePhotoAdd)[0].onclick = null;
        $(ProfilePhotoRemove)[0].onclick = null;
        $(ProfilePhotoAdd).unbind('click').click(function() { Controtex.AuthManager.Current.AttemptAccess('S', function() { addProfile(id, cid); }); return false; });
        $(ProfilePhotoRemove).unbind('click').click(function() { Controtex.AuthManager.Current.AttemptAccess('S', function() { removeProfile(id, cid); }); return false; });

        ClientVisible(ProfilePhotoAdd, canBeProfilePhoto && (photoProf.ProfileIndex < 0));
        ClientVisible(ProfilePhotoRemove, canBeProfilePhoto && (photoProf.ProfileIndex >= 0));
        ClientVisible(liProfile, canBeProfilePhoto);
    }

    function setFavouriteButtons(photoProf) {
        var isFavourite = photoProf.FavouriteIndex >= 0;
        var id = photoProf.ID;
        $(FavouritePhotoAdd)[0].onclick = null;
        $(FavouritePhotoAdd).unbind('click').click(function() { Controtex.AuthManager.Current.AttemptAccess('S', function() { addFavourite(id); }); return false; });
        $(FavouritePhotoRemove)[0].onclick = null;
        $(FavouritePhotoRemove).unbind('click').click(function(e) { Controtex.AuthManager.Current.AttemptAccess('S', function() { removeFavourite(id); }); return false; });

        ClientVisible(FavouritePhotoAdd, !isFavourite);
        ClientVisible(FavouritePhotoRemove, isFavourite);
    }

    function setRemoveButtons(photoProf) {
        var guestPhoto = photoProf.GalleryId === 11;
        var id = photoProf.ID;
        $(GalleryAddButton)[0].onclick = null;
        $(GalleryRemoveButton)[0].onclick = null;
        var isPhotographer = (!photoProf.Photographer ? "--" : photoProf.Photographer).toUpperCase() === UserName.toUpperCase();
        var isRemovable = (guestPhoto || photoProf.CanBeProfile || isPhotographer);
        ClientVisible(GalleryAddButton, isRemovable && photoProf.NonDisplayable);
        ClientVisible(GalleryRemoveButton, isRemovable && photoProf.Displayable);
        ClientVisible(liGallery, isRemovable);

        if (isRemovable) {
            var uploader = (photoProf.SubmittedBy || "--").trim().toUpperCase() === UserName.trim().toUpperCase();
            var role = isPhotographer || uploader ? "U" : (guestPhoto ? "S" : "P");
            $(GalleryRemoveButton)[0].Roles = $(GalleryAddButton)[0].Roles = role;
            $(GalleryAddButton).unbind('click').click(function() { Controtex.AuthManager.Current.AttemptAccess(role, function() { addGallery(id); }); return false; });
            $(GalleryRemoveButton).unbind('click').click(function() { Controtex.AuthManager.Current.AttemptAccess(role, function() { removeGallery(id); }); return false; });
        }
    }

    function setExtraButtons(a) {
        $(pnFavourite).show();
        var photoProf = a.Rights;
        // Photo for profile
        setProfileButtons(photoProf);
        // Add or remove from the favourites
        setFavouriteButtons(photoProf);
        // Add or remove from the gallery
        setRemoveButtons(photoProf);
    }

    function photoDetailsLoaded(a) {
        var i;
        try {
            var photoId = a.PhotoId;
            info[photoId] = a;
            setLikes(photoId, a.Likes || 0);
            Service('', 'GetLikes', { likeType: 7, likeId: photoId },
                function(r) {
                    setLikes(photoId, r.d);
                }
        );
            $('#loadinggif').remove();
            $('.desc').stop(true, true).fadeIn(200);
            $('#refNo').text(photoId);

            var photoPath = String.format(C_PHOTOPATH, a.FileName);

            $('#elAdded').hide();

            $(lnkCart).unbind('click').click(function() {
                addToBasket(photoId, $(ddlProducts).attr('id'));
                return false;
            });
            $(litCoupleName).text(a.CoupleName);

            $(lnkCouplePhotos).attr('href', String.format("/Couple/{0}/Photos.aspx", a.CoupleNameEnc))
                .attr('title', String.format("More photos of {0}", a.CoupleName));
            $(lnkCoupleProfile).attr('href', String.format("/Couple/{0}/Details.aspx", a.CoupleNameEnc))
                .attr('title', String.format("Profile page of {0}", a.CoupleName));
            $(lnkCoupleResults).attr('href', String.format("/Couple/{0}/Results.aspx", a.CoupleNameEnc))
                .attr('title', String.format("Results of {0}", a.CoupleName));

            ClientVisible(liCouple, a.CoupleId > 0);
            ClientVisible(liUnknown, a.CoupleId <= 0);

            $(litRefNo).text(photoId);

            //    Session["PreAssignRawUrl"] = Request.RawUrl;
            var al = String.format("/AssignPicture.aspx?ID={0}", photoId);
            $(lnkAssignPhoto).attr('href', al).unbind('click').click(function() {
                Controtex.AuthManager.Current.AttemptAccess('U', function() { document.location = al; });
                return false;
            });

            ClientVisible(liComp, a.CompId > 0);
            ClientVisible(lnkBreadcrumbComp, a.CompId > 0);

            ClientVisible(liEvent, a.EventId > 0);
            ClientVisible(lnkBreadcrumbEvent, a.EventId > 0);
            $(litSeen).html($(litSeen).html()); // magic for IE <9
            $(litSeen).find('p0').text(a.TotalViews.toString());


            //    var gallery = GalleryController.GetGalleryInfo(a.GalleryId);

            if (a.GalleryId === 11) {
                $(litPhotographer).html("Guest " + (a.SubmittedBy?String.format(" (<a href='/Member/{0}/profile.aspx'>{1}</a>)", a.SubmittedBy, a.UserName):""));
            } else {
                $(litPhotographer).text(a.GalleryName);
            }
            $(lnkGallery).attr('href', String.format("/Gallery/{0}_{1}/Photos.aspx", a.GalleryName, a.GalleryId))
                .attr('title', String.format("More photos from {0}", a.GalleryName));

            if (IsClientVisible(liComp)) {
                //        var comp = GalleryController.GetCompetitionInfo(Language, photo.Competition.Id, photo.Event.Id, 0);
                var comp = a.Comp;
                $(lnkCompPhotos).attr('href', String.format("/Competition/{0}/Photos.aspx", a.CompNameEnc))
                    .attr('title', String.format("More photos from {0}", a.CompName));
                $(lnkCompEvents).attr('href', String.format("/Competition/{0}/EventList.aspx", a.CompNameEnc))
                    .attr('title', String.format("Events from {0}", a.CompName));
                $(lnkCompVideos).attr('href', String.format("/Competition/{0}/Videos.aspx", a.CompNameEnc))
                    .attr('title', String.format("Videos from {0}", a.CompName));
                ClientVisible(lnkCompVideos, a.CompTotalVideos > 0);

                $(litComp).text(a.CompName);
                $(litCompPlace).text(a.CompPlace);
                $(litCompStarted).text(a.CompStarted);

                if (IsClientVisible(liEvent)) {
                    //            var evn = CompController.GetEventInfo(photo.Event.Id);
                    if (a.EventId > 0) {
                        $(litEvent).text(a.EventName);
                        $(lnkEventPhotos).attr('href', String.format("/Competition/{0}/Photos.aspx", a.EventNameEnc))
                            .attr('title', String.format("More photos from {0}, {1}", a.CompName, a.EventName));
                        $(lnkEventResults).attr('href', String.format("/Competition/{0}/Results.aspx", a.EventNameEnc))
                            .attr('title', String.format("Results from {0}, {1}", a.CompName, a.EventName));

                        ClientVisible(lnkBreadcrumbEvent, EventId > 0);
                        if (EventId > 0) {
                            $(lnkBreadcrumbEvent).text(a.EventName)
                                .attr('href', String.format(C_GALLERYEVENTLINK, a.GalleryNameEnc, a.EventNameEnc));
                        }
                    }
                }

                var CompId = a.CompId;
                ClientVisible(lnkBreadcrumbComp, CompId > 0);
                if (a.CompId > 0) {
                    $(lnkBreadcrumbComp).text(a.CompName)
                        .attr('href', String.format(C_GALLERYEVENTLINK, a.GalleryNameEnc, a.CompNameEnc));
                }


                ClientVisible(lblPhotoNoDesc, a.CoupleName === '');
                ClientVisible(lblPhotoDesc, a.CoupleName !== '' && CompId === 0);
                ClientVisible(lblPhotoDescAtComp, a.CoupleName !== '' && CompId > 0);
                if (!a.CoupleName) {
                    $(pnFull).attr('title', $(lblPhotoNoDesc).text());
                } else {
                    if (CompId > 0) {
                        $(lblPhotoDescAtComp).html($(lblPhotoDescAtComp).html()); // magic for IE <9
                        $(lblPhotoDescAtComp).find('p0').text(a.CoupleName);
                        $(lblPhotoDescAtComp).find('p1').text(a.CompName);
                        $(pnFull).attr('title', $(lblPhotoDescAtComp).text());
                    }
                    else if (CompId === 0) {
                        $(lblPhotoDesc).html($(lblPhotoDesc).html()); // magic for IE <9
                        $(lblPhotoDesc).find('p0').text(a.CoupleName);
                        $(pnFull).attr('title', a.CoupleName);
                    }
                }
            }

            var products = a.Products;
            //    ddlProducts.DataSource = products;
            //    ddlProducts.DataBind();

            ClientVisible(pnSale, products.length > 0);

            var GalleryId = a.GalleryId;
            ClientVisible(lnkBreadcrumbGallery, GalleryId > 0);
            if (GalleryId > 0) {
                $(lnkBreadcrumbGallery).text(a.GalleryName);
                if (GalleryId !== 11) {
                    $(lnkBreadcrumbGallery).attr('href', String.format("/Gallery/{0}_{1}/Photos.aspx", a.GalleryName, a.GalleryId));
                }
            }

            if (IsClientVisible(pnSale)) {
                $(ddlProducts).find('option').remove();

                for (i = 0; i < a.Products.length; i++) {
                    var p = a.Products[i];
                    var p1 = htmlEncode(p.ProductName);
                    var op = $("<option></option>").attr('value', p.Value);
                    if (p.IsDefault) { op.attr('selected', 'selected'); }
                    op.text(p.Text);
                    $(ddlProducts).append(op);
                }
            }

            var sponsors = a.Sponsors;
            ClientVisible(pnSponsors, sponsors && sponsors.length > 0);
            var sp = $(pnSponsors + " ul");
            sp.html('');
            if (IsClientVisible(pnSponsors)) {
                for (i = 0; i < sponsors.length; i++) {
                    var s = sponsors[i];
                    sp.append(String.format('<li>{0} by {1}<br><a href="/SponsorPage.aspx?Id={3}"><img src="/Pictures/Sponsors/{2}" /></a></li>', s.Message, s.Name, s.ImageName, s.SponsorId));
                }
            }

            if (CoupleId > 0) {
                var cpl = a.Couple;
                if (cpl && cpl.LineAdvertId > 0) {
                    $(litOwnTextNextLine).show();
                    $(lnkOwnText).show();
                    lnkOwnText.TId = String.format("cLinkAdvert{0}", cpl.LineAdvertId);
                    $(lnkOwnText).text(cpl.LineAdvertText);
                    $(lnkOwnText).attr('href', cpl.LineAdvertURL);
                }
                else {
                    $(litOwnTextNextLine).show();
                    $(lnkOwnText).show();
                }
            }

            setExtraButtons(a);
        }
        catch(err) {
            locked = false;
            $('.desc').stop(true, true).show();
            txt = "There was an error on this page.\n\n";
            txt += "Error description: " + err.description + "\n\n";
            txt += "Click OK to continue.\n\n";
            alert(txt);
        }
        locked = false;


        //    return photo;
    }


    $(function() {
        // define full photo dialog
        $(pnFull).dialog({ modal: true, width: 'auto', zIndex: 15000, autoOpen: false });
        $(imgFull).unbind('click').click(function() { $(pnFull).dialog('close'); });
        $(imgPhoto).unbind('click').click(function() {
            $(pnFull).dialog('option', 'dialogClass', 'dsInfoDialog').dialog('open').dialog('option', 'title', $(pnFull).attr('title'));
        });
        // Rating component
    }
);

    var hovHtml = '<div id=hovering style="position:absolute;display:none;cursor:pointer" class="hovering" ><a><img id="imgPhotoH"/></a><br />Ref#<span></span><img src="/images/icons/zoom_in.png"></div>';
    function onMouseEnter(e) {
        if ($('#hovering').length === 0) {
            $(hovHtml).appendTo($('form'));
        }
        var pos = $(this).offset(); pos.left -= 20; pos.top -= 20;
        var pId = $(this).find('a').attr('pId');

        $("#hovering").show();

        var isrc = $('#hovering').unbind('click').click(function() { $(this).hide(); moveCurrent(this); })
            .css(pos)
            .find('#imgPhotoH').attr('src', $(this).find('img').attr('src')).end()
            .find('a').attr('pId', pId).end().find('span').html(pId);
    }
    function onMouseLeave(e) {

    }

    var lastPos;
    var pressed = false;
    function getPos(e) {
        return { x: e.pageX, y: e.pageY };
    }
    $(document).ready(function() {

        $(hovHtml).mouseleave(function() { $("#hovering").hide(); }).appendTo($('form'));
        $('.mainphoto').hide();
        $('.mainphoto').mousedown(function(e) {
            lastPos = getPos(e);
            pressed = true;
            return true;
        }).data("isvisible", false).appendTo($('form'));
        $('#closebutton').unbind('click').click(function() { $('.mainphoto').hide().data("isvisible", false); });
        $('.photo').unbind('mouseenter').mouseenter(onMouseEnter);
    });
    $(document).mousemove(function(e) {
        if (!pressed) { return; }
        var p = getPos(e);
        var pos = $('.mainphoto').position();
        if (lastPos) {
            pos.left += p.x - lastPos.x;
            pos.top += p.y - lastPos.y;
            $('.mainphoto').css(pos);
        }
        lastPos = p;
        return false;
    }).mouseup(function(e) {
        lastPos = getPos(e);
        pressed = false;
    }).mouseleave(function(e) {
        pressed = false;
    });

