// JavaScript Document



jQuery(document).ready(function() {
     
	 
	 // JSON load not used in this implementation
	 // var $DataURL     ='http://qa.symtio.com/symtio/control/widgetDataByISBN?isbns=9780310938231|9780310270690|9780310296188&a=symtio';
	 // $DataURL          +=  format=json&jsoncallback=?'
     
	
	 
 
   //-------------------------------------------------------------------------------------------------
   
$.extend({ 
     
	 InitWidget: 
	  
	    function InitWidget(){
	 
				  // Set Visual Properties
				  //console.log('** InitWidget()==> WidgetSettings:', WidgetSettings);
				 
				  carouselDiv       = $('#mycarousel2').parent().parent();
				  tblParent         = $('#mycarousel2').parent().parent().parent().parent().parent().parent().parent();
				  MYwidgetTextColor = WidgetSettings['widgetTextColor'];
				  MYtitleTextColor  = WidgetSettings['titleTextColor'];
				  
				    
				  
				    //physical width of the carousel if its an ad type it is fixed to 300 wide
				 
				   if( $WidgetType == "content"){
					      // HORZ CONTENT SCROLLER
						  
						  w = parseInt( WidgetSettings['widgetWidth']);
						 
					      //get current padding value, convert to int and thn sub from width (not hardcodeint this now, since edge sever creats issues)
					      //padding = carouselDiv.css("padding-left");
						  padding = 40;
						  
					     // padding = parseInt( padding.substr(0,padding.length -2) );
					      
						  carouselDiv.css('width',w - (padding + 44)) ;
						   
						  //console.log("calculate Width:", w -  (padding + 44));
						  
						  // the visible clip (should be same as width)
						  carouselDiv.find("div.jcarousel-clip").css('width',w -  (padding + 44) );
						  
						  $myCarousel.options.scroll = 3;
						  
					}else{
						  // AD RAIL  TYPE
						  
						  //start Reading Button
						   carouselDiv.find('.WidgetButton a').css({"background-color": WidgetSettings['viralLinkColor']});
						  
						  // changed this to allow local styles to control dimension since this is always fixed
						  //console.log("setting width to:", $adWidthMin);
						 // carouselDiv.css('width',$adWidthMin) ;
						  // the visible clip (should be same as width)
						  //carouselDiv.find("div.jcarousel-clip").css('width',$adWidthMin);
				  
						  WidgetSettings['widgetWidth'] = $adWidthMin;
						  
						  $myCarousel.options.scroll = 1;
						  //element width
					      //carouselDiv.find("li.jcarousel-item").each(function() {
						  // });
						  //			
						 // carouselDiv.find("li.jcarousel-item").css({"width":"300px"})
						  
						  //BUTTON background buttonBgColor
						   //console.log("applying new color: ",WidgetSettings['buttonBgColor'])
						   carouselDiv.find('div.WidgetButton').each(function() {
							   newCOLOr =WidgetSettings['buttonBgColor'];
							   $(this).find('a').attr('style', "background-color:" + newCOLOr );
						      
						  });
						   
						   
						   carouselDiv.find('div.data_Title').each(function() {
							    $(this).attr('style', "color:" + MYtitleTextColor );
						    });
						   
						   carouselDiv.find('div.data_Auth').each(function() {
							    $(this).attr('style', "color:" + MYwidgetTextColor );
						    });
						   
						   carouselDiv.find('span.data_Desc').each(function() {
							    $(this).attr('style', "color:" + MYwidgetTextColor );
						    });
						   
						  // <span class="data_Desc"
						  //console.log(  carouselDiv.find('div.data_Title').css('color',"") )
						  //<div class="WidgetButton"><a href="#">Start Reading Now!</a></div>
					}
					
				   
				   /* // Wrap image in a div to hide blank spaces, default background has no image graphic
			          carouselDiv.find('img.prodthumbImg').each(function() {
				             w = $(this).css('width') ;
				             h = $(this).css('height') ;
				              ///http://widget.symtio.com/img/carousel/noImage.jpg
				             $(this).wrap('<div class="proddiv" style="border: 0px solid #686868; height: ' +  h +  '; width: ' + w + '; background-image:url(http://widget.symtio.com/img/carousel/noImage.jpg); background-repeat:no-repeat"></div>');

			          });
			    */
			         // bttnNext = carouselDiv.find('div.jcarousel-next');
			         // bttnPrev = carouselDiv.find('div.jcarousel-prev');
			         // bttnNext.css("width","32px");
			         // bttnPrev.css("width","32px");
			         //console.log (bttnNext.attr("width","32px"));
				  
					
				  tblParent.find('div#virLink a').css({"color": WidgetSettings['viralLinkColor'] });
					
				  
				  //Next and Previous Button Images make them dark  or light(options are light|dark)
				  nextBttnDiv  = carouselDiv.find("div.jcarousel-next-horizontal"); 
				  prevBttnDiv  = carouselDiv.find("div.jcarousel-prev-horizontal");
	
				 		 
				if (WidgetSettings['buttonType'] == 'light' ){
					
					prevBttnDiv.removeClass('jcarousel-prev-horizontal-dark');
				    nextBttnDiv.removeClass('jcarousel-next-horizontal-dark');
					
					prevBttnDiv.addClass('jcarousel-prev-horizontal-light');
				    nextBttnDiv.addClass('jcarousel-next-horizontal-light');
					
				}else if (WidgetSettings['buttonType'] == 'dark' ){
					
					prevBttnDiv.removeClass('jcarousel-prev-horizontal-light');
				    nextBttnDiv.removeClass('jcarousel-next-horizontal-light');
					
					prevBttnDiv.addClass('jcarousel-prev-horizontal-dark');
					nextBttnDiv.addClass('jcarousel-next-horizontal-dark');
					
				}else{
					
					alert ("* buttontStyle data type is wrong");
					
				    prevBttnDiv.removeClass('jcarousel-prev-horizontal-light');
				    nextBttnDiv.removeClass('jcarousel-next-horizontal-light');
					
					prevBttnDiv.addClass('jcarousel-prev-horizontal-dark');
					nextBttnDiv.addClass('jcarousel-next-horizontal-dark');
				}

					
				  // The rounded border around div (always set to zero dont display)
				   carouselDiv.css({'border':'0px solid black','background':'none','color': MYwidgetTextColor } );
				 //$('#mycarousel2').parent().parent().css('padding-left',30) ;
				 //$('#mycarousel2').parent().parent().css('padding-top',50)
				 
				 
				  
				 
				 //Begin table Properties
				  // *table background color Made redundant  
				 tblParent.attr('bgcolor',   WidgetSettings['widgetBgColor'] );
				 tblParent.find('tr:eq(1)').find('td').css({'background-color':  WidgetSettings['widgetBgColor'] });
				 
				 tblParent.find('td#viraltableCell').css({'background-color':  WidgetSettings['widgetBgColor'] });
				 
				  // Header background color
				 //   note in IE  Im purposely redundant here, bgcolor not supp in IE 7 for TR so I set in TD
			     tblParent.find('tr:eq(0)').attr('bgcolor',  WidgetSettings['headBgColor'] );
				 tblParent.find('tr:eq(0)').find('td').css({'background-color':    WidgetSettings['headBgColor'] });
				 
				 //  * Header font color,family
				 //tblParent.find('tr:eq(0)').css({'color':    WidgetSettings['headFontColor'] });
				
				  
				 // Table Border (always on), if no value for color then remove border
				 $brdcolor =    WidgetSettings['widgetBorderColor'] ;
				 
				 //console.log("initwidget() $brdcolor: " + $brdcolor +  " " + $brdcolor.length);
				 
				 ($brdcolor.length < 1) ? bordPx = 0 : bordPx = 2 ;
			 	  
				 tblParent.css( {'border-spacing': '0px' ,'border-collapse': 'separate',
					              'border-left':'solid ' + bordPx + 'px ' + $brdcolor ,
								 'border-top':'solid ' + bordPx + 'px ' + $brdcolor ,
								 'border-right':'solid ' + bordPx + 'px ' + $brdcolor ,
								 'border-bottom':'solid ' + bordPx + 'px ' + $brdcolor } );
				 
				 //SHOW HEADER TEXT OR IMAGE
				 
				 WidgetHeadDIV =  tblParent.find('tr:eq(0)').find('td').find('div#widgetHead');
			 
				 
				 if (WidgetSettings['headType'] == "img"){
					  
					    if ( WidgetSettings['headImgUrl'].length > 0 ) {
					    	
					    	urlStr = WidgetSettings['headImgUrl']
					 	    urlStr  =   urlStr.replace(/^\s+/g,'');
						    urlStr  =   urlStr.replace(/^http\:\/\//g,'');   
						   
						   
						    //console.log('setting img background', WidgetSettings['headImgUrl']);	
						   tblParent.find('tr:eq(0)').attr('style', "background : transparent url(http://" + urlStr + ") scroll 0 0 !important; background-repeat: repeat-x");
						   tblParent.find('tr:eq(0)').find('td').css({'background-color':   "" });
					    }
			     }else{
					   //console.log("removeClass");
					   tblParent.find('tr:eq(0)').css('background',"");
					    WidgetSettings['headImgUrl'] ="";
					   //tblParent.find('tr:eq(0)').removeClass();
				 }
					
					//Header Text
					 
					  WidgetHeadDIV.text(  WidgetSettings['headText']) ;
					  
					  //Header Text : Left Margin  of span tag for Header
					  WidgetHeadDIV.css({'font-family':  WidgetSettings['headFontFamily'],
										  'color': WidgetSettings['headFontColor'] } )
					 
 				 
				 
				 //Show Viral Link? 
				 VirLInkDiv =   tblParent.find('div#virLink');
				 
				 if (WidgetSettings['enableViral'] =="true") {
					
					     //console.log("show viral");
						 VirLInkDiv.css( {'font-family':  WidgetSettings['headFontFamily'] });
						 
						 
						 VirLInkDiv.show();
					 
				 }else{
					       //console.log("hide viral");
						   VirLInkDiv.css( { "display" : "none"} );
					 
				 }
				 
				 // set Tool Tip CSS
		 
				   
			      $("div#tooltip").css( { "background-color" : WidgetSettings['hoverBgColor'] ,
										  "border": "1px solid " + WidgetSettings['hoverBorderColor'],
										  "color": WidgetSettings['hovertextColor'],
										  "position": "absolute",
										  "z-index": "3000",
										  "padding": "15px",
										  "opacity": "0.95",
										  "font-family":"Arial,Verdana,Helvetica,sans-serif",
										  "font-size":"11px",
	                                      "height":"120px",
				                          "overflow":"hidden",
										  "text-align":"left",
										  "width":"250px",
										  "margin":"0"
										 } );
				  
				  
				  
				  
				  
				  							  
							  
				  
				  // Scroll to first postion, this is here so we can get an acurate index of the last
                  // item visible , otherwise it returns a false on upon loading items due to the 
                 // fact that its based the defualt width setting
   
				  $myCarousel.scroll(1);
				  
								 
	   }
				   
				   
				   
			 
 
 });


   //-------------------------------------------------------------------------------------------------
   
$.extend({ 
       
	   loadproducts:
	   
	    function LoadProducts(){
	          
	         //Set properties and configuration options and Loads Product DATA
              jQuery('#mycarousel2').jcarousel({
											   
              itemLoadCallback     :  mycarousel_itemLoadCallback, 
			  itemLastInCallback:  mycarousel_itemLastInCallback
       });
	
	
   }
    
  
});

     //-------------------------------------------------------------------------------------------------
    
	 
 

	// Will be moved out for JSP implmentation will get popluated by JSP
	 //$WidgetType = "ad"; // possible ("content"|"ad") 
	 
	 // Not used in implementation now JSP populates widget UL
	//var $DataURL       =  'dynamic_ajaxJSON.txt?';
	//var $linkText1      =  '';
	//var $linkText2      =  '';
    $myCarousel       =   null ;
	
	// this may be used for tracking in future
    //myLastItemVisible   =  '';
	 

	$adWidthMin =300;
	$adWithMax = 700;
	
   // settings list  for the widget, this gets moved out of here
   // for JSP inplementation,it  gets popluted by JSP
 
   //   options for    Buttontype : light|dark"
   //  headType    : img|html"
   //  enableViral  : true|false
  
  
 
							  
						  
							  
							  
 
  $.loadproducts();
   
   //$.InitWidget();
 
  // Events (viral Link)
   $('div#virLink a').bind("click", ToggleViralCode);
   
   // Scroll to first postion, this is here so we can get an acurate index of the last
   // item visible , otherwise it returns a false on upon loading items due to the 
   // fact that its based the defualt width setting
    // $myCarousel.scroll(1);

 

  
  
 
   
  //==========================================================================================
   function ToggleViralCode(){
	    
		//console.log ("ToggleViralCode()");
		
	   MyWidgeTable = $(this).parent().parent().parent().parent().parent().parent();
	   
	   curStyle = MyWidgeTable.find("td#viraltableCell").attr('style')
	   curStyle == undefined ? curStyle ="" : curStyle=curStyle ;
	    
		//console.log('curStyle',curStyle  );
		
		if ( curStyle.indexOf('none') >0){
				w =  MyWidgeTable.find('tr:eq(1)').find('div.jcarousel-clip-horizontal').width() ;
				 
			    MyWidgeTable.find('input[name*="viralcode"]').width(w-100);
				//MyWidgeTable.find("td#viraltableCell").show();
			    MyWidgeTable.find("td#viraltableCell").css( { "display" : "block"} );
	    }else{
			    
			    MyWidgeTable.find("td#viraltableCell").css({"display":"none"});

		}
	   
   }
  
   //==========================================================================================
   
   
     function mycarousel_itemLastInCallback(carousel, item, idx, state) {
         
		 // console.log('** mycarousel_itemLastInCallbac()  # ' + idx  );//DEBUG
	 
		 
    };
	
  //==========================================================================================
 
	
	function mycarousel_itemLoadCallback(carousel, state)
     {
	   
		// Since we get all URLs in one file, we simply add all items
		// at once and set the size accordingly.
		if (state != 'init')
		return;
		
		//alert ("Calling getJson");
		
         /*
			$.getJSON($DataURL , function(data){  
			
			 response = {values: [],count: 0};
			 // Now start cycling through our array of Flickr photo details  
			 $.each(data.components.items, function(i,item){  
				   //console.log('item',i , item);
					 response.count++;
					 var tmp = new Array();
					 tmp[0] = item.productName
					 tmp[1] = item.imageURL
					 tmp[2] = item.browseInsideURL
					 tmp[3] = item.addToCart
					 
					 response.values[i]= tmp;
					 
					 //console.log(i, tmp);
			
			   });  
			   
			   //console.log('carousel.last',carousel.last);
				mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, response.values);
			
		   }); 
		*/
		  // console.log("** mycarousel_itemLoadCallback()");
		  
		  if( $WidgetType == "content"){ // possible ("content"
		     
			 setUpToolTip();
		   }
		   
		   // This gobal is reference to widget object,gets used in initWidget
		   $myCarousel = carousel;
		   
		   
		   
			
			
		 
		   $.InitWidget();
		   
			/*  //Check all images in Carousel to see if the loaded, if not load no image graphic
		   setTimeout(function() {
				$('img.prodthumbImg').each(function(){
			         //console.log( $(this), $(this).attr('src'), $(this)[0].naturalWidth );
					if ($(this)[0].width ==0){
					   $(this).attr('src',"http://widget.symtio.com/img/carousel/noImage.jpg");
					}
			    }) 
		  }, 100); 
         */
			
		    
		//carousel.add(i+1, Itm)
		
	 
	 
     };
	 
     //-------------------------------------------------------------------------------------------------
	 function mycarousel_itemAddCallback(carousel, first, last, data)
	 {
		 
		 //console.log('mycarousel_itemAddCallback data:',data);//debug
	 
		for (i = 0; i < data.length; i++) {
		     currRecord = data[i];
			  // wrapp data in html and add to carousel
			  for (x = 0; x < currRecord.length;x++){
			     var Itm  =  getItemHTML1(currRecord[0],currRecord[1]) + getItemHTML2(currRecord[2]) + getItemHTML3(currRecord[3]) ;
				 carousel.add(i+1, Itm);
			}
		}
	 
	 
		carousel.size(data.length-1);
	 	
	   
	    

		
		 setUpToolTip();
		
	};
	
	   //-------------------------------------------------------------------------------------------------
	    // Format HTML for carousel List
	function getItemHTML1(title,url)
    {
	      
		  htm    = '<span class="data_Title" style="display:none"><strong>' + title + '</strong></span>';
		  htm    += '<span class="data_Auth" style="display:none">' + "Tom Smith" + '</span>';
		  htm    += '<span class="data_Desc" style="display:none">' + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque augue dui, mollis at dignissim ac, pulvinar id sem. Nulla porttitor neque iaculis dui fringilla ac cursus elit luctus. Aliquam hendrerit fringilla metus at tempor. Mauris interdum aliquet elementum. Nullam facilisis augue vel tortor aliquet dignissim. Donec aliquam venenatis laoreet. Quisque molestie lectus quis neque bibendum eget interdum quam laoreet." + '</span>';
		  
		  htm    +='<img class="prodthumbImg"  src="' + url + '" />';
		   
		  return htm;
    };
	
	   //-------------------------------------------------------------------------------------------------
	
	function getItemHTML2(url)
    {
           return '<a  class="smll" href="' + url + '">' + $linkText1 + '</a>';
    };
	   //-------------------------------------------------------------------------------------------------
	function getItemHTML3(url)
    {
           return '<br><a class="smll" href="' + url + '">' + $linkText2 + '</a>';
    };
	
	//-------------------------------------------------------------------------------------------------
	
	  MouseX=MouseY=0;
	
	 $().mousemove(function(e){
      MouseX = e.pageX ;
	  MouseY = e.pageY ;
	   //console.log(MouseX,MouseY);
     });
	 
	
   //-------------------------------------------------------------------------------------------------
   function setUpToolTip(){
	   
	 //console.log("setUpToolTip()");
	  
   	  $('img.prodthumbImg').tooltip({ 
										showURL: false ,
										track: false,delay:900,fade: 250 , fixPNG: true ,
										bodyHandler: function() { 
										
										 
										         //console.log ("toolTip rollover");
													 
							                     $html     =   $(this).parent().parent();
												 $Tit      =  $html.find('span.data_Title').text();
												 $Aut      =  $html.find('span.data_Auth').text();
												 $Des      =  $html.find('span.data_Desc').text();
									 			 
								 
												 //console.log ("toolTip rollover", $html.html());
												 
													// Set the position manually based on Hover Items Position, and offset
												 	Thumb_Pos   =  $(this).offset() ;
													Thumb_Width =  $(this).width();
													
													//get with of the widget Holder
													$parentHolder = $html.parent().parent().parent().parent().parent().find('div.jcarousel-container-horizontal');
													 
													//console.log ($parentHolder)
													 //Begin Calculate the Direction of the tool tip, if the right of the current thumb is
													 // greater than the middle of holder Div + the width of the current thumb  rolled over then , draw
													 // tool tip to the left of the thumbnail image
													 
													HolderWidth  =  $parentHolder.width();
													
													HolderMiddle_X = ($parentHolder.offset().left + HolderWidth/2) ;
													
													ThreshHold     = HolderMiddle_X + Thumb_Width ;
													
													thumbDelta_X  =  Thumb_Pos.left + Thumb_Width  ;
											   
												   (thumbDelta_X > ThreshHold) ? direction = -1 : direction = 1;
												   ( direction  > 0) ? leftOffset = 0 : leftOffset =$("div#tooltip").width()/2 + (Thumb_Width/2);
												   ( direction  > 0) ? additionalOffset = 0 : additionalOffset = -32; 
											 
											     
												   
												   newLeft    =   ( (Thumb_Pos.left  + (direction *  Thumb_Width  ) ) - leftOffset + additionalOffset)  ;
												   newTop     =  Thumb_Pos.top;  
												   
												   //console.log( newLeft,newTop );
												   
													
												     $("div#tooltip").css( { "left": newLeft + "px", "top":newTop + "px" } );

													 return ( "<span style='font-size:13px;color:" + MYtitleTextColor + "'><strong>" +$Tit + "</strong></span><br/><i>by " + $Aut +"</i><br /><br />"   + "<div style='border:0px black solid;height:82px;overflow:hidden;line-height:14px'>" + $Des + "</div>"   );
													
												}  
																 
								  });
	  

    
   }
	
});