$(function() {

	// Onload, preload eeeeeeevreything
	getSlides();
		
}); // end init

//Get info for each slide!
function getSlides(){
		
		// Get the values from ajax call to json script, and populate the structure
		$.ajax({
				//url: "/widget/php/getDeals.php",
				//Instead of dynamically generating the JSON on each call
				//grab the JSON generated from a PHP cronjob
				url: "/widget/json/slider.json",
				async: "false",	// we don't want to continue until the loading is loaded
				dataType: "json",
				beforeSend: function(){
					$("#dl_slider").append("<div id='loader'></div>");
				},
				success: function(results){
			
					// create the 'template'
					createTemplate(results);
					
				},
				error: function(jqXHR, textStatus, errorThrown){
					$("#error").html(errorThrown);
				}
			});
}

// create slider template
function createTemplate(results){
	
	var thestuff = 	"<div id='slider_colors'>" +
				"<h1 class='title'>We work with the beast</h1>" +
							"<div id='adplace'>" +
								"<ul id='slider'>" +
								"</ul>" +
								"<div id='my-pager-container'><div id='my-pager'></div>" +
							"</div>" +
						"</div>" +
					"</div>" +
					"<div class='linkstext'>" +
						"<div class='linkboxes'>" +
							"<div class='button1 linkbox ui-corner-all' onClick=\"window.location.href='http://www.groupcommerce.com/publishers/'\"><span class='buttontitle'>Button1</span><br/><br/> <span class='buttontext'>Test button 1</span></div>" +
							"<div class='button2 linkbox ui-corner-all' onClick=\"window.location.href='http://www.groupcommerce.com/merchants/'\"><span class='buttontitle'>Button2</span><br/><br/> <span class='buttontext'>Test button 2</span></div>" +
						"</div>" +
						"<h2 class='subtitle'>Subtitle</h2>" +
						"<p class='text'>Lorem ipsum dolor sit amet.</p>" +
					"</div>" +							
					"<div class='bottom-box ui-corner-bottom'>" +	
						"<img id='logo1' class='logo' src='' alt='' height='20' width='20'>" +
						"<img id='logo2' class='logo' src='' alt='' height='20' width='20'>" +
						"<img id='logo3' class='logo' src='' alt='' height='20' width='20'>" +
						"<img id='logo4' class='logo' src='' alt='' height='20' width='20'>" +
						"<img id='logo5' class='logo' src='' alt='' height='20' width='20'>" +
						"<img id='logo6' class='logo' src='' alt='' height='20' width='20'>" +
						"<img id='logo7' class='logo' src='' alt='' height='20' width='20'>" +
					"</div>" +
					"<div class='clear'></div>" +
				"</div>";
	
	$("#dl_slider").html(thestuff).addClass("ui-corner-all");
	
	// fill in the 'general' info
	if(results.general){
		$("#dl_slider").find(".title").html(results.general.title);
		$("#dl_slider").find(".subtitle").html(results.general.subtitle);
		$("#dl_slider").find(".text").html(results.general.text);
		$("#dl_slider").find(".button1").find(".buttontitle").html(results.general.button1.title);
		$("#dl_slider").find(".button1").find(".buttontext").html(results.general.button1.text);
		$("#dl_slider").find(".button1").click(function(){window.location.href=results.general.button1.url});
		$("#dl_slider").find(".button2").find(".buttontitle").html(results.general.button2.title);
		$("#dl_slider").find(".button2").find(".buttontext").html(results.general.button2.text);
		$("#dl_slider").find(".button2").click(function(){window.location.href=results.general.button2.url});
		
		for(var em in results.general.logos){
			$("#"+em).attr("src",results.general.logos[em].url).attr("height",results.general.logos[em].height).attr("width",results.general.logos[em].width).click(function(){window.location.href="http://www.groupcommerce.com/clients"});
		}
		
		// Get caption params
		var captionparams = makecaption(results.general.caption);
	}
	else {
		var captionparams = "Check out these great deals.";
	}
	
	if (results.data){

		// For each data object, get values and make a slide
		for(idx=0; idx<results.data.length;idx++){
	
			if (!results.data[idx]){ // Return false if you don't find data
				continue;
			}

			// Make each slide
			makeSlide(idx,results.data[idx],captionparams);

		}
	}

	//$("#thead").remove(); // delete template

	// Hide the loader, show the slider
	$("#loader").hide();
	$("#adplace").show();

	// Once everything is preloaded, now load slider
	$("#slider").bxSlider({
		mode: 'fade',
		speed: 1000,
		pause: 5000,
		infiniteLoop: true,
		controls: true, // prev and next arrows
        auto: true,
        pager: true, // pager buttons
        pagerSelector: '#my-pager'
        /*onAfterSlide: function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject){ 	
			// Make bg same height as fg (can't use CSS or it would opacity-ize the entire thing including text)
    		var targheight = currentSlideHtmlObject.find(".textfg").height();
			currentSlideHtmlObject.find(".textbg").height(targheight);
			//Positioning the caption in the center of the slide
			//var toppixels = (135 - 0.5*(targheight));
			//currentSlideHtmlObject.find(".textbg,.textfg").css("top",toppixels+"px");
        	}*/      
		});
}

// Turns slide info into html structure
function makeSlide(num,dlr,captionparams){
	
		var templateli = "<li id='thead-"+num+"'>" +
			//"<div class='dealimg'>" +
				"<div class='caption'>" +
					/*"<span class='dealername'></span> is offering a deal worth " +
					"<span class='discountPercent'></span> off at " +
					"<span class='merchant'></span>" +*/
				"</div>" +
				"<div class='imageplate ui-corner-all'></div>" +
			//"</div>" +
			"<div class='dealers ui-corner-all'>" +
				"<div class='dealerimg'>" +
					"<img src='http://groupcommerce.com/images/dailycandy_logo.png' width='200' height='66' alt='merchant image'>" +
				"</div>" +
				"<div class='dealerplate ui-corner-bottom'>" +
					"<div class='dealertext'>Lorem ipsum dolor sit amet</div>" +
				"</div>" +
			"</div>" +
		"</li>";
		
		// Append the (hidden) clone-x to the ad box
		$("#slider").append(templateli);
		
		// and select by new id
		var mydiv = $("#thead-"+num);
		
		// Copy the basic html structure
		//var mydiv = $("#thead").clone().attr("id","thead-"+idx);
		
                //Check for 0% deals and edit the caption accordingly
                if  (dlr.options[0].pricing.discountPercent == "0%") {
                        captionparams_edited = captionparams[0].replace("worth","");
                        captionparams_edited = captionparams_edited.replace("off "," ");
	  		   $(mydiv).find(".caption").html(captionparams_edited);
                }
		  else {
			// For caption: first put in caption with spans
			$(mydiv).find(".caption").html(captionparams[0]);
		  }
		var tags = captionparams[1];
		
		// Now place each item in params
		for(var j=0;j<tags.length;j++){
			
			// Special cases, I guess
			if(tags[j] == 'discountPercent'){
				var toprint = dlr.options[0].pricing.discountPercent;
                                //Remove 0%
                                if (toprint == "0%") {
                                        toprint = "";
                                }
			}
			else if (tags[j] == 'dealerName'){
				var toprint = dlr.dealer.name;
			}
			else if (tags[j] == 'companyName'){
				
				if (dlr.merchant){
					var toprint = dlr.merchant.companyName;
				}
				else {
					var toprint = dlr.headline;
				}
			}
			else {
				var toprint = dlr[tags[j]];
			}
			
			$(mydiv).find("."+tags[j]).html(toprint);
		}
		
		// Rest of items
		$(mydiv).find(".dealerimg").html("<img src='"+dlr.dealer.image.url+"' height='"+dlr.dealer.image.height+"' width='"+dlr.dealer.image.width+"' alt='"+dlr.dealer.name+" logo'>");
		$(mydiv).find(".dealertext").html(dlr.dealer.copy);
		$(mydiv).find(".imageplate").click(function(){window.open(dlr.url)});
		$(mydiv).find(".dealers").click(function(){window.open(dlr.dealer.link.dealsurl)});
		//$(mydiv).find(".offerlink").html("[<a href=\""+dlr.url+"\">"+dlr.link.text+"</a>]");
	
		var myimg = getRandomImage(dlr.images);

		// Set image as background image of the add
		$(mydiv).find(".imageplate").css("background-image","url('"+myimg+"')");
	}

// Given an array of images URLS, returns a random image URL from the list; checks for isOfferImage flag
function getRandomImage(images){

	// If this array is empty, return empty string
		if (images.length <= 0){
			return "";
		}

	// Choose a random image.
		var imgcount = images.length;
		var randnum = Math.floor(Math.random()*imgcount);
		var myimg = images[randnum].url;
		
	// Try again or return, depending on if this image has isOfferImage flag set
		if (myimg.isOfferImage == 'false'){
			// Remove this image from the array
				images = images.slice(0,randnum).concat( images.slice(randnum+1) );
				
			// Run the function again
				getRandomImage(images);
		}
		else {
			return myimg;
		}
}
	
function makecaption(jsoncaption){
	
	// Initialize return variables
	var returncaption = "";
	var returntags = new Array;
	
	// Get all tags
	var findtag = new RegExp(/\[\[[a-zA-Z0-9]+\]\]/gi);
	var tags = jsoncaption.match(findtag,'gi');
	
	// Go thru each tag... replace with <span>, and add to array to return
	for (var i=0;i<tags.length;i++){
		var tag = tags[i].split("[")[2].split("]")[0];
		var search = new RegExp('\\[\\['+tag+'\\]\\]');
		jsoncaption = jsoncaption.replace(search,"<span class='"+tag+" specialtag'></span>");
		returntags.push(tag);
	}

	//alert("return:"+[jsoncaption,returntags]);
	return [jsoncaption,returntags];
	
}

