$(document).ready(function(){
		
		// Clear image from attachment div.
		$("#posted-article").html("");

    
		
		var postImages      =new Array();						//creates a new array	
		var myImages        =new Array();						//creates a new array	
		var myImagesCheck        =new Array();						//creates a new array	
		var myDescriptions=new Array();						//creates a new array	
		$('#gallery-1 img').css("display","none");  		// hides all the images under size-medium class  

    function isGalleryImage(description) {
        beginning = description.substring(0,15);
        if (beginning=='|m-mag-gallery|') {
            isGalleryImageBool = true; 
        } else {
            isGalleryImageBool = false;
        }
        return isGalleryImageBool;
    }

    function filterDescriptions(description) {
        filteredString = description;
        if (isGalleryImage(description)) {
             filteredString = description.substring(15,(description.length));
        }
        return filteredString;
    }

    //Get all images that are inserted into the body of a post. 
    $('.entry p img').each(function()			//loop to check the available images under post-alt div and size-medium 	
			{
				var Imagesrc=($(this).attr("src"));		//gets the path of the image to a variable
				var Imagealt=($(this).attr("alt"));		//gets the path of the image to a variable
        Imagesrc = Imagesrc.substring(0,(Imagesrc.length)-12);
				//postImages.push(Imagesrc); 				//and adds into the create array
			});
    window.postImages = postImages;


		if ($('#wrap').length)								//if a carousel wrap div exists
		{
			$('#mycarousel li').remove();
			$('#gallery-1 img').each(function()			//loop to check the available images under post-alt div 
			{
				var Imagesrc=($(this).attr("src"));		//gets the path of the image to a variable
				var Imagealt=($(this).attr("alt"));		//gets the path of the image to a variable
        ImagesrcCheck = Imagesrc.substring(0,(Imagesrc.length)-12);
				myImagesCheck.push(ImagesrcCheck); 				//and adds into the create array
          if (jQuery.inArray(ImagesrcCheck, postImages) == -1) {
            ImagesrcResized = "http://www.m-magazine.co.uk/wp-content/themes/dailyedition/thumb.php?src=" + ImagesrcCheck + ".jpg&w=560" 
                      if (isGalleryImage(Imagealt) ) {
                        myImages.push(ImagesrcResized);        		//and adds into the create array
                        myDescriptions.push(filterDescriptions(Imagealt)); 				//and adds into the create array
                      }
          }

			});
			   
    window.myImages = myImages;
			for (image_loop in myImages)				//another loop to go through the array		
			{
				var getvalue=myImages[image_loop]		//and get the path from the 'th element 
				$('#mycarousel').append(				// and appends in the list
					"<li jcarouselindex='"+image_loop+"' class='jcarousel-item jcarousel-item-horizontal'>"+"<img class='image' id='image-carousel"+image_loop+"' src='"+getvalue+"'/>"+"</li>"
				);
					   //alert(image_loop);
			}

         

		} else /*if wrap doesnt (carousel) exists*/ {
		
    /*this should probably vo into a function*/
			$('#gallery-1 img').each(function()		//loop to check the available images under post-alt div and size-medium 
			{
				var Imagesrc=($(this).attr("src"));  	//gets the path of the image to a variable
				var Imagealt=($(this).attr("alt"));  	//gets the path of the image to a variable
				if ($(this).parent().attr("class") != "post-ratings" && $(this).parent().attr("class") != "post-ratings-loading") { 
        ImagesrcCheck = Imagesrc.substring(0,(Imagesrc.length)-12);
				myImagesCheck.push(ImagesrcCheck); 				//and adds into the create array

          if (jQuery.inArray(ImagesrcCheck, postImages) == -1) {
            ImagesrcResized = "http://www.m-magazine.co.uk/wp-content/themes/dailyedition/thumb.php?src=" + ImagesrcCheck + ".jpg&w=560" 
                      if (isGalleryImage(Imagealt)) {
                        myImages.push(ImagesrcResized);        		//and adds into the create array
                        myDescriptions.push(filterDescriptions(Imagealt));        		//and adds into the create array
                      }
          }
				}
			});
    window.myImages = myImages;
    window.myImagesCheck = myImagesCheck;
	
      default_src = myImages[0]; 
      default_des = myDescriptions[0]; 
    
      //If the image at the top exists. 
      if ($('.topImageBorder').length>=1)  {
            window.gallery_image = ""; 
			$(".imageText").html(default_des);
      } else {
			//Check if the top image is already on the page. If not, add it. 
            window.gallery_image = 
            "<div class='topImageBorder'>" +
            "<img class='thumbnail' alt='" + default_des + "' src='"+default_src+"'>" +
			"<p class='imageText'>"+ default_des + "</p>" +
            "</div>";
      }

			$('#posted-article').prepend(  //prepends the carousel to top

        window.gallery_image +

				"<div id='wrap'>"+
				"<div class='slideshowbar'><a id='startShow'>Play slideshow</a><img id='sliderArrows' class='arrowLeft' src='/wp-content/themes/dailyedition/carouselfiles/slideArrow2.png'/><div id='sliderNumbers'><div id='sliderMin'>1</div> of <div id='sliderMax'>7</div></div><img class='arrowRight' src='/wp-content/themes/dailyedition/carouselfiles/slideArrow.png'/></div>"+
				"<div class='jcarousel-skin-tango'>"+
				"<div class='jcarousel-container jcarousel-container-horizontal'>"+
				"<div class='jcarousel-clip jcarousel-clip-horizontal'>"+
				"<ul id='mycarousel' class='jcarousel-list jcarousel-list-horizontal'>"+
				"</ul>"+	
				"</div>"+
				"<div class='jcarousel-prev jcarousel-prev-horizontal'>"+
				"</div>"+
				"<div class='jcarousel-next jcarousel-next-horizontal jcarousel-next-disabled jcarousel-next-disabled-horizontal'>"+
				"</div>"+
				"</div>"+
				"</div>"+
				"</div>"									
			);
		  $('.arrowRight').click(function()  {
        //Set the image blurb depending on the alt tag for that image.Beautiful
        image_position = parseInt($("#sliderMin").html());
        if ((image_position+1) > parseInt($("#sliderMax").html()) ) {
          return;
        }
        $('#sliderMin').text(image_position+1);
        blurb = myDescriptions[image_position];
			  $("#posted-article .imageText").html(blurb);
			  var vari1 = $('#image-carousel'+(image_position)).attr("src");	
        //console.log('ARROW RIGHT!'+image_position+'variable'+vari1);
        $('#stwrapper').append('<!--' + image_position + vari1 +'!-->');
			  $("#posted-article .thumbnail").attr("src", vari1);
			  $('#posted-article .image-src').attr("href",vari1)
      });
		  $('.arrowLeft').click(function()  {
        //Set the image blurb depending on the alt tag for that image.Beautiful
        image_position = parseInt($("#sliderMin").html());
        if ((image_position-1) < 1 ) {
          return;
        }
        $('#sliderMin').text(image_position-1);
        blurb = myDescriptions[image_position-2];
			  $("#posted-article .imageText").html(blurb);
			  var vari1 = $('#image-carousel'+(image_position-2)).attr("src");	
        //console.log('ARROW LEFT!'+(image_position-2)+'variable'+vari1);
        $('#stwrapper').append('<!--' + image_position + vari1 + '!-->');
			  $("#posted-article .thumbnail").attr("src", vari1);
			  $('#posted-article .image-src').attr("href",vari1)
      });


						 
      $('#sliderMax').text(myImages.length);					   
						   
			for (image_loop in myImages)  			//another loop to go through the array	
			{
				var getvalue=myImages[image_loop]  	//and get the path from the 'th element 
						   
				$('#mycarousel').append(    			// and appends in the list
					"<li jcarouselindex='"+image_loop+"' class='jcarousel-item jcarousel-item-horizontal'>"+"<img class='image' id='image-carousel"+image_loop+"' src='"+getvalue+"'/>"+"</li>"
				);
			}

		}


				
		/*Next button funcion*/
				
		$('.jcarousel-next').click(function()  					
		{
			var valueofwidth;								//creates a new variable to get the width
			//$('.jcarousel-prev').css("background-position","0% 0%");
			for (image_loop in myImages)  					//count-down the number of images
			{
        //Set a global flag to stop added buttons. 
				valueofwidth=(image_loop)*(75);				//multiplies number of images * an image width(75) 
			}
						 
			var get_in_minus_value= (valueofwidth)*(-1);	//makes the value minus		
						
			var currentleft=$('#mycarousel').css("left");	// gets the left value
			var splittedleft=currentleft.split('px');		// splits tyhe px
			var myleftinteger = parseInt(splittedleft[0]); 	// converts hthe value into integer
						
						 
			if ((myleftinteger-300)>(parseInt(get_in_minus_value))) 	//subtract theleft value from 185 and check if it is greater than the total width the perform oopertation\
			{
				$('#mycarousel').animate({left:(myleftinteger-505)});		//animate(the ul list)
					
				$('.jcarousel-prev').css("background-position","0% 0%"); 	//and enable the privios button
				//$('.jcarousel-prev').attr("disabled","disabled");
					 			
			}
					
			if ((myleftinteger-505)<(parseInt(get_in_minus_value)))				//disables the next button when reaches the last set of images
			{
				$('.jcarousel-next').css("background-position","100% 0%");		
			}
						
		});

		/*****previous button*******/

					
		$('.jcarousel-prev').click(function() 
		{
			var currentleft=$('#mycarousel').css("left");			/*does the reverse operation of the next buttom*/
			var splittedleft=currentleft.split('px');
			var myleftinteger = parseInt(splittedleft[0]); 
					
					
			if((myleftinteger)<(0))	
			{
				$('.jcarousel-next').css("background-position","0% 0%");
				$('#mycarousel').animate({left:(myleftinteger+505)});
			}
				
					
			if ((myleftinteger+505)>(0))
			{
				$('.jcarousel-next').css("background-position","0% 0%");
				$('.jcarousel-prev').css("background-position","100% 0%");
			}
					
					
		});				
				
		/*shows the image as a large one in center*/
		$(".image").click(function()
		{
			var vari1 = $(this).attr("src");	
			$("#posted-article .thumbnail").attr("src", vari1);
			$('#posted-article .image-src').attr("href",vari1)
					
		});	
					
		// Slideshow functionality
		var interval = 0;
		$("#startShow").toggle(function(){
			$(this).html("Stop slideshow");
		  $(this).css("background","url('/wp-content/themes/dailyedition/carouselfiles/square.png') no-repeat scroll 60px 4px transparent");  		// hides all the images under size-medium class  
			var slideCount = -1;
			slideCount = advanceSlide(slideCount, myImages, myDescriptions);
			interval = setInterval(function(){
				slideCount = advanceSlide(slideCount, myImages, myDescriptions);
			}, 5000);
		}, function() {
			$(this).html("Play slideshow");
		  $(this).css("background","url('/wp-content/themes/dailyedition/carouselfiles/slideArrow.png') no-repeat scroll 60px 4px transparent");  		// hides all the images under size-medium class  
			interval = clearInterval(interval);
		});
		// Text functionality (dummy)
		/*$(".thumbnail").wrap("<div class='topImageBorder' />");
		$(".thumbnail").after("<p class='imageText'></p>");*/
					
		$(".image").click(function(){
			var id = $(this).attr("id");
      //Set the image blurb depending on the alt tag for that image.Beautiful
      image_position = parseInt(id.substring(14));
      $('#sliderMin').text(image_position+1);
      blurb = myDescriptions[image_position];
			$(".imageText").html(blurb);

			/*if (id == "image-carousel0") {	
				$(".imageText").html("This is some text.");
			} else {
				$(".imageText").html("This is some more text.");
			}
      */
		});

	});
		

	/** Advances the slideshow to the next stage. */
	function advanceSlide(slideCount, myImages, myDescriptions) {
		$(".topImageBorder").fadeOut("fast", function(){
			$("#posted-article .thumbnail").attr("src", myImages[slideCount]);
			$("#posted-article .imageText").html(myDescriptions[slideCount]);
			//$(".imageText").html("");
		});
		$(".topImageBorder").fadeIn();
		slideCount += 1;
		if (slideCount >= myImages.length) {
			slideCount = 0;
		}
    $('#sliderMin').text(slideCount+1);
		return slideCount;
	}
				
				
				
				

