
// add permalink request 
var imageSet;
var credit;
var search;

(function($){
    $.fn.gallery = function(){
	return $(this).each(function(){
	    // function scope this golobal 
	    var that = this;
            var buy = $('#buy-link a');
            //var top;

            $('a.linkeffect',that).click(function(){
                var obj = this;
                var perm = "";
                var str = "";
                var buyLink = "";
                //top = this.rel || 0;
                $('div',that).each(function(){
                    if( obj !== $('a.linkeffect',this)[0]){
                        $(this).addClass('disabled');
                    }
                });
                str = $('img',obj).attr('src').split('/');
                str = str[str.length-1].replace('.jpg','');
                search = str;
                //location.hash = '#' + str;

                // credit 
                credit = $(this).closest('div').find('credittext');

                // buy
                buyLink = $(this).closest('div').find('.buy').text();
                buy.attr('href', buyLink);


                setCube(obj);
                return false;
            });
			
            function animateLoad(obj){
                var top = obj.rel || 0;
                $('#fullzoom').animate({ width: 978, height: 565, backgroundColor: '#fff' }, 450, function(){
                    $('#fullzoom').css({ opacity: 1 });
                    $('#current_zoom').css({ bottom: 0, display: 'block', visibility: 'hidden'});
                    $('#store_zoom').css({ display: 'block'});
                    $('#close_zoom').css({ display: 'block'});
                    $('#current_zoom').load(function() {
                        if($.browser.msie){
                            var img = new Image()
                            img.src = this.src
                            $(this).width(img.width)
                            $(this).height(img.height)
                        }
                        var ww = (this.width - 978) * -1;
                        var hh = (this.height - 577) * -1;
                        this.style.left = (parseInt(ww/2, 10))+'px';								
                        if (this.height > 565) {
                            this.style.top  = [hh, 'px'].join('');        // per visualizzare lo zoom in basso
                            //$(this).css('margin-top',[hh, 'px'].join(''))
                            $('#current_zoom').css('visibility', 'visible');
                            jQuery('#current_zoom').animate({ top: -top }, 1000, function() {
                                if(! $.browser.msie ){
                                    $('#current_zoom').draggable({
                                        drag: function(event,ui){
                                            if (ui.position.top > 0) ui.position.top = hh+'px';
                                            if (ui.position.top < hh) ui.position.top = '0px';
                                            if (ui.offset.left < ww) ui.position.left = ww + 'px';
                                            if (ui.offset.left > 0) ui.position.left = '0px';
                                        }
                                    });
                                }
                            });
                        } else { // ci sono meno di 100 px da scrollare
                            this.style.top = '0';        // per visualizzare lo zoom in alto
                            $('#current_zoom').css('visibility', 'visible');
                        }
                    });
                    $('#current_zoom').attr('src',$('#current_zoom').attr('longdesc'));
                });
                return false;
            }
			
	    function setCube(obj){
		var classY = 'top'
                var classX = 'left'
		// select bigger image
                var src = $('img',obj).attr('src');
                var imgPath = src.replace(/^(.+\/).+$/, function(url, uri) { return uri });
                if(imgPath.match(/thumb/)){
                    imgPath = imgPath.replace('thumb/','');
                }
                var imgName = src.replace(/^.+\//,'');
		// image set       
                var imgMagnified = [imgPath, "zoom/", imgName].join('');
                var imgDescription = $(obj).parent().next();
                var insStructure; 
                insStructure = $('<div/>',{ id: 'fullzoom' }).append(function(){
                    return $('<ins />',{
                            id: 'currentins'
                    }).addClass([classY, classX].join(" "))
                    /*.append(function(){
                            return $('<p />',{
                                    id: 'store_zoom',
                                    text: ''
                            })
                    })*/
                    .append(function(){
                        return $('<img />',{
                            id: 'current_zoom', src: '', longdesc: imgMagnified
                        }).addClass('dragme').css({ visibility:'hidden' });
                    })
                    .append(function(){
                        return $('<span />',{
                                id: 'cntdetail'
                        }).html(imgDescription.html()).css('color','#000000')
                    })
                    .append(function(){
                        return $('<a />',{
                            id: 'close_zoom',
                            text: "Close",
                            click: function(){
                                closeBigCube()
                            }
                        });
                    });
                });
                $(that).after(insStructure);
                animateLoad(obj);
                return false;
	    }
			
	    function closeBigCube(obj) {
		// layer close
            	$('#current_zoom').animate({ backgroundColor: '#fff' }, 100,function() {
                    $('#store_zoom').css('display','none');
                    $('#close_zoom').css('display','none');
                    $('#current_zoom').css('display','none');
                    $('#fullzoom').animate({ width: 0, height: 0 },450,function() {
                        $(this).remove();
                        $('div',that).each(function(){
                            if($(this).hasClass('disabled')){
                                $(this).removeClass('disabled');
                            }
                        });
		    });
                });
            	return false;
            }

            // set function object
            imageSet = setCube;

	});
    }
})(jQuery);


var getParams = function(query) {
    var params = query.split("&");
    var obj = {}
    for(var i=0, l = params.length; i<l; i++) {
        var param = params[i].split('=');
        obj[param[0]] = param[1];
    }
    return obj;
    
}


$(function(){
    var gallery = $('#gallerycnt');
    gallery.gallery();
    if(location.search){
        var str = getParams(location.search.slice(1));
        if(str.id) {
            var num = Number(str.id);
            var dom;
            var path; 
            if(num){
                num -= 1;
                dom = $('div a[rel="'+ str.id +'"]',gallery)
                if(dom !== undefined){
                    imageSet(dom);
                    credit = $(dom).closest('div').find('credittext');
                    path = $("img",dom)[0].src;
                    if(path !== "") {
                        path = path.replace("thumb","zoom");
                        //open graph
                        //$('[property="og:url"]').attr("content",location.href);
                        //$('[property="og:image"]').attr("content",path);
                    }
                     
                }
            }
        }
    }

    $('#social-link a').click(function(){
        var social = $(this).attr('title'),
            url = "",
            title = document.title,
            host = location.href;

        if (search !== undefined) {
            if (location.search !== "") {
                var str = getParams(location.search.slice(1));
                if (str.id) {
                    str.id = search;
                    host = host.replace(location.search,'') + "?" + $.param(str);
                } else {
                    host += "&id=" + search;
                }
            } else {
                host += "?id=" + search;
            }
        }

        if(social=="twitter"){
            url = "http://twitter.com/?status=" + encodeURIComponent(title + " " + host); 
        } else if(social=="facebook"){
            url = "http://www.facebook.com/sharer.php?u=" + host;
        } else if(social=="mixi"){
            params = { 
                title: title, 
                body: host
            };
            url = "http://mixi.jp/simplepost/diary?" + $.param(params) ;
        }
        if(url){
            window.open(url);    
        }
        return false; 
    });
});

