$(document).ready(function(){

 /*Cufon.replace('#nav li a', {hover: true, fontFamily: 'Georgia'});
 Cufon.replace('.georgia', {hover: true, fontFamily: 'Georgia'});
 Cufon.replace('.heading', {hover: true, fontFamily: 'Georgia Bold Italic'});
 Cufon.replace('.georgia-italic', {hover: true, fontFamily: 'Georgia Italic'});
 Cufon.replace('.selectedTxt, .newList li a', {hover: true, fontFamily: 'Georgia Italic'});*/

 $('.featurebox:last').css('margin','0px');
 
 //initialize shadowbox
 Shadowbox.init({
    handleOversize:     "resize",
    continuous:         true,
    handleUnsupported:  "remove",
    autoplayMovies:     false
});

 /* ------------------------------- */
// Equal Heights
/* ------------------------------- */
function equalHeight(group) {
    tallest = 0;
    group.each(function() {
       thisHeight = $(this).height();
       if(thisHeight > tallest) {
        tallest = thisHeight;
      }
    });
    group.height(tallest);
}

equalHeight($(".col"));

// Navigation Hover
/* $('#nav li').hover(function(){
 var currentId = $(this).attr('id');
 //alert('#nav ' + currentId + ' div');
  $('#nav #' + currentId + ' div').addClass("rightcurve");
 },function() {
  var currentId = $(this).attr('id');
  $('#nav #' + currentId + ' div').removeClass("rightcurve");
 }); */


/*-------------------------------------- */
/* Navigation
/*-------------------------------------- */

//$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)
	$("ul#nav li a").hover(function() { //When trigger is clicked...
	
	  var currentId = $(this).parent().attr('id');
	  
	   
   if ( currentId != '' ) $('#nav #' + currentId + ' div').addClass("rightcurve");
  
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
		$(this).parent().hover(function() {
		}, function(){
		 
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});
	
  }, function(){
  
     var currentId = $(this).parent().attr('id');
     
     if ( currentId != '' ) $('#nav #' + currentId + ' div').removeClass("rightcurve");
     
  });
	
	$("ul#nav li ul.subnav li a").hover(function() { //When trigger is clicked...
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show();
		$(this).parent().find("ul.secondnav").slideDown('fast').show(); //Drop down the subnav on click
      
		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.secondnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
	  });
  });

/*-------------------------------------- */
/* Navigation
/*-------------------------------------- */

	
	//cool drop down
	
	if ( $('.cool-dropdown').length )
  {
	$('.cool-dropdown').sSelect().change(function(){
	
	var page = '';
  
   if ( $(this).val() != '' )
   {
   
   var id = $(this).attr('id');
   
      
   document.location.href = baseURL + 'categories/?cat='+$(this).val();
   
   }
   else
   {
   
    alert('Please select a value');
   
   }
  
  });
 }
 
 //trigger the shadowbox when the big img is clicked
 $("#bigimglink").click(function () { 
      $("a.clinks:first").click();
    });
    
    
    if ( $('#mockup').length )
  {  
    		var count_dropped_hits = 0;
    		
    					
				// Array Remove - By John Resig (MIT Licensed)
				Array.prototype.remove = function(from, to) {
				  var rest = this.slice((to || from) + 1 || this.length);
				  this.length = from < 0 ? this.length + from : from;
				  return this.push.apply(this, rest);
				};
				
				/*  remove an object from data */
				$('.remove',$('#tools')).live('click',function(){
					var $this = $(this);
					
					/* the element next to this is the input that stores the obj id */
					var objid = $this.next().val();
					
	
					/* remove the object from the sidebar */
					$this.parent().remove();
					/* ,from the picture */
					var divwrapper = $('#'+objid).parent().parent();
					
													
					$('#'+objid).remove();
					
									
				
					/* add again to the objects list */
					var image_elem 		= $this.parent().find('img');
					//var thumb_width 	= image_elem.attr('width');
					var thumb_width = '50px';
				//	var thumb_height 	= image_elem.attr('height');
				var thumb_height = 'auto';
					var thumb_src 		= image_elem.attr('src');
					
				divwrapper.find('.ui-wrapper').remove();
        				
			/*	$('<img/>',{
						id 			: 	objid,
						src			: 	thumb_src,
						width		:	thumb_width, 
						height		:	thumb_height,
						className	:	'ui-widget-content'
					}).appendTo(divwrapper).parent('.ui-wrapper').transformable('destroy'); */
                              
                    
          $('<div/>',{
								className	:	'ui-wrapper',
								html		:	'<img id="'+objid+'" width="50" class="ui-widget-content" src="'+thumb_src+'"></img>'
							}).appendTo(divwrapper);
							
							$('#'+objid).parent('.ui-wrapper').draggable({
                    revert	: 'invalid'
         
           });
                
					/* and unregister it - delete from object data */
					var index = exist_object(objid);
					data.images.remove(index);
					

				});
                
                /*  checks if an object was already registered */
                function exist_object(id){
                    for(var i = 0;i<data.images.length;++i){
                        if(data.images[i].id == id)
                            return i;
                    }
                    return -1;
                }
				
				/* triggered when stop resizing an object */
				function resizestop(event, ui) {
					//calculate and change values to obj (width and height)
					var $this 		= $(this);
					var objid		= $this.find('.ui-widget-content').attr('id');
					var objwidth 	= ui.size.width;
					var objheight 	= ui.size.height;
					
										
				/*	var tr=$this.getTransform();
					
					var objwidth = tr.scalex;
					
					var objheight = tr.scaley; */
					
						
								
					var index 		= exist_object(objid);
				
					if(index!=-1) { //if exists (it should!) update width and height
						data.images[index].width 	= $('#'+objid).width();
						data.images[index].height 	= $('#'+objid).height();
						data.images[index].order += 'z';
					}
        }
        
        /* triggered when stop dragging an object */
				function dragstop(event, ui) {
					//calculate and change values to obj (width and height)
					var $this 		= $(this);
					var objid		= $this.find('.ui-widget-content').attr('id');
					
															
					 var objtop		= ui.offset.top - $('#background').offset().top;
           var objleft		= ui.offset.left - $('#background').offset().left;
           
                           
         	var index 		= exist_object(objid);
				
					if(index!=-1) { //if exists (it should!) update left and top
						data.images[index].top 	= objtop;
						data.images[index].left 	= objleft;
						data.images[index].order += 'd';
					}
        }
        
				/* objects are resizable and draggable */
				
				$('#objects .ui-wrapper').draggable({
				
				   revert	: 'invalid'
                    
                }); 
				
				 $('#background').droppable({
                    accept	: '#objects div', /* accept only draggables from #objects */
                    drop	: function(event, ui) {
                        var $this 		= $(this);
                        
                        var uiobj = ui;
                        ++count_dropped_hits;
                      
                        
                        
						var draggable_elem = ui.draggable;
						
                      
            
            draggable_elem.draggable({
            
              stop : dragstop
                          
           
            });
						
																	
						draggable_elem.css('z-index',count_dropped_hits);
						
			
						/* object was dropped : register it */
						
						           				            
                        var objsrc 		= draggable_elem.find('.ui-widget-content').attr('src');
                        //var objwidth 	= parseFloat(draggable_elem.css('width'),10);
                        //var objheight 	= parseFloat(draggable_elem.css('height'),10);
                        
                        var trr;
                        //var skewx;
                        //var skewy;
                        
                       	
                        /* for top and left we decrease the top and left of the droppable element */
                        var objtop		= ui.offset.top - $this.offset().top;
                        var objleft		= ui.offset.left - $this.offset().left;
                        
                                                    
                                                             
                         var objid		= draggable_elem.find('.ui-widget-content').attr('id');
                        
                         var index 		= exist_object(objid);
                         
                         var objheight = $('#'+objid).height();
                         
                         var objwidth = $('#'+objid).width();
                         
                         
                         draggable_elem.resizable({
                        handles	: 'all',
                               
                   aspectRatio : true,
                   
					         stop	: resizestop,
					         
					         alsoResize: '#'+objid
                    
                });
                        
		                    		                    
		        				
                        if(index!=-1) 
                        { //if exists update top and left
                            data.images[index].top 	= objtop;
                            data.images[index].left = objleft;
                            //data.images[index].rotation = tr_rotation;
                            data.images[index].order += 'p';
                        } 
                        else 
                        {					
							/* register new one */
                            var newObject = { 
								'id' 		: objid,
                                'src' 		: objsrc,
                                'width' 	: objwidth,
                                'height' 	: objheight,
                                'top' 		: objtop,
                                'left' 		: objleft,
                                'rotation'  : trr,
                                'order'      : ''
                                //'skewx'     : skewx,
                                //'skewy'     : skewy
								                };
							
							/* add object to sidebar*/
							
							data.images.push(newObject);     
							
							$('<div/>',{
								className	:	'item'
							}).append(
								$('<div/>',{
									className	:	'thumb',
									html		:	'<img width="50" class="ui-widget-content" src="'+objsrc+'"></img>'
								})
							).append(
								$('<a/>',{
									className	:	'remove'
								})
							).append(
								$('<input/>',{
									type		:	'hidden',
									value		:	objid		// keeps track of which object is associated
								})
							).appendTo($('#tools'));
							
						//	newObject.rotation = tr_rotation;
							
					    draggable_elem.transformable( {
                    			rotateStop:  function(e,ui){
                          
                          var tr=$(this).getTransform();
                          
                          var o=$(this).tOffset();
                           
                                                 
                          newObject.rotation = tr.rotate;
                          
                          //newObject.skewx = tr.skewx;
                          
                          //newObject.skewy = tr.skewy;
                          
                          trr = tr.rotate;
                          
                          //skewx = tr.skewx;
                          
                          //skewy = tr.skewy;
                          
                          var objtop		= uiobj.offset.top - $('#background').offset().top;
                          
                          var objleft		= uiobj.offset.left - $('#background').offset().left;
                          
                                                 
                          var objid		= $(this).find('.ui-widget-content').attr('id');
                          
                          var index 		= exist_object(objid);
                          
                          	if(index!=-1) { //if exists (it should!) update width and height
					
					                    data.images[index].order += 'r';
					                    
					                    data.images[index].top 	= objtop;
						                  
                              data.images[index].left 	= objleft;
					                  }
                          
                          
                          
                                                  
                          },
                          
                          skewStop : function(e,ui){
                          
                          var tr=$(this).getTransform();
                          
                           newObject.rotation = tr.rotate; 
                                                 
                          //newObject.skewx = tr.skewx;
                          
                          //newObject.skewy = tr.skewy;
                          
                          trr = tr.rotate;
                          
                          //skewx = tr.skewx;
                          
                          //skewy = tr.skewy;
                          
                            
                          },
                          
                          scalable : false,
                          
                          skewable : false
		                    }); 
		                    
		               
					
		              }
		              
		             
                 }
                 
                 
                });
			
				/* User presses the download button */
                $('#submit').bind('click',function(){
                    var dataString  = JSON.stringify(data);
      
                    $('#jsondata').val(dataString);
					$('#jsonform').submit();
                });
                
                
         //uploadify
 $('#file_upload').uploadify({
    'uploader'  : baseURL+'web/uploadify/uploadify.swf',
    'script'    : baseURL+'uploadify.php?member='+folder,
    'cancelImg' : baseURL+'web/uploadify/cancel.png',
    'auto'      : true,
    'fileExt'     : '*.jpg;*.gif;*.png',
    'fileDesc'    : 'Image Files',
    'onComplete'  : function(event, ID, fileObj, response, data) {
     
     //add the image to the logos list if it doesn't exist
     
      
     var objsrc = baseURL + 'distributorlogos/member'+folder+'/'+fileObj.name;
     
      
     var objid = 'obj_'+response;
     
      var index 		= exist_object(objid);
      
      if ( index == -1)
      {
     
            
        			$('<div/>',{
								className	:	'obj_item',
								html		:	'<div class="ui-wrapper"><img id="obj_'+response+'" width="50" class="ui-widget-content" src="'+objsrc+'"></img></div>'
							}).appendTo($('#objects'));
              
            $('#'+objid).parent('.ui-wrapper').draggable({
                    revert	: 'invalid'
                    
                   
           });
          
           
      } 
    }
  });       
           
  }
  
  //uploadify logo for distributors
  if ( $('#uploaded_logo').length )
  {
  
 $('#logo_upload').uploadify({
    'uploader'  : baseURL+'web/uploadify/uploadify.swf',
    'script'    : baseURL+'uploadify_logo.php?member='+folder,
    'cancelImg' : baseURL+'web/uploadify/cancel.png',
    'auto'      : true,
    'fileExt'     : '*.jpg;*.gif;*.png',
    'fileDesc'    : 'Image Files',
    'onComplete'  : function(event, ID, fileObj, response, data) {
     
     //add the image to the logos list if it doesn't exist
     
      
     var objsrc = baseURL + 'distributorlogos/member'+folder+'/'+response;
     
          
     $("#uploaded_logo").attr('src', objsrc);      
  
    }
  });    
  }  
  
  //quote form
  if (  $('#myquoteform').length )
  {
  
   var units_changed = false;
   
   var arr = new Array("cost","price","setup","film","flashing");
   
     
   $("#cost,#colours,#flashing_colours,#panels,#setup,#film,#units,:radio,#markup,#repeat_print").change( function() 
   {
   
   units_changed = false;
   
   $(this).blur();
   
   var this_id = $(this).attr("id");
   
   if ( this_id == 'units' ) units_changed = true;
     
   var str = $("#frm").serialize();
    
    $.ajaxq ("ajaxqueue", 
    {
        url: baseURL+'getquote/?action=calculatequote&'+str,
        cache: false,
        success: function(json) {
        
        var obj = $.parseJSON( json );
        
        var fcost = parseFloat($("#flashing_colours").val() * $("#panels").val() * $("#flashingcost").val() * $("#units").val());
               
        var total_cost = parseFloat( obj['total_cost'] );
        
        //get the checked radio button val
        var rval = $("input[name=flashing_required]:checked").val();
        
        if ( rval == '1' )
        {
         total_cost = total_cost + fcost;
        
        }
        else
        {
        
         fcost = 0;
        
        }
        
        $("#total_cost").val( number_format(total_cost, 2, '.', '') );
        
        $("#price").val( number_format(obj['price'], 2, '.', '') );
        
        $("#flashing").val( number_format(fcost, 2, '.', '') );
        
        $("#setup").val( parseFloat( number_format(obj['setup'], 2, '.', '') ) );
        
        $("#film").val( parseFloat( number_format(obj['film'], 2, '.', '') ) );
        
        $("#colour").html( $("#colours").val()  );
        
        $("#custcolour").html( $("#colours").val()  );
        
        $("#panel").html( $("#panels").val()  );
        
        $("#custpanel").html( $("#panels").val()  );
        
        //apply markup if > 0
        if ( $("#markup").val() == ''  ) $("#markup").val(0);
        
        if ( isNaN( $("#markup").val() ) ) $("#markup").val(0);
        
        //copy the values to the customer quote form
        for ( var i=0; i < arr.length; i++)
        {
        
        
        
         if ( $("#markup").val() > 0 )
         {
         
           if ( arr[i] == "cost" || arr[i] == "price" || arr[i] == "setup" || arr[i] == "film" || arr[i] == "flashing" )
           {
           
            //apply markup
            var markup = parseFloat( $("#"+arr[i]).val() ) + (( parseFloat($("#"+arr[i]).val()) * parseFloat($("#markup").val()))/100);
            
                       
                        
            $("#cust"+arr[i]).val( number_format(markup, 2, '.', '') );
           
           }
           else
           {
           
            $("#cust"+arr[i]).val( $("#"+arr[i]).val()  );
           
           }
         
         
         }
         else
         {
         
         $("#cust"+arr[i]).val( $("#"+arr[i]).val()  );
         
         }
        
        }
        
        //do the customer total;
        calculate_cust_total();
        
        }
    });
  });
  
   
  }
  
  
   
  if (  $('#customerquoteform').length )
  {
  
     
     
   $("#custcost,#custprice,#custsetup,#custfilm,#custflashing").change( function() 
   {
   
  
    calculate_cust_total();
     
  });
  
   
  }
  
  
  function calculate_cust_total()
  {
  
   var cust_total_cost = 0;
  
   cust_total_cost = ((parseFloat( $("#custcost").val() ) + parseFloat( $("#custprice").val() )) * parseInt($('#units').val()) ) + parseFloat( $("#custsetup").val() ) + parseFloat( $("#custfilm").val() ) + parseFloat( $("#custflashing").val() );
   
     
   $("#custtotal_cost").val( number_format(cust_total_cost, 2, '.', '') );
  
  }
  
  
  //javascript equivalent of PHP's number_format function
function number_format (number, decimals, dec_point, thousands_sep) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
     
         
 
                  
    
 
});

