/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$(document).ready(function(){

    if ($('[_uploadType]').size() == 0) return;

    var PictureWrapper = {
        AddNewPicture : function(data){ // the user uploaded a new pic
            _container = $(".container", $("#widget-picture"));

            if (data != null){
                $(".tips", $("#widget-picture")).hide().next().show();
                img = data.new_picture_big;
                id = data.new_picture_id;
                tn = data.new_picture_small;
                $("#widget-picture div.selected").removeClass("selected");
                $("#widget-picture div[_isprofilephoto=1]").attr("_isprofilephoto","0");
                $("<div class=\"photoContainer selected\" _isprofilephoto=\"1\" _photoid=\"" + id + "\"><a href=\"#\" _photoid=\"" + id + "\" _zoom=\""+ img +"\"><img _photoid=\"" + id + "\" _tag=\"photo_preview\" class=\"photo selected\" border=\"0\" src=\""+ tn +"\"></a></div>").prependTo(_container.children(".inner")).click(function(){
                    $("a[_class=currentPhoto] img", $("#widget-picture")).attr("src", $(this).attr("_zoom"));

                    $("#widget-picture div.selected").removeClass("selected");
                    $(this).addClass("selected");

                    Popmenu.Attach($("img:first", $(this)));
                    $(this).blur();
                    return false;
                });
                // _container.scrollLeft(0);
                _container.animate({
                    scrollLeft : 0
                }, 200, "linear");
            }
            
            numOfPics = $("img", _container).size();
            $("a[_class=currentPhoto]").children("img:first").attr("src", img);
            $(".inner", _container).width(60*numOfPics);
            while($(".inner", _container).height()>100) $(".inner", _container).width($(".inner", _container).width()+10);        
        },
        AddNewEmoticon : function(data){
            _container = $(".inner", $("#widget-emoticon"));
            preview = $("<img class=\"emoticon\" _tag=\"emoticon_preview\" _hash=\""+ data.new_emoticon_hash +"\" _emoticonid=\"" + data.new_emoticon_id + "\" src=\""+ data.new_emoticon_preview+ "\" />").appendTo(_container);
            cache = $("<img src=\"" + data.new_emoticon + "\" />").hide().insertAfter(preview);
            preview.hover(function(){
                $(this).attr("_src", $(this).attr("src")).attr("src", $(this).next("img:hidden").attr("src"));
            }, function(){
                $(this).attr("src", $(this).attr("_src"));
            });
            Emoticon.InitPreview();
            Emoticon.ManageDisplay();
        },
        AddNewProductPicture : function(data){ // the user uploaded a new product pic
            _container = $(".container", $("#widget-ibuddy"));
            img = data.new_picture_big;
            tn = data.new_picture_small;
            id = data.productid;
            $(".container a[_isProfile=1][_productid="+id+"]", $("#widget-ibuddy")).attr("_isProfile","0");
            $("<a href=\"#\" _zoom=\""+ img +"\" _productid=\""+ id + "\" _isProfile=\"1\"><img class=\"photo\" border=\"0\" src=\""+ tn +"\"></a>").appendTo(_container.children(".inner")).click(function(){
                $("a[_class=currentPhoto] img", $("#widget-ibuddy")).attr("src", $(this).attr("_zoom"));
                $(this).blur();
                return false;
            });
            $(".ibuddy-photo img","#widget-ibuddy").attr("src",img);
            numOfPics = $("img", _container).size();
            $(".inner", _container).width(70*numOfPics);
			$("div.tips","#widget-ibuddy").hide();
            $("div.photo-select","#widget-ibuddy").show();
            //while($(".inner", _container).height()>100) $(".inner", _container).width($(".inner", _container).width()+10);
        // alert($(".inner img:last", _container).attr("src"));
        }
    }

    jQuery.uploader.swfURL = 'scripts/lib/jQuery.uploader/jQuery.uploader.swf';
    // jQuery.uploader.allowedDomain = 'gen-pc:8888';
    jQuery.uploader.backendScript = '/index.php?r=user/uploadImage';
    jQuery('[_uploadType]').height(jQuery('#btnBrowse').height());
    jQuery('[_uploadType]').width(jQuery('#btnBrowse').width()+10);

    $("[_uploadType]").css({
        cursor : "pointer"
    });

    var oUpload = [];

    $.each($("[_uploadType]"), function(idx, obj){

        // console.info(obj);
        $(obj).attr("_idx", idx);

        oUpload[idx] = $(obj).uploader({
            swfURL : jQuery.uploader.swfURL,
            backendScript : $(obj).attr("_backend"),
            allowedDomain : jQuery.uploader.allowedDomain,
            movieID : 'uploader' + idx
        });

        jQuery.extend(oUpload[idx].events, {
            uploaderReady : function(){

                // console.info("ready");

                this.setFilters([
                {
                    description : 'Images (*.JPG, *.BMP, *.PNG, *.GIF)',
                    extensions: '*.jpg; *.jpeg; *.bmp; *.png; *.gif'
                },
//                {
//                    description : 'Icons (*.GIF)',
//                    extensions: '*.gif'
//                },
                {
                    description : 'All Files (*.*)',
                    extensions: '*.*'
                }
                ]);

                this.setMaxFileSize(2000000);
                this.setMaxQueueCount(1);
                this.idx = idx;

                firer = $("#"+this._settings.containerID);
                btn = firer.parent().children("button");
				if (btn.attr("_uploadLimit")) this.setMaxFileSize(btn.attr("_uploadLimit"));
                // btn.parent("td:last").attr("width", btn.width()).css("width", btn.width());
                // console.info(btn.closest("table").width());
                progressbar = eval(firer.attr("_progressbar"));
                progressbar.css("width", btn.closest("table").width() - btn.width() - 25);
                progressbar.parent("td").css("width", btn.closest("table").width() - btn.width() - 25);
            },
        
            rollOver : function(){
                firer = $("#"+this._settings.containerID);
                firer.parent().children("button").addClass("ui-state-hover");
            },
            rollOut : function(){
                firer = $("#"+this._settings.containerID);
                firer.parent().children("button").removeClass("ui-state-hover");
            },
            fileUploadStarted : function(args){
                firer = $("#"+this._settings.containerID);
                firer.parent().children("button").addClass("ui-state-disabled");
                progressbar = eval(firer.attr("_progressbar"));
                progressbar.progressbar({
                    value: 1
                });
            },
            fileUploadProgress : function(args){
                firer = $("#"+this._settings.containerID);
                progressbar = eval(firer.attr("_progressbar"));
                progressbar.progressbar('value', args.fileProgress.progress);
            },
            fileAdded: function(args) {
                firer = $("#"+this._settings.containerID);
                progressbar = eval(firer.attr("_progressbar"));
                param = {
                    user_id : firer.attr("_userid"),
                    private_key : firer.attr("_privatekey"),
                    upload_type : firer.attr("_uploadtype"),
                    product_id : firer.attr("_productid")
                }
                progressbar.fadeIn("slow", function(){
                    // console.info();
                    oUpload[firer.attr("_idx")].upload(args.fileData.id, jQuery.uploader.backendScript, "GET", param);
                    return true;
                });
            },
            fileErrorSize : function(args){
                firer = $("#"+this._settings.containerID);
                btn = firer.parent().children("button");
                uploadLimit = (btn.attr("_uploadLimit"))? "200k" : "2m";
                alert("The uploaded file exceeds the 2mb limit.".replace(/(2m|2\smb)/i, uploadLimit));
            },
            fileUploadCompleted: function(args) {
                this.remove(args.fileData.id);
            },
            fileUploadError: function(args) {
                response = args.fileProgress.status;
                response = parseInt(response.match(/\d+/));
                console.error(response);
            
                switch(response){
                    case 507:
                        // valid file format, but not allowed in server
                        $("<div>Invalid file format!<br />The uploaded file is not an image file,  please retry another one.</div>").dialog({
                            title: args.fileProgress.status,
                            modal: true,
                            resizable: false,
                            buttons: {
                                'Close' : function(){
                                    $(this).dialog("destroy");
                                    $(this).remove();
                                }
                            }
                        });
                        break;
                    case 506:
                        // invalid file format
                        $("<div>Invalid file format!<br />The uploaded file is not an image file,  please retry another one.</div>").dialog({
                            title: args.fileProgress.status,
                            modal: true,
                            resizable: false,
                            buttons: {
                                'Close' : function(){
                                    $(this).dialog("destroy");
                                    $(this).remove();
                                }
                            }
                        });
                        break;
                    default:
                        break;
                }
                this.remove(args.fileData.id);
                firer = $("#"+this._settings.containerID);
                progressbar = eval(firer.attr("_progressbar"));
                progressbar.fadeOut(2000, function(){
                    $(this).progressbar('destroy');
                    firer.parent().children("button").removeClass("ui-state-disabled");
                });
            },
            fileUploadServerData: function(reply) {
                // console.info('done');
                // console.info(reply);
                firer = $("#"+this._settings.containerID);
                progressbar = eval(firer.attr("_progressbar"));
                progressbar.fadeOut(2000, function(){
                    $(this).progressbar('destroy');
                    firer.parent().children("button").removeClass("ui-state-disabled");
                });
                // remove progressbar
                // console.info(firer);
                result = JSON.parse(reply.serverData);

                if (firer.attr("_uploadType") == 1){
                    // Photos
                    switch(result.error_code){
                        case 1 :
                            // upload done with no error
                            // console.info(result.data);
                            PictureWrapper.AddNewPicture(result.data);
                            break;
                        default: break;
                    }
                } else if (firer.attr("_uploadType") == 2){
                    // Emoticons
                    switch(result.error_code){
                        case 1 :
                            // upload done with no error
                            // PictureWrapper.AddNewPicture(result.data);
                            PictureWrapper.AddNewEmoticon(result.data);
                            break;
                        default: break;
                    }
                }else if (firer.attr("_uploadType") == 3){
                    // Emoticons
                    switch(result.error_code){
                        case 1 :
                            // upload done with no error
                            PictureWrapper.AddNewProductPicture(result.data);
                            break;
                        default: break;
                    }
                }
            }

        });
    });

})