$('pav_next').addEvent('click',function(e){e.stop();if (!this.hasClass('page_none')) getPictures('next');});
$('pav_pre').addEvent('click',function(e){e.stop();if (!this.hasClass('page_none')) getPictures('last');});
function getPictures(dir) {
	$('slideshow_items').fade(0.3);
    $('pictures_loading').removeClass('hidden');
	if(dir == 'next') { page++; }
	else if(dir == 'last') { page--; }
	else if(dir != '') { page = dir; }
	url = SocialEngine.URL.url_base+'misc_js.php';
	data = 'task=newpics_get&ajax_page=ajax_user&user_id='+SocialEngine.Owner.user_info.user_id+'&p='+page;
	var jsonRequest = new Request.JSON({secure: false, url: url, method: 'post',
		onComplete: updatePictures,
		onFailure: function() {
			alert('Có lỗi do đường truyền, bấm F5 để refresh');
		}
	}).send(data);
}
function updatePictures(comObj){
	var total_pictures = comObj['total_pictures'];
	var pictures = comObj['pictures'];
	page = comObj['p'];
	var maxpage = comObj['maxpage'];
	// Neu chua co anh nao
	if (total_pictures==0 && page==1){
		$('slideshow-wrap').innerHTML = SocialEngine.Owner.user_info.user_username+' chưa có ảnh';
		$('otherInfo').setStyle('display','none');
		return ;
	}
	
	$('page_statistic').innerHTML = '('+page+'/'+maxpage+')';
	if (page==1) $('pav_pre').addClass('page_none'); else $('pav_pre').removeClass('page_none');
	if (page==maxpage) $('pav_next').addClass('page_none'); else $('pav_next').removeClass('page_none');
	
	$('slideshow_items').innerHTML = '';
	var i=0;
		for(c in pictures) {
			var pic_active = (i==0)?'id="first_pic"':'';
			var newPicItem = new Element('div');
			newPicItem.addClass('slideshow_item');
			var PicItemHTML = '<a rel="'+pictures[c]['media_date']+'::'+pictures[c]['media_view']+'::'+pictures[c]['media_rate']+'::'+pictures[c]['media_totalcomments']+'" href="'+pictures[c]['media_link']+'" class="pic_item" '+pic_active+'><img title="'+pictures[c]['media_title']+'" src="'+pictures[c]['media_small_path']+'" /></a>';
			newPicItem.innerHTML = PicItemHTML;
			$('slideshow_items').appendChild(newPicItem);
		}
		var clearDiv = new Element('div');
		clearDiv.addClass('clr');
		$('slideshow_items').appendChild(clearDiv);
		$('slideshow_items').fade(1);
    $('pictures_loading').addClass('hidden');
    loadImage($('first_pic'));
    $$('.pic_item').addEvent('click',function(e1){
		e1.stop();
		loadImage(this);
	});
    
}
function loadImage(obj){
	$('pic_loading').removeClass('hidden');
	$('pic_slideshow').fade(0.3);
	$$('.pic_active').removeClass('pic_active');
	obj.addClass('pic_active');
	var picObj = obj.getChildren('img');
	var url = obj.getProperty('href');
	var rel = obj.getProperty('rel') || false;
	var title = picObj.getProperty('title') || false;
	var picActivePath = picObj.getProperty('src');
	picActivePath = str_replace('_small','_preview',picActivePath);
	var myFx2 = new Fx.Slide('pic_active', {
		duration: 1000,
		transition: Fx.Transitions.Cubic.easeOut
	});
	myFx2.slideOut().chain(function(){
		$('pic_active').getParent().dispose();
		if (title) $('pic_title').set('text',title);
		if (rel){
			var arrayRel = explode('::',rel);
			$('otherInfo').innerHTML = '<span>'+arrayRel[0]+'</span> | <span>'+arrayRel[1]+'</span> Lượt xem | <span>'+arrayRel[3]+'</span> Bình luận | <span>'+arrayRel[2]+'</span> Đánh giá';
		}
		
		var newDiv = new Element('div', {id: 'pic_active', align: 'center'});
		newDiv.setStyle('visibility', 'hidden');
		var newA = new Element('a', {href: url});
		var newImg = new Element('img', {src: picActivePath});
		$('pic_slideshow').grab(newDiv);
		$(newDiv).grab(newA);
		$(newA).grab(newImg);
		var myFx3 = new Fx.Slide(newDiv, {
				duration: 1000,
				transition: Fx.Transitions.Cubic.easeIn
		});
		var myImages = new Asset.images([picActivePath], {
			onProgress: function(){
				myFx3.hide();
			},
		    onComplete: function(){
		    	newDiv.setStyle('visibility', 'visible');
				myFx3.slideIn().chain(function(){
					reziseImage(newImg, 500, 470);
					$('pic_loading').addClass('hidden');
					$('pic_slideshow').fade(1);
				});
		    },
			onFailure: function() {
				alert('Có lỗi do đường truyền, bấm F5 để refresh');
			}
		});
		
	});
}
function explode( delimiter, string, limit ) {
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}
function is_array(mixed_var){return(mixed_var instanceof Array)}
function str_replace(search, replace, subject) {
	var f = search, r = replace, s = subject;
	var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
	while (j = 0, i--) {
		while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
	};
	 
	return sa ? s : s[0];
}

function reziseImage(obj, widthMax, heightMax){

	var div = obj.getSize();
	var w = div.x;
	var h = div.y;
	var myFx = new Fx.Morph(obj, {
		duration: 2000,
		transition: Fx.Transitions.Expo.easeOut
	});
	var tl = (w/h);
	
	if (h>heightMax && w>widthMax){
		if (tl>1){
			var margintop = (470-(widthMax/tl))/2;
			myFx.start({
				'width':widthMax,
				'height': widthMax/tl,
				'margin-top':margintop
			});
		}
		else {
			myFx.start({
				'height':heightMax,
				'width':heightMax*tl
			});
		}
	}
	if (h > heightMax){
		myFx.start({
				'height':heightMax,
				'width':heightMax*tl
			});
	}
	else if (w>widthMax) {
		var margintop = (470-(widthMax/tl))/2;
		myFx.start({
			'width':widthMax,
			'height': widthMax/tl,
			'margin-top':margintop
		});
	}
}