var pwGallery = {
    videoPage : '',
    galleryPage : '',
    galleryListingPage : '',
    pageHandle : '',
    galleryPageTitle : '',
    galleryPageDesc : '',
    videoListPageTitle : '',
    videoListPageDesc : '',
    viewGalleryLabel : '',
    uploadGalleryLabel : '',
    videoPageTitle : '',
    videoPageDesc : '',
    maxVideos : 0,
    byline : '',
    uploadLabel : '',
    uploadTitleLabel : '',
    uploadDescLabel : '',
    pagingNextLabel : 'Next', 
    pagingPrevLabel : 'Prev',
    publicGalleryLabel : 'Public Galleries',
    maxGalleries : 0,
    pageIndex : 1,
    noOfIndicesGallery : 1,
    noOfIndicesVideo : 1,    
    show : function(x) {
        pwGallery.divsToToggle.each(function(y) {
            if (x === y)
                $(y).show();
            else
                $(y).hide();
        });
    },

    crumbs :
            [
                {
                    title : 'public galleries',
                    onclick: "pwGallery.show('galleries');pwGallery.goToCrumb(0, pwGallery.crumbs[0]);"
                }
            ],

    crumbHtml : function (x, index) {
      var div;
        if (index < pwGallery.crumbs.length - 1) {            
              div= new Element('li').insert(new Element('a', {href: x.href + ".html"}).insert(x.title));
              div.insert('&nbsp;>&nbsp;');
              return(div);
               
            
        } else {
            return new Element('span').insert(x.title);
        }
    },
    showCrumbs : function() {
        $('videocrumbs').update("");
        var div = new Element('ul', {});
        div.setAttribute((document.all ? 'className' : 'class'), "breadcrumb");
       pwGallery.crumbs[0].title = pwGallery.publicGalleryLabel;
        pwGallery.crumbs.each(function(x, index) {
            div.insert(pwGallery.crumbHtml(x, index)).insert("&nbsp;&nbsp;");
        });
       
      $('videocrumbs').insert(div);
    },
    goToCrumb : function(level, crumbData) {
        pwGallery.crumbs.splice(level, pwGallery.crumbs.length - level, crumbData);
        pwGallery.showCrumbs();
    },

    uploadFormCounter : 0,
    uploadVideo : function () {
       
        new iframe(
                $('uploadVideoForm'),
        {onComplete: function(request) {

            pwPluck.runRequest(function() { location.reload(); }, [new UpdateVideoAction(new VideoKey(request.responseText), $('uploadVideoTitle').value, $('uploadVideoDescription').value)]);

        } },
                pwGallery.uploadFormCounter++);
    },

    div : function(classname) {
        return new Element('div', {'class': classname});
    },
    playVideoForKeyString : function(keyString, galleryTitle, galleryKey) {
        var callback = function(responseBatch) { pwGallery.playVideo(responseBatch.Responses[0].Video, galleryTitle, galleryKey); };
        pwPluck.runRequest(callback, [new VideoKey(keyString)]);
    },

    playVideo : function(video, galleryTitle, galleryKeyString) {
        document.title = video.Title; 
        var videoWidth = document.getElementById('leftColumn').offsetWidth;       
        if ((videoWidth != null) && (typeof(videoWidth) != "undefined" ) ) {          
          videoWidth = videoWidth-10;          
        } else {
          videoWidth = 450;  
        }    
        if (pwGallery.videoPageTitle != '') {
            $('videoplayer').insert(pwGallery.div('pluckvideo-video-pagetitle').insert(pwGallery.videoPageTitle));
        }
        if (pwGallery.videoPageDesc != '') {
            $('videoplayer').insert(pwGallery.div('pluckvideo-video-pagedesc').insert(pwGallery.videoPageDesc));
        }
        var videoPlayEmbed = new Element('embed', { width: videoWidth,height:'375',          
            flashvars:'&file=' + video.VideoUrl + '&width=' + videoWidth + '&height=375&autostart=true',
            allowfullscreen: 'true',
            src: pwSitelifePrefix + '/ver1.0/content/swf/mediaplayer.swf'
        });
        $('videoplayer').insert(pwGallery.div('pluckvideo-video-title').insert(video.Title));
        if (pwGallery.byline == "" || pwGallery.byline == null) {
            $('videoplayer').insert(pwGallery.div('pluckvideo-video-author').insert(video.Author.DisplayName));
          } else {
           $('videoplayer').insert(pwGallery.div('pluckvideo-video-author').insert(pwGallery.byline).insert('&nbsp;').insert(video.Author.DisplayName));
          }
        $('videoplayer').insert(new Element('br'));
        $('videoplayer').insert(pwGallery.div('pluckvideo-video-embed').insert(videoPlayEmbed));
        $('videoplayer').insert(new Element('br'));
        if (video.Description != '') {
          $('videoplayer').insert(pwGallery.div('pluckvideo-video-desc').insert(video.Description));
        }        
        $('videoplayer').insert("");
        pwGallery.show('videoplayer');
        if (galleryTitle && galleryKeyString) {
            pwGallery.goToCrumb(
                    1,
            {title: galleryTitle,
                onclick: "pwGallery.renderGallery('" + galleryKeyString + "');",
                href: pwGallery.galleryPage + ".gallery." + galleryKeyString
            }
                    );
        }
        pwGallery.goToCrumb(2, {title: video.Title, onclick: "", href:""});
        showComments(video.VideoKey.Key);
    },
    log : function(value) {
//        if (console && console.info) {
//            console.info(value);
//        }
    },
    pagingVideos : function(totVideos,NoOfVideos,galleryKey,pageIndex, currDiv) {
        var lastPage = Math.ceil(totVideos/pwGallery.maxVideos);
         if (pageIndex > lastPage) {
              pageIndex = lastPage;
         } else if (pageIndex <= 0) {
           pageIndex = 1;
         }
        var pagingArray = pwGallery.pagingHelper(pageIndex,lastPage,pwGallery.noOfIndicesVideo);
        if ( pagingArray[3]>0 ) {
           var galleryLnk = new Element('a',
                     {href:pwGallery.galleryPage + ".gallery." + galleryKey + "." + pagingArray[3] +".html",
                      title:'prev'}).update(pwGallery.pagingPrevLabel); 
                  currDiv.insert(galleryLnk);
        } else {
                  currDiv.insert(pwGallery.pagingPrevLabel);
        }  
        currDiv.insert('&nbsp;&nbsp;');          
        for(var i=pagingArray[0];i<=pagingArray[1];i++)
        {
                  if(i==pageIndex)
                  {                 
                      currDiv.insert(i);
                      currDiv.insert('&nbsp;');
                  } else {
                    var galleryLnk = new Element('a',
                     {href:pwGallery.galleryPage + ".gallery." + galleryKey + "." + i +".html",
                      title:i}).update(i); 
                     currDiv.insert(galleryLnk);
                     currDiv.insert('&nbsp;');  
                  }
         } 
         currDiv.insert('&nbsp;');
         if ( pagingArray[2]!=0 ) {             
                  var galleryLnk = new Element('a',
                     {href:pwGallery.galleryPage + ".gallery." + galleryKey + "." + pagingArray[2] +".html",
                      title:'next'}).update(pwGallery.pagingNextLabel); 
                  currDiv.insert(galleryLnk);
         } else {
                 currDiv.insert(pwGallery.pagingNextLabel);
         }

     },
   pagingHelper : function( pageIndex, lastPage,noOfIndices){
       var pagIndex = parseInt(pageIndex);
       var noOfIndicesInt = parseInt(noOfIndices);
       var currIndex = 1;
       var endCurrIndex = 1;
       var startCurrIndex = 1; 
       var nextPage=1;
       var prevPage=1;     
       var lastPageIndex = 0;
       lastPageIndex =parseInt(lastPage);
       currIndex = pagIndex%noOfIndicesInt;      
       var intDiff = parseInt(noOfIndicesInt) - parseInt(currIndex);
       endCurrIndex = parseInt(pagIndex) + parseInt(intDiff) ;        
       if (currIndex == 0) {
         startCurrIndex = parseInt(pagIndex) - parseInt(noOfIndicesInt) + 1;
         endCurrIndex = parseInt(pagIndex) * 1;
       }               
       if (currIndex > 0)
         startCurrIndex = parseInt(pagIndex) - parseInt(currIndex) + 1;
        
       if (endCurrIndex > lastPageIndex )
          endCurrIndex = lastPageIndex;
       
       if (startCurrIndex == 0)
           startCurrIndex = pagIndex;     
         
            nextPage=pwGallery.getNextPageIndex(parseInt(pagIndex),parseInt(lastPageIndex));
            prevPage=pwGallery.getPrevPageIndex(parseInt(pagIndex));
            var allData=new Array();
            allData[0] = startCurrIndex;
            allData[1] = endCurrIndex; 
            allData[2] = nextPage;
            allData[3] = prevPage;
                    
            return allData;
    },
    getNextPageIndex: function(offset, totalpageindex)
        {
            var nextIndex=0;
         
            if(offset<totalpageindex)
            {
                nextIndex=++offset;
            }
            return nextIndex;
        },
     getPrevPageIndex : function( offset)
        {
            var prevIndex=0;
            
            if(offset> 1)
            {
                prevIndex=offset-1;
            }
            return prevIndex;
        },

     pagingGalleries : function(totVideos,NoOfVideos,pageIndex, currDiv) {
        var lastPage =1;
        lastPage = Math.ceil(totVideos/pwGallery.maxGalleries);
         if (pageIndex > lastPage) {
             	  pageIndex = lastPage;
         } else if (pageIndex <= 0) {
           pageIndex = 1;
         }
        var pagingArray = pwGallery.pagingHelper(pageIndex,lastPage,pwGallery.noOfIndicesGallery);
           if ( pagingArray[3]>0 ) {
             var galleryLnk = new Element('a',
                     {href:pwGallery.galleryListingPage + ".galleries."  + pagingArray[3] +".html",
                      title:'prev'}).update(pwGallery.pagingPrevLabel); 
                  currDiv.insert(galleryLnk);
           } else {
                  currDiv.insert(pwGallery.pagingPrevLabel);
           }
               currDiv.insert('&nbsp;&nbsp;');           
              for(var i=pagingArray[0];i<=pagingArray[1];i++)
              {
                  if(i==pageIndex)
                  {                 
                      currDiv.insert(i);
                      currDiv.insert('&nbsp;');
                  } else {
                    var galleryLnk = new Element('a',
                     {href:pwGallery.galleryListingPage + ".galleries."  + i +".html",
                      title:i}).update(i); 
                     currDiv.insert(galleryLnk);
                     currDiv.insert('&nbsp;');  
                  }
               }
               currDiv.insert('&nbsp;');
               if ( pagingArray[2]!=0 ) {
                var galleryLnk = new Element('a',
                     {href:pwGallery.galleryListingPage + ".galleries."  + pagingArray[2] +".html",
                      title:'next'}).update(pwGallery.pagingNextLabel); 
                  currDiv.insert(galleryLnk);
               } else {
                  currDiv.insert(pwGallery.pagingNextLabel);
               }
     },
    renderGallery : function(galleryKeyString, pageIndex) {
        pwGallery.log("entering renderGallery with " + galleryKeyString);
        var callback = function (responseBatch) {
         if (pwGallery.checkUndefined(responseBatch.Responses) ) {
            var gallery = responseBatch.Responses[0].Gallery;            
            var galleryDiv = pwGallery.div('currentGallery');
            pwGallery.goToCrumb(
                    1,
            {title: gallery.Title,
                onclick: "pwGallery.renderGallery('" + galleryKeyString + "');",
                href: pwGallery.galleryPage + ".gallery." + galleryKeyString
            }
                    );

            galleryDiv.insert(new Element('br'));           
           if (pwGallery.videoListPageTitle != '') {
             galleryDiv.insert(pwGallery.div('pluckvideo-videolisting-pagetitle').insert(pwGallery.videoListPageTitle));
           }
           if (pwGallery.videoListPageDesc != '') {
              galleryDiv.insert(pwGallery.div('pluckvideo-videolisting-pageDesc').insert(pwGallery.videoListPageDesc));
           }
            pwGallery.show("currentGallery");
            $('currentGallery').update(galleryDiv);
            var videoPage = responseBatch.Responses[1].VideoPage;
            var videos = responseBatch.Responses[1].VideoPage.Videos;
            var i = 0;
            var tableStruct = new Element('table', {'class':'pluckvideo-videolisting-tablestruct' }); 
            var tablebod = new Element("tbody");
            var tableTr;

            for (var j = 0; j+3 < videos.length; j=j+3){ 
              pwGallery.listVideo(videos, gallery.Title, galleryKeyString, j, j+3, tablebod);            
            }
            if ((videos.length > 0) && (videos.length - j > 0)) {
              pwGallery.listVideo(videos, gallery.Title, galleryKeyString, j,videos.length, tablebod);
            }
            tableStruct.insert(tablebod);
            galleryDiv.insert(tableStruct);
            if ((videoPage.NumberOfVideos > 0 ) && (videos.length > 0)) {
              var currDiv =  pwGallery.div('pluckvideo-videolisting-pagination');
              pwGallery.pagingVideos(videoPage.NumberOfVideos,videos.length,gallery.GalleryKey.Key,pageIndex,currDiv);
              galleryDiv.insert(currDiv);
            }
            currDiv =  pwGallery.div('pluckvideo-upload-formdiv');
            pwGallery.uploadFormCreation(galleryKeyString,currDiv);
            galleryDiv.insert(currDiv);    
          }
        };
        var galleryKey = new GalleryKey(galleryKeyString);        
        var videoPage = new VideoPage(galleryKey, pwGallery.maxVideos, pageIndex);
        pwPluck.runRequest(callback, [galleryKey, videoPage]);
        
    },
    uploadFormCreation : function(galleryKeyString, currDiv) {
      currDiv.insert(pwGallery.div('pluckvideo-upload-title').insert(pwGallery.uploadLabel ));
        var tableStruct = new Element('table', {'class':'pluckvideo-upload-tablestruct' }); 
        var tablebod = new Element("tbody"); 
        var tableTr = new Element('tr', {'class':'pluckvideo-upload-tabletr' });
        var tableTd =  new Element('td', {'class':'pluckvideo-upload-tabletd' });
        var dataDiv = pwGallery.div('pluckvideo-upload-newTitle');
        dataDiv.insert(pwGallery.uploadTitleLabel);      
        tableTr.insert(tableTd.insert(dataDiv));
        dataDiv = pwGallery.div('pluckvideo-upload-Titletext');
        dataDiv.insert(new Element('input', {type : 'text', name: 'uploadVideoTitle', id: 'uploadVideoTitle'}));
        tableTr.insert(new Element('td', {'class':'pluckvideo-upload-tabletd' }).insert( dataDiv));
        tablebod.insert(tableTr);         
        tableTr = new Element('tr', {'class':'pluckvideo-upload-tabletr' });
        dataDiv = pwGallery.div('pluckvideo-upload-desclabel');
        dataDiv.insert(pwGallery.uploadDescLabel);
        tableTr.insert(new Element('td', {'class':'pluckvideo-upload-tabletd' }).insert( dataDiv));
        dataDiv = pwGallery.div('pluckvideo-upload-desctext');
        dataDiv.insert(new Element('input', {type : 'textarea', name: 'uploadVideoDescription', id: 'uploadVideoDescription'}));
        tableTr.insert(new Element('td', {'class':'pluckvideo-upload-tabletd' }).insert( dataDiv));
        tablebod.insert(tableTr);
        tableStruct.insert(tablebod); 
        currDiv.insert(tableStruct); 
         
        var videoUploadForm = new Element('form', {method: 'post',
                enctype : "multipart/form-data",
                id : "uploadVideoForm",
                action : pwUser.community.sitelifeVideoUploadURL});
        videoUploadForm.setAttribute('encoding', 'multipart/form-data');
            videoUploadForm.insert(new Element('input', {type : 'hidden',
                value : galleryKeyString ,
                id: 'galleryKey',
                name: 'galleryKey'}));
            
            videoUploadForm.insert(new Element('input', {type : 'file', name : 'Filedata', id : 'videoUpload'}));
            var button;
            button = new Element('button', {type : 'submit', id : 'btnUpload'}).insert('Start Upload.');
            button.onclick = pwGallery.uploadVideo; 
            videoUploadForm.insert(button);            
            currDiv.insert(videoUploadForm);
    },
    uploadFormVideo : function(galleryKeyString, gallTitle) {
        pwGallery.goToCrumb(
                    1,
            {title: gallTitle,
                onclick: "pwGallery.renderGallery('" + galleryKeyString + "');",
                href: pwGallery.galleryPage + ".gallery." + galleryKeyString
            }
                    );
        var currentGallery = pwGallery.div('pluckvideo-upload-form');
        pwGallery.uploadFormCreation(galleryKeyString,currentGallery); 
        $('uploadVideo').update(currentGallery); 
        pwGallery.show("currentGallery");

    },
    listVideo : function(videos, galleryTitle, galleryKeyString, startIndex, endIndex, tablebod) {
       var stIndex = (startIndex * 1) + 3;
        var div;
        var tableTr = new Element('tr', {'class':'pluckvideo-videolisting-titletr' });
        var tableTd;
        for (var i = startIndex; i < stIndex; i++){ 
          div = pwGallery.div('pluckvideo-videolisting-videotitle');
          tableTd =  new Element('td', {'class':'pluckvideo-videolisting-titletd' });
          if (i < endIndex)
            tableTd.insert(div.insert(videos[i].Title)); 
          else
            tableTd.insert(div);
         tableTr.insert(tableTd);
 
        }     
       tablebod.insert(tableTr);
       tableTr = new Element('tr', {'class':'pluckvideo-videolisting-videotr' }); 
       var href;     
       for (var i = startIndex; i < stIndex; i++){ 
         tableTd =  new Element('td', {'class':'pluckvideo-videolisting-videotd' });
         if (i < endIndex) {
          href = pwGallery.videoPage + ".video." + videos[i].VideoKey.Key + "." + galleryTitle + "." + galleryKeyString + ".html";
          div = new Element('div', {'class':'pluckvideo-videolisting-video', id:'videolisting' + videos[i].VideoKey.Key});
          div.insert(new Element('a', {href: href})
             .insert(new Element('img', {src: videos[i].VideoThumbnail, height:60, width:96,  alt:videos[i].Title})) );
          }
         else {           
           div = new Element('div', {'class':'pluckvideo-videolisting-video'});
         } 
          tableTd.insert(div);
          tableTr.insert(tableTd); 
        }
       tablebod.insert(tableTr);
       tableTr = new Element('tr', {'class':'pluckvideo-videolisting-authortr' });      
       for (var i = startIndex; i < stIndex; i++){ 
          div = pwGallery.div('pluckvideo-videolisting-author');
          tableTd =  new Element('td', {'class':'pluckvideo-videolisting-authortd' });
         if (i < endIndex) {
        	 if (pwGallery.byline == "" || pwGallery.byline == null) {
                 tableTd.insert(div.insert(videos[i].Author.DisplayName));
              } else {          
                 tableTd.insert(div.insert(pwGallery.byline).insert('&nbsp;').insert(videos[i].Author.DisplayName)); 
              }	           
         }
         else {
          tableTd.insert(div);
         }
          tableTr.insert(tableTd); 
        }  
      tablebod.insert(tableTr);   
    },

    loadPublicGalleries : function(noOfGalleries,pageIndex) {
    	pwGallery.maxGalleries = noOfGalleries;
        pwGallery.pageIndex = pageIndex;
        pwPluck.runRequest(pwGallery.renderGalleries, [new PublicGalleryPage(noOfGalleries, pageIndex, new MediaType("Video"))]);
    },
    loadUserGalleries : function(userKey) {
        pwPluck.runRequest(pwGallery.renderGalleries, [userKey]);
    },
    checkUndefined : function(responseStr) {
        if (responseStr == null && responseStr !== null ) {
          return false;
        } else {
          return true;
        }
      },
    renderGalleries : function(responseBatch) {
      if (pwGallery.checkUndefined(responseBatch.Responses) ) {	  
        var galleries = responseBatch.Responses[0].PublicGalleryPage;
        if (!galleries) galleries = responseBatch.Responses[0].UserGalleryPage;
        if (!galleries) galleries = {Galleries:responseBatch.Responses};

        var galleryListDiv = new Element('div');
        if (pwGallery.galleryPageTitle != '') {
          galleryListDiv.insert(pwGallery.div('pluckvideo-gallerylisting-pagetitle').insert(pwGallery.galleryPageTitle));
        }
        if (pwGallery.galleryPageDesc != '') {
          galleryListDiv.insert(pwGallery.div('pluckvideo-gallerylisting-pageDesc').insert(pwGallery.galleryPageDesc));
        }
        var tableStruct = new Element('table', {'class':'pluckvideo-gallerylisting-tablestruct' }); 
        var tablebod = new Element("tbody");
        for (var i = 0; i < galleries.Galleries.length; i++) {
            var gallery = galleries.Galleries[i].Gallery;
            if (!gallery) gallery = galleries.Galleries[i];            
            var tableTr = new Element('tr', {'class':'pluckvideo-gallerylisting-tabletr' });
            var tableTd =  new Element('td', {'class':'pluckvideo-gallerylisting-imagetd' });
            var imageDiv = pwGallery.div('pluckvideo-gallerylisting-thumbnail');
            if (gallery.GalleryPromo.PhotoKey) {
                var image = new Element('img', {src: gallery.GalleryPromo.Image.Small, alt:gallery.Title});
                imageDiv.insert(image);
            }
            var attrs = { href: pwGallery.galleryPage + ".gallery." + gallery.GalleryKey.Key + ".html" };
            tableTd.insert(imageDiv);
            tableTr.insert(tableTd); 
            tableTd =  new Element('td', {'class':'pluckvideo-gallerylisting-infotd' });
            var videoLink = pwGallery.div('pluckvideo-gallerylisting-link').insert(
                    new Element('a', attrs).update(gallery.Title));
            var descDiv = pwGallery.div('pluckvideo-gallerylisting-desc').insert(gallery.Description);
            var galleryLnk = pwGallery.div('pluckvideo-gallerylisting-link').insert(
                    new Element('a', attrs).update(pwGallery.viewGalleryLabel));
            var uploadLnk = pwGallery.div('pluckvideo-gallerylisting-uploadlnk').insert(new Element('a',
                    {href:pwGallery.pageHandle +  gallery.GalleryKey.Key + '.' +  gallery.Title + '.html' ,                         
                        title:pwGallery.uploadGalleryLabel}).update(pwGallery.uploadGalleryLabel));

            tableTd.insert(videoLink);
            tableTd.insert(descDiv);
            tableTd.insert(galleryLnk);
            tableTd.insert(uploadLnk);
            tableTr.insert(tableTd);  
            tablebod.insert(tableTr);           
        }
        tableStruct.insert(tablebod);        
        galleryListDiv.insert(tableStruct);
        if ((galleries.NumberOfGalleries  > 0 ) && (galleries.Galleries.length > 0)) {
            var currDiv =  pwGallery.div('pluckvideo-galleries-pagination');
            pwGallery.pagingGalleries(galleries.NumberOfGalleries ,galleries.Galleries.length,pwGallery.pageIndex,currDiv);
            galleryListDiv.insert(currDiv);
        }
        $('galleries').update(galleryListDiv);
      }
    }   
};


