/*
	Copyright Robert Nyman, http://www.robertnyman.com
	Free to use if this text is included

	Modified for JPG.
*/

JPGMAG.addPhotoWidget={
    current:null,
    get_current:function(el){
        /**
         * look for an item with and id that starts with 'theme__'
         * set the current to the numeric portion of the id --> id.split('__')[1]
         */
         
        var JPW = JPGMAG.addPhotoWidget;
        
        //get the el's parents (divs and lis only please)
        var parentEls = $j(el).parents('li, div')
        .each(function ()
        {
            //go thru each of the parent items
            var elid = this.id;
            
            //if this is the "theme__X" box...
            if(elid && elid.indexOf('theme__') > -1)
            {
                //populate jpw.current
                JPW.current =
                {
                    'theme_box_id' : elid,
                    'theme_id': elid.split('__')[1]
                };
                
                //if there's an image in the placeholder box, get some additional info
                if($j('#' + elid + ' .placeholder img').length)
                {
                    var imgsrc = $j('#' + elid + ' .placeholder img')[0].src;
                    JPW.get_image_info(imgsrc);
                }
            }
        });
        return;
    },
    
    get_image_info: function(imgsrc){
        /**
         *  parse img.src to get photo_id, user_id, and user_key
         */
        var JPCUR = JPGMAG.addPhotoWidget.current;
        
        var image_data = imgsrc.split('/');
            image_data = image_data[(image_data.length) - 1].split('.')[0];
            image_data = image_data.split('_');
        
        JPCUR['photo_id']  = image_data[0];
        JPCUR['user_id']   = image_data[1];
        JPCUR['user_key']  = image_data[2];
    },
    
    set_image: function(imgsrc)
    {
        /**
         * put the selected image in the placeholder
         */
        //console.log('in set_image ' + imgsrc);
        var JPW   = JPGMAG.addPhotoWidget;
        var JPCUR = JPW.current;
        
        var placeholder = $j('#' + JPCUR.theme_box_id + ' .placeholder');
        
        //set the "current image"...
        JPW.get_image_info(imgsrc);
        
        //if there is no placeholder box, bail
        if(!placeholder) return false;
        
        //submit the image to the theme
        var args = {
            'theme'  : JPCUR.theme_id,
            'photo'  : JPCUR.photo_id,
            'action' : 'addfromtheme',
            'size'   :'t'
        };
        $j.post('/actions/theme3.php',args,function(d){
            do {d=d.replace(/^ |\n|\r|\t/,'');} while(d.match(/^ |\n|\r|\t/));
            if(d!=0)
            {
                //if there's an image the placeholder, clear the thumb
                if(placeholder.children().length)
                {
                    JPW.get_image_info(placeholder.children()[0].src);
                    JPW.show_thumb_in_widget(JPCUR.photo_id);
                }
            
                JPW.get_image_info(imgsrc);
                placeholder.empty().html('');
                
                // fill er up
                var img = document.createElement('img');
                img.src = 'http://photos.jpgmag.com/' + [JPCUR.photo_id, JPCUR.user_id, JPCUR.user_key, 't'].join('_') +'.jpg';
                placeholder.append(img);
                
                // set to used in widget
                $j('#w_'+ JPCUR.photo_id).attr('class','used');
                
                // get image info if it's on the Themes submission widget and submit it to the theme
                // (or, clear out the image info and remove the image from the theme if there's no image)
                if($j('#' + JPCUR.theme_box_id + ' .phThemeMeta').length)
                {
                    JPGMAG.addPhotoWidget.populateMeta(d);
                }
                $j('#' + JPCUR.theme_box_id + ' .submittext').html('Change it?');
            }
            else
            {
                alert('Hmm, that didn\'t work. Can you try that again, please?');
            }
        });
    },
    
    show_thumb_in_widget:function(imgid)
    {
        /**
         * show the thumb, and allow it to be selected in the widget
         */
        $j('#w_'+imgid).attr('class','thumb');
    },
    
    enable:function(show_remove)
    {
        /**
         * show the widget
         */
        var ww = document.body.clientWidth;
        var element = JPGMAG.addPhotoWidget.activeElement;
        $j(element).addClass('active');
        
        var x = $j(element).offset().left - 6;
        var y = $j(element).offset().top + 71;
        this.enabled=true;
        
        if($j('#themewidget #loading').length)
        {
            JPGMAG.addPhotoWidget.populate(show_remove);
        }
        else if(show_remove)
        {
            $j('#themewidget').prepend('<img src="/images/removeCurrentPhoto.gif" id="removeImg" class="remove" alt="" />');
        }
        
        $j('#themewidget').show().css('top',(y)+'px');
        
        // the following bit has to appear after .show()
        // because Safari can't getStyle on a hidden object
        var widgetw = $j('#themewidget').width();
        if(x + widgetw > ww) x += ww - (x + widgetw);
        $j('#themewidget').css('left',(x)+'px');
    },
    
    disable:function()
    {
        /**
         * hide the widget
         */
        var JPW = JPGMAG.addPhotoWidget;
        JPW.activeElement = null;
        $j('#themewidget').hide();
        $j('#removeImg').remove();
    },
    
    populateMeta:function(txt)
    {
        /**
         * set the text for the theme (title, counts or default text)
         */
        $j('#' + JPGMAG.addPhotoWidget.current.theme_box_id + ' .phThemeMeta').html(txt);
    },
    
    populate:function(remove)
    {
        $j.post('/actions/theme3.php',{action:'display',sub:'populate'},function(d){
            do {d=d.replace(/^ |\n|\r|\t/,'');} while(d.match(/^ |\n|\r|\t/));
            if(d=='0'||d==''||(d.match(/^</)!='<'))
            {
                $j('#themewidget').html('<p>You haven\'t uploaded any photos yet...<br /><a href="/upload/"><strong>Upload a photo &raquo;</strong></a></p>');
            }
            else
            {
                $j('#themewidget').html(d);
                widgetImage = document.getElementById('themewidget').firstChild;
                do{widgetImage.imgid = widgetImage.id.match(/\d+/);}
                while(widgetImage = widgetImage.nextSibling);
                if(remove){
                    $j('#themewidget').prepend('<img src="/images/removeCurrentPhoto.gif" id="removeImg" class="remove" alt="" />');
                }
            }
        });
    },
    
    init:function(e)
    {
        /**
         * INITIALIZE THE IMAGE SUBMITTER WIDGET
         */
         
        // /* hack to get around inconsistent init method */
        if(e) JPGMAG.stopEvent(e);
        
        //set up some shortcuts
        var JPW = JPGMAG.addPhotoWidget;
        var JPCURR = JPW.curren
        
        //preload the 'remove' image for the widget
        var ix=new Image();
        ix.src="/images/removeCurrentPhoto.gif";
        
        //hide the widget
        JPW.disable();
        
        //set the content of the widget to the "loading bar"
        $j('#themewidget').html('<img src="/images/TransparentLoadingBar.gif" width="200" height="16" id="loading" alt="" />');
        
        //event delegation: handle clicks on body
        $j('body').bind('click', function(e)
        {
            /**
             * AHH, THE USER CLICKED...
             */
            
            //get the target of the click
            var target = e.target;
            
            //get the current (theme and img info)
            JPW.get_current(target);
            
            //if there's theme info, find the placeholder
            if(JPW.current){
                var placeholder = $j('#' + JPW.current.theme_box_id + ' .placeholder');
            }
            
            /**
             * show the widget if...
             */
            var show_remove;
            if($j(target).hasClass('placeholder') && JPW.activeElement !== target)
            {
                /* user clicked an empty placeholder (no image submitted, hence do not show the remove) */
                show_remove = false;
                JPW.disable();
                JPW.activeElement = target;
                JPW.enable(show_remove);
            }
            else if($j(target).parent().hasClass('placeholder') && JPW.activeElement !== target.parentNode)
            {
                /* user clicked a placeholder image (image submitted, hence show the remove) */
                show_remove = true;
                JPW.disable();
                JPW.activeElement = target.parentNode;
                JPW.enable(show_remove);
            }
            else if(($j(target).hasClass('trigger_submitphoto') || 
                $j(target).parent().hasClass('trigger_submitphoto') || 
                $j(target).parent().parent().hasClass('trigger_submitphoto') ) && JPW.activeElement !== placeholder)
            {
                /* user clicked a change/submit link (don't know if image submitted, so we have to figure out the show_remove value) */
                JPGMAG.stopEvent(e);
                JPW.disable();
                JPW.activeElement = placeholder;
                var show_remove = (placeholder.children().length) ? true : false; // Is there a picture in the placeholder div?
                JPW.enable(show_remove); // if so, show the Remove Current Photo image.
                return false;
            } else {
                /**
                 * other actions (handle thumb and remove clicks)
                 */
                if($j(target).hasClass('thumb'))
                {       
                    if($j('#' + JPW.current.theme_box_id + ' .placeholder img').length){
                        if(confirm('Are you sure you want to replace your current submission with a new one? The photo will lose any votes it\'s collected.')){
                            JPW.set_image(target.src);
                        }
                    }
                    else
                    {
                        JPW.set_image(target.src);
                    }
                }
                else if($j(target).hasClass('remove'))
                {
                    if(confirm('Are you sure you want to remove your current submission? The photo will lose any votes it\'s collected.'))
                    {
                        var args={theme:JPW.current.theme_id,action:'remove'};
                        $j.post('/actions/theme3.php',args,function(d){
                            do {d=d.replace(/^ |\n|\r|\t/,'');} while(d.match(/^ |\n|\r|\t/));
                            if(d!=0)
                            {
                                if(JPW.current.photo_id)
                                {
                                    JPW.show_thumb_in_widget(JPW.current.photo_id);
                                }
                                
                                placeholder.empty().html('');
                                if($j('#' + JPW.current.theme_box_id + ' .phThemeMeta').length)
                                {
                                    $j('#' + JPW.current.theme_box_id + ' .phThemeMeta').html('<p>Please make sure you\'ve read our <a href="/about/photos">guidelines</a> and <a href="/about/copyright">copyright</a> info first.</p>');
                                    $j('#' + JPW.current.theme_box_id + ' .submittext').html('');
                                }
                            }
                            else
                            {
                                alert('Hmm, that didn\'t work. Can you try that again, please?');}
                        });
                    }
                }
                
                /**
                 * hide the widget after *other* clicks, or clicks on anything that is not one of these specific cases...
                 */
                JPW.disable();
            }
        });//end body.click handler
    }
    
}; //end JPGMAG.addPhotoWidget

JPGMAG.confirmRemovalFromClosedTheme = function()
{
	var goagain = window.location.toString();
	if(confirm('Are you sure you want to remove your current submission? This theme is closed, so you will not be able to resubmit it to this theme later. The photo will also lose any votes it\'s collected.'))
    {
		var themeid = goagain.match(/\d+/);
		$j.post('/actions/theme3.php', {action:'remove',theme:themeid},function(){window.location=goagain;return false;});
	}
	return false;
}

/* auto initialize */
$j(function(){
	if($j('#themeYourPhoto').length){JPGMAG.addPhotoWidget.init();}
    $j('.trigger_people_votable_private').bind('click',JPGMAG.addPhotoWidget.init);
  	$j('#themeRemoveLink').html('<span>Remove (x)</span>').click(JPGMAG.confirmRemovalFromClosedTheme);
});