mcmGlobals = {}

mcmGlobals.tag = ''

mcm_stewf_gallery_EBAY_APP_ID = 'StephenC-b68a-4a01-80cc-fa0d371f663f'

mcm_stewf_gallery_url_with_affiliate_id =function(id){
var out = 'http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=2&pub=5574666425&toolid=10001&campid=5336529894&customid=&icep_item='
out += id
out += '&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg'

return out
}


mcm_stewf_gallery_caseless_sort =  function(a, b){
	a = a.toLowerCase(); b = b.toLowerCase();
	if (a>b) return 1;
	if (a <b) return -1;
	return 0; 
}

mcm_stewf_gallery_parse_duration = function(duration){
	if(duration == 'PT0S'){
		return 'Auction has Ended'
	}
	
	duration = duration.replace('P','').replace('T','')
	
	if (duration.match('D')) {
		days = parseInt(duration.split('D')[0])	
		return(days + ' Days Remaining')		
	}
	
	if (duration.match('H')) {
		hours = parseInt(duration.split('H')[0])
		return(hours + ' Hours Remaining')
	}	
	
	minutes = parseInt(duration.split('M')[0])			
	if (minutes > 0 ) {
		return(minutes + ' Minutes Remaining')
	}
	
	//P3DT12H35M31
	return duration
		
}

mcm_stewf_gallery_unique_array = function (arrayName)
{
    var newArray=new Array();
    label:for(var i=0; i<arrayName.length;i++ )
    {  
        for(var j=0; j<newArray.length;j++ )
        {
            if(newArray[j]==arrayName[i]) 
                continue label;
        }
        newArray[newArray.length] = arrayName[i];
    }
    return newArray;
}



mcm_stewf_gallery_create_public_gallery = function(base_url, data, tag) {
	//we care about the current tag incase we're only looking at active auctions
	var out = ''
	var set_holder = []
	var k = 0;
	var single_set = []
	var len = data.pieces.length - 1
	
	//set this for mcm_stewf_gallery_get_items_from_ebay_ids
	mcmGlobals.tag = tag
	
	jQuery("div.paginationHolder").html(data.pagination)
	
	jQuery("div.paginationHolder a").each( function(){
		var new_url = jQuery(this).attr('href').replace('/api','')
		jQuery(this).attr('href', base_url + new_url)
	})
	
	jQuery(data.pieces).each(function(i, value){
		if ( (i%20 == 0) || (len  == i) ) {

			set_holder[k] = single_set			
			single_set = []
			k += 1;			
		}

 		single_set.push(value['piece'])

		var classes = value['piece']['cached_tag_list'].replace(/, /g, ',') 
		classes = classes.replace(/ /g, '_') 
		classes = classes.replace(/,/g, ' ')
		
		out +='<div class="itemHolder ' + classes + '">'
		
		//we want a seperate div for holder the ebay content so stewfs content will show up.
		out += '<div id="' + value['piece']['ebay_item_id'] + '">'
		out += '<a href="' +  mcm_stewf_gallery_url_with_affiliate_id(value['piece']['ebay_item_id']) + '">'
		
		out += '<img src="' + value['piece']['s3_url'] + '" /></a>' + '<div class="update_holder">'		
		out += '<div class="description">' + value['piece']['description'] 
		out += '<span class="like-button" id="like_' + value['piece']['id'] + '">like</span>'
		out += '<span class="like-count" id="like-count_' + value['piece']['id'] + '">' + value['piece']['likes'] +'</span>'
		out += '<a class="edit-link" href="http://stewfbay.heroku.com/pieces/' + value['piece']['id']  + '/edit" class="edit-link">' +"edit</a>"			
		out += '</div></div></div>'
		
		out += '</div>'	
		 
		
		if ( (i%20 == 0) || (len  == i) ) {

			set_holder[k] = single_set			
			single_set = []
			k += 1;			
		}
		
	});

	
	jQuery('#mcm_stewf_gallery').html(out);
	
	//slicing off the first empty array
	jQuery(set_holder.slice(1)).each(function(i, value){		
		mcm_stewf_gallery_get_items_from_ebay_ids(value)	
	});
		
	//adding hover effect, have to do it on this end
	jQuery("div.itemHolder").hover(function(){
			jQuery(this).find("img").animate({opacity:0.01},300)
		},	
		function(){
			jQuery(this).find("img").animate({opacity:1.0}, 300)
		});
	
	jQuery("div.itemHolder").hover(function(){
			jQuery(this).find("img").animate({opacity:0.01},300)
		},	
		function(){
			jQuery(this).find("img").animate({opacity:1.0}, 300)
		});
		
}

mcm_stewf_gallery_get_items_from_ebay_ids = function(item_json){
	
	var item_array = []
	jQuery(item_json).each(function(i, val){
		item_array.push(val['ebay_item_id'])
	});	

		var load_ebay = '<script type="text/javascript" src="http://open.api.ebay.com/shopping?appid=' + mcm_stewf_gallery_EBAY_APP_ID
		load_ebay += '&ItemID=' + item_array.join(',') + "&"
	
		load_ebay += 'version=647&siteid=0&callname=GetMultipleItems&responseencoding=JSON&'
		load_ebay += 'callbackname=mcm_stewf_gallery_display_public_gallery'
	
		load_ebay += '"></script>'

		jQuery('body').append( load_ebay )
}

mcm_stewf_gallery_display_public_gallery = function(data) {
		
	  var items = data.Item;
	  var out = ''
	
	  for (var i = 0; i < items.length; ++i) {
		
				
		var item = items[i];
				
		if( mcmGlobals.tag == 'active' && item.TimeLeft == 'PT0S' ) {
			jQuery('#' + item.ItemID ).hide();
		} else {
			out = ''		
			out +=  '<a href="' + mcm_stewf_gallery_url_with_affiliate_id(item.ItemID) + '" class="itemLink" target="_blank">'
				out += '<span class="itemInfo">' 
					out += '<span class="title">'+ item.Title + '</span>'
					out += '<span class="timeLeft">'+ mcm_stewf_gallery_parse_duration(item.TimeLeft) + '</span>'
					out += '<div class="description">' + jQuery('#' + item.ItemID + ' div.update_holder div.description' ).html() + '</div>'				
					out += '<span class="bids">'+ item.BidCount + '</span>'
					out += '<span class="price">$'+ item.ConvertedCurrentPrice.Value + '</span>'
					out += '</span>'
					out += '</a>'
			jQuery('#' + item.ItemID + ' div.update_holder' ).html(out);					
		}	
	  }
	
	jQuery("span.like-button").unbind('click');
	//adding like button function
	
	jQuery("span.like-button").click( function(ev){
		var id = jQuery(this).attr('id').split('_')[1]
		var my_url = global_admin_app_url + '/api/like_piece/' + id
		
		var count_span = jQuery('#like-count_' + id)
		count_span.html( parseInt(count_span.html()) + 1)
		
		jQuery(this).fadeOut()
		
		jQuery('body').append('<script type="text/javascript" src="' + my_url + '"></script>')
		ev.stopPropagation()
		return false	
	})	  	
};

mcm_stewf_gallery_build_tag_toggle = function( tags, url ) {
	
	out = '<span id="tag_title">Filter by tag:</span>'
	
	out+= '<li><a href="' + url + '/all" class="tagButton " id="all">all</a></li>'
	
	
	jQuery(tags).sort(mcm_stewf_gallery_caseless_sort).each(function(i,valu){
			
		var nice = valu.replace(' ', '_')
		out += '<li><a href="' + url + '/' + nice + '" class="tagButton" id="' + nice +'">' + valu + '</a></li>'
		
		if( i== 49){
			out += '<span style="clear:both; display:block;" id="show-tags">Show all tags</span><div id="hidden-tags" style="display:none;" id="hidden-tags">'	
		}
		
	});
				
	out += '</div>'	
				
	jQuery('#mcm_stewf_tags').html(out)	
	
	jQuery('#show-tags').click(function(){
		jQuery('#hidden-tags').slideDown();	
		jQuery(this).slideUp(400, function(){
			jQuery(this).css('display', 'none !important')
		});
	});
		
}

mcm_stewf_gallery_fix_tags = function(tag, url ){
	if(!tag) {
		tag = 'all'
	}
	
	if(tag == 'active' ) {
		jQuery('#active').attr('href',url).html('Show archived auctions')	
		
//		jQuery('div.auctionEnded').hide();
	}
	
	jQuery('#' + tag ).addClass('selected')	
	
}

success = function(){ return true}
