var panelsJSON={ panels: [] };
var availPanels=new Array;
var curPanel;
var numPanels=0;
var thumb_height=73;
var thumb_width=88;
var np=0;
var pbfilter='all';

(function () {
    $.fn.panelsCarousel = function () {
        function repeat(str, n) {
            return new Array( n + 1 ).join(str);
        }
        
        return this.each(function () {
            // magic!
            var $wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul').width(9999),
                $items = $slider.find('> li'),
                $single = $items.filter(':first')
                
                singleWidth = $single.outerWidth(),
                visible = Math.ceil($wrapper.innerWidth() / singleWidth - 1),
                currentPage = 1,
                pages = Math.ceil($items.length / visible);
                
            /* TASKS */
            
            // 1. pad the pages with empty element if required
            if ( !isNaN(visible) ) {
	            if ($items.length % visible != 0) {
	                // pad
	                $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
	                $items = $slider.find('> li');
	            }
            }
            // 2. create the carousel padding on left and right (cloned)
        	$items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
        	$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
 
            $items = $slider.find('> li');
            
            // 3. reset scroll
            $wrapper.scrollLeft(singleWidth * visible);
            
            // 4. paging function
            function gotoPage(page) {
                var dir = page < currentPage ? -1 : 1,
                    n = Math.abs(currentPage - page),
                    left = singleWidth * dir * visible * n;
                
                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft : '+=' + left
                }, 500, function () {
                    // if page == last page - then reset position
                    if (page > pages) {
                        $wrapper.scrollLeft(singleWidth * visible);
                        page = 1;
                    } else if (page == 0) {
                        page = pages;
                        $wrapper.scrollLeft(singleWidth * visible * pages);
                    }
                    
                    currentPage = page;
                });
            }
            
            // 5. insert the back and forward link
            $wrapper.after('<a href="#" class="arrow back">&lt;</a><a href="#" class="arrow forward">&gt;</a>');
            //alert('got here')
            
            // 6. bind the back and forward links
            $('a.back', this).click(function () {
                gotoPage(currentPage - 1);
                return false;
            });
            
            $('a.forward', this).click(function () {
                gotoPage(currentPage + 1);
                return false;
            });
            
            $(this).bind('goto', function (event, page) {
                gotoPage(page);
            });
            
            // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
            $(this).bind('next', function () {
                gotoPage(currentPage + 1);
            });
        });
    };
})(jQuery);



function loadPanels(){
    var autoscrolling = true;
	$('#panels').html("");
	$('#panels').html(formatPanels());

    $('.panelsCarousel').panelsCarousel().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = true;
    });
    
    if (panelsJSON.panels == undefined || panelsJSON.panels.length == 0) {
    	$.cookie.set('myProjectBox', '', { expires: -1 }); 
    } else {
   		$.cookie.set('myProjectBox',panelsJSON,{json:true,  expires: 21});
    }
	setupShadowbox();
}

function getAvailablePanels(pbfilter){
	availPanels=new Array;
	if (panelsJSON.panels != undefined) {
		for(var bx=0; bx<panelsJSON.panels.length; bx++){	
			var tmp = panelsJSON.panels[bx].ptype;
			if ((pbfilter==tmp) || (pbfilter=='all')){
				availPanels[panelsJSON.panels[bx].panelID]=panelsJSON.panels[bx];
			}
		}
	}
	//availPanels.sort(sortByAddDate);
	numPanels = availPanels.length;
}

function sortByOnDate(a, b) {
    var x = new Date(a.OnDate);
    var y = new Date(b.OnDate);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByAddDate(a, b) {
    var x = new Date(a.adddate);
    var y = new Date(b.adddate);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function addShareThisButton(){
	SHARETHIS.addEntry({
			title:'True Value Project Box',
			summary:'Check out my Project Box',
			url:'http://tvpaint.com/digitalcamera'
	}, {button:true} );
}

function formatPanels(){
	var curPanel = "";
	panel_list = "";
	getAvailablePanels(pbfilter);
	if (numPanels < 4) {
		$("a.arrow ").hide();
	}
	
	var pbkeys = new Array;
	for(var bx in availPanels){
		tmp = availPanels[bx].panelID;
		if (tmp != undefined) {
			pbkeys[pbkeys.length] = bx;
			//console.log('loopin  ' + bx+ '...' +availPanels[bx].panelID);
		}
	}
	//console.log(pbkeys[0]+ '...' +pbkeys.length);
	pbkeys.reverse();
	//console.log(pbkeys[0]+ '...' +pbkeys.length);

	
	for(var bx=0;  bx < pbkeys.length; bx++){
		//console.log(' now in main loop ' +pbkeys[bx]+ '...' +bx);
		curPanel=availPanels[pbkeys[bx]];
		if (curPanel.panelID != undefined ) {
			ctitle = curPanel.title;
			subtitle = curPanel.subtitle;
			body = curPanel.body;
			panel_list = panel_list + "<li class='panel'>";
			
			dlink = "<a href='/details.aspx?pid=" + curPanel.panelID + "' rel='shadowbox' style='float: left'>";
			if (curPanel.detaillink!=undefined) {
				dlink="<a href='" + curPanel.detaillink + "' style='float: left'>";
				detaillink = curPanel.detaillink
			}
			thumb = curPanel.thumb;
		    panel_list = panel_list + dlink;
		    switch (curPanel.ptype) {
		    	case "swatch":
				    panel_list = panel_list + "<div id='PNL-" + curPanel.panelID + "' class='pnlswatch' style='background-color: "+ curPanel.thumb +"; display:block;'></div>";
				    break;
		    	case "trend":
				    panel_list = panel_list + "<div id='PNL-" + curPanel.panelID + "' class='pnlswatch' style='background-color: "+ curPanel.thumb +"; display:block;'></div>";
				    break;
 				case "project":
 				case "lgproject":
 				case "mrproject":
 				case "paintproject":
 				case "ektrondriven":
 				    panel_list = panel_list + "<img src='"+ curPanel.thumb +"' height='"+ thumb_height +"' width='"+ thumb_width +"' />";
				    break;
	  		 	case "room":
				    panel_list = panel_list + "<img src='"+ curPanel.thumb +"' height='"+ thumb_height +"' width='"+ thumb_width +"' />";
				    break;
	  		 	case "location":
				    panel_list = panel_list + "<img src='"+ curPanel.thumb +"' height='"+ thumb_height +"' width='"+ thumb_width +"' />";
				    break;
 				case "colorstripe":
 				case "ideacard":
 				case "quickidea":
 				case "calc":
 				case "coupon":
 				case "diy":
 				case "quiz":
 				case "diy":
	  		 	case "faq":
	  		 		subtitle = subtitle.substr(0,30);
	  		 		body = "";
	  		 		//if (curPanel.body !=" " ) body=curPanel.body;
	  		 		thumb = "/images/pbox-icon-" + curPanel.ptype + ".jpg";
				    panel_list = panel_list + "<img src='"+ thumb +"'  height='"+ thumb_height +"' width='"+ thumb_width +"' />";
				    break;
		    }
			panel_list = panel_list + "</a>";
			panel_list = panel_list + "<div class='projectInfo'>";
			panel_list = panel_list + "<p><span>"+ ctitle +"</span></p>";
			panel_list = panel_list + "<h4>"+ subtitle +"</h4>";
			panel_list = panel_list + "<p>"+ body +"</p>";
/*			
			//panel_list = panel_list + "<p><a class='addthis_button_compact' addthis:url='http://www.TrueValuePaint.com' addthis:title='True Value Paint'  addthis:description='What do you think of my TrueValuePaint.com Color Swatch?' style='float: left'><img src='http://s7.addthis.com/static/btn/sm-share-en.gif' width='83' height='16' alt='Bookmark and Share' style='border:0'/></a></p>";

			//panel_list = panel_list + "<p>Share <script language='javascript' type='text/javascript'>addShareThisButton()</script> This</p>";
*/
/*
			panel_list = panel_list + "<p><a href='#'><img src='assets/images/icon_twitter.gif' alt='tweet' /></a><a href='#'><img src='assets/images/icon_facebook.gif' alt='fb status' /></a><a href='#'><img src='assets/images/icon_flickr.gif' alt='flickr /></a></p>";
*/		
			panel_list = panel_list + "<div class='share'>";
			panel_list = panel_list + "<p><a href='/sharing.aspx?ptype=" + curPanel.ptype + "&pimg=" + thumb +"&ptitle=" + ctitle +"&plink=" + detaillink +"' rel='sharelink'><img src='/images/button_addthis.gif' alt='sharethis' width='70' /></a>";
			panel_list = panel_list + "<a href='#' onclick='removeFromMyProjects(\""+curPanel.panelID + "\"); return false'>Remove</a></p>";
			panel_list = panel_list + "</div>";
			panel_list = panel_list + "</div>";
			panel_list = panel_list + "</li>";
		}
	}
	
	if (panel_list =="") {
		emptymsg = "This is your Project Box. Use it to save your favorite content from the website.<br/>Anywhere you see this <img src='/images/btn_projectbox_add.png' alt='btn_projectbox_add' width='120' height='26' />  just click and it will be stored here.";
		if (panelsJSON.panels.length > 0) emptymsg = "There are no items in your project box for this category.<br/><br/><div class='button'><a href='#pbox' onclick='filterPanels(\"all\", \"Off\");'>&nbsp;View All</a></div>";
		panel_list="<div id='emptypbox'>" + emptymsg + "</div>";
	} else {
		panel_list = "<ul>" + panel_list + "</ul>";
	}
	//console.log("panel", panel_list)
	return panel_list;
}


function addToMyProjects(pitem){
	curptype = pitem.ptype;
	ptype_desc="";
	showProjectbox();
	switch(curptype){
		case "swatch":
			ptype_desc="Color Swatch";
			pitem.body = pitem.thumb.substring(1);
			break;
		case "trend":
			ptype_desc="Trend Color";
			//pitem.body = pitem.thumb.substring(1);
			break;
		case "location":
			ptype_desc="Store Location";
			break;
		case "room":
			ptype_desc="Room Image";
			break;
	    case "ektrondriven":
			ptype_desc="Ektron Content";
			break;
	}
	
	if (curptype != undefined) {
		np++;
		pid = pitem.pid;
		if (pitem.pid =="") pid = np;
		panelsJSON.panels.push({"panelID": pid, "ptype" : curptype, "thumb" : pitem.thumb, "title" : pitem.title, "subtitle" : pitem.subtitle, "body" : pitem.body });
		loadPanels();
		$.cookie.set('myProjectBox',panelsJSON,{json:true,  expires: 21});
	} else {
		alert("object needs a ptype");
	}
}

function projectItem(pid, ptype, title, subtitle, thumb, detaillink, body, site, adddate){
	this.pid=pid;
	this.ptype=ptype;
	this.title=title;
	this.subtitle=subtitle;
	this.thumb=thumb;
	this.body=body;
	this.site=site;
	this.detaillink=detaillink;
	today = new Date();
	this.adddate = today;
}
			
function removeFromMyProjects(pid) {
	//panelsJSON.panels.splice(1,1);
	panelsJSON.panels.remove("panelID", pid)
	loadPanels();
	$.cookie.set('myProjectBoxRemoveID',pid,{expires: 21});
	window.location.href = window.location.href;
}

function clearProjectBox(){
	panelsJSON={ panels: [] };
 	loadPanels();
}

function filterPanels(newfilter, filterLabel){
 	$("#filtertype").html(filterLabel)
	pbfilter=newfilter;
 	hideViewPanel();
 	loadPanels();
}

			
Array.prototype.remove = function(name, value) {  
    var rest = $.grep(this, function(item){    
        return (item[name] != value); // <- You may or may not want strict equality
    });
    this.length = 0;
    if(rest.length == 0) {
    	$.cookie.set('myProjectBox', '', { expires: -1 }); 
    }
    this.push.apply(this, rest);
    //return this; // <- This seems like a jQuery-ish thing to do but is optional
};	

function toggleViewPanel(){
	var panelLayer = $("div#viewpanel");	
	panelLayer.slideToggle('fast');	
}			

function hideViewPanel(){
	var panelLayer = $("div#viewpanel");	
	if (panelLayer.is(':visible')==true) panelLayer.slideToggle('fast');			
}			

function addColorSwatchToProjectBox(pid, name, color){
	pbItem = new projectItem(pid, "swatch","Color Swatch", name, color.toUpperCase(), "");
	addToMyProjects(pbItem);
}

function addTrendSwatchToProjectBox(pid, name, color, product){
	pid = pid.substring(1);
	pbItem = new projectItem(pid, "trend", "Trend Color", name, color.toUpperCase(), "", product);
	addToMyProjects(pbItem);
}

function addRoomToProjectBox(pid, name, image){
	pbItem = new projectItem(pid, "room","Room Image", name, image, "", "Custom");
	addToMyProjects(pbItem);
}
					
function addStoreLocToProjectBox(zip){
	pbItem = new projectItem(zip, "location","Store Location", "True Value Stores", "/images/pbox-icon-storeloc.jpg", "", "near " + zip);
	addToMyProjects(pbItem);
}

function addDIYToProjectBox(pid, question, answer){
	pbItem = new projectItem(pid, "diy","DIY Advisor", question, "/images/pbox-icon-diy.jpg", "", answer);
	addToMyProjects(pbItem);
}

function addFAQToProjectBox(pid){
	pbItem = new projectItem(pid, "faq","Paint", "Frequently Asked Questions", "/images/pbox-icon-faq.jpg", "", "");
	addToMyProjects(pbItem);
}

function addQuizToProjectBox(pid, name){
	pbItem = new projectItem(pid, "quiz","Quiz Results", name, "/images/pbox-icon-quiz.jpg", "", "");
	addToMyProjects(pbItem);
}

function addIdeaCardToProjectBox(pid, name){
	pbItem = new projectItem(pid, "ideacard","Idea Card", name, "/images/pbox-icon-ideacard.jpg", "", "");
	addToMyProjects(pbItem);
}

function addQuickIdeaToProjectBox(pid, name){
	pbItem = new projectItem(pid, "quickidea","Quick Ideas", name, "/images/pbox-icon-quickidea.jpg", "", "");
	addToMyProjects(pbItem);
}

function addPaintCalcToProjectBox(pid, name){
	pbItem = new projectItem(pid, "calc","Paint Calculator", name, "/images/pbox-icon-calc.jpg", "", "");
	addToMyProjects(pbItem);
}

function addCouponToProjectBox(pid, name){
	pbItem = new projectItem(pid, "coupon","Coupon", name, "/images/pbox-icon-coupon.jpg", "", "");
	addToMyProjects(pbItem);
}

function addColorStripeToProjectBox(pid, name){
	pbItem = new projectItem(pid, "colorstripe","Color Stripe Card", name, "/images/pbox-icon-colorstripe.jpg", "", "");
	addToMyProjects(pbItem);
}

function addMRProjectToProjectBox(pid, name){
	pbItem = new projectItem(pid, "mrproject","M&R Project", name, "/images/pbox-icon-mrproject.jpg", "", "");
	addToMyProjects(pbItem);
}

function addLGProjectToProjectBox(pid, name){
	pbItem = new projectItem(pid, "lgproject","L&G Project", name, "/images/pbox-icon-lgproject.jpg", "", "");
	addToMyProjects(pbItem);
}

function addPaintProjectToProjectBox(pid, name){
	pbItem = new projectItem(pid, "paintproject","Paint Project", name, "/images/pbox-icon-paintproject.jpg", "", "");
	addToMyProjects(pbItem);
}


//Addthis
$('.sharelink').click(function() {
    $('.lightbox').fadeIn('fast');
    return false;
});
$('.lightbox_close').click(function(){
    $('.lightbox').fadeOut('fast');
    return false;
});

