var MPKitchen = {};

/*
This will get any link with the class 'mpk' and add the click event to each.
*/
MPKitchen.initMPK = function() {

    MPKitchen.links = $('.mpk');

    MPKitchen.links.css('cursor', 'pointer');
    MPKitchen.clearlinks = $('.clear_mpk');

    MPKitchen.budget_radios = $('.brr');
    MPKitchen.submit_basics = $('#sbmt_basics');


    // Select floorplan/shape properties
    MPKitchen.roomsize = false;
    MPKitchen.shape_holder = $('#floorplan_block_holder');
    MPKitchen.pick_shape = $('.pick_shape');
    MPKitchen.showidea = $('.showidea');
    MPKitchen.shape_link = false;
    MPKitchen.floorplan_id = false;
    MPKitchen.floorplan_title = false;
    MPKitchen.floorplan_sqm = false;
    MPKitchen.floorplan_sqm_min = false;
    MPKitchen.floorplan_sqm_max = false;
    MPKitchen.floorplan_response = $('#floorplan_response');
    MPKitchen.floorplan_dimensions = $('#floorplan_dimensions');
    MPKitchen.floorplan_dimensions_intro = $('#floorplan_dimensions_intro');
    MPKitchen.floorplan_dimensions_outer = $('#fpi_step1');
    
    MPKitchen.floorplan_ideas_outer = $('#fpi_step2');
    MPKitchen.floorplan_full_dims_outer = $('#fpi_step3');
    
    MPKitchen.floorplan_idea_id = false;
    
    MPKitchen.floorplan_dimension_links = false;
    MPKitchen.floorplan_id_hidden = $('#current_floorplan_id');
    MPKitchen.floorplan_ideas_ids = $('#current_floorplan_idea_ids');
    MPKitchen.floorplan_title_hidden = $('#current_floorplan_title');
  
    MPKitchen.floorplan_add_full_dims = $('#add-fulldims');
    MPKitchen.floorplan_save_full_dims = $('#sbmt_dims');
  
    MPKitchen.form_postcode = $('#form_designer');
    MPKitchen.submit_postcode = $('#sbmt_postcode');
    MPKitchen.input_postcode = $('#fd_postcode');
  
    
    if(MPKitchen.form_postcode && MPKitchen.submit_postcode && MPKitchen.input_postcode) {
      MPKitchen.submit_postcode.livequery('click', function(event) {
        var postcode = MPKitchen.input_postcode.val();
        if(!postcode) {
          UserMessage.Message('Error', 'Please enter your postcode');
          return false;
        }      
        MPKitchen.form_postcode.submit();
        return true;
      });
    }


    // Add to My Perfect Kitchen Links
    $('.mpk').livequery('click', function(e) {
           
_gaq.push(['_trackEvent', 'My Perfect Kitchen', 'Add', this.rel]);

        e.preventDefault();
            
        var mpkRelId = this.rel;
        if (mpkRelId && mpkRelId !== "") {

            // Store these against the object so we can restore them after the ajax request.
            var mpp = mpkRelId.split(':');
            if (mpp && mpp.length == 2) {

                var rel_id = mpp[0];
                var rel_tid = mpp[1];

                if (rel_id && rel_tid) {

                    MPKitchen.current = $(this);
                    MPKitchen.current_linkcontent = $(this).text();

                    $(this).text('Please wait...');

                    MPKitchen.addToMyPerfectKitchen(rel_id, rel_tid);
                    return false;
                }
                return false;
            }
        }
        return false;
    });




    if (MPKitchen.pick_shape) {
    MPKitchen.floorplan_save_full_dims.livequery('click', function(event) {
            
      event.preventDefault();

            var fm = $('#frm_editlayout');
            var fid = MPKitchen.floorplan_id;
            if (fm && fid) {
                var par = fm.serialize();
                if (par) {
                    $.ajax({
                        url: "/my-perfect-kitchen/layout-ideas-ajax.html?editLayoutDimensions=1&fid="+fid+"&returnideas=1&" + par,
                        context: document.body,
                        success: function(data) {
                          if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false; }
                          
                          MPKitchen.updateProgressPanel();
                          
                            var jsondata = jQuery.parseJSON(data);
                        if(jsondata) {
                          UserMessage.Message(jsondata.status, jsondata.message);

                        var txt = "";                      
                        if (jsondata.status == 'success' && jsondata.error == false) {                      
                          MPKitchen.floorplan_dimensions_outer.addClass('hide');
                          MPKitchen.shape_holder.addClass('hide');
                          MPKitchen.floorplan_ideas_outer.removeClass('hide');
                          MPKitchen.floorplan_full_dims_outer.empty().addClass('hide');
                        
                          if (jsondata.additional && jsondata.additional.length) {
                            
                            $(jsondata.additional).each(function(ind) {
                              txt += jsondata.additional[ind];
                            });
                            
                          } else {
                            txt += "No layout ideas were found that match your criteria.";
                          }
                          
                          if(jsondata.mpk && jsondata.mpk.roomsize) {
                            var rsize = (jsondata.mpk.roomsize) ? jsondata.mpk.roomsize : false;
                            if(rsize) {
                          $('.roomsize_updater').html(rsize);
                          $('#lnk_rsize').removeClass('hide');
                            }  
                          }
                        }
                        MPKitchen.floorplan_ideas_outer.html(txt);
                        }
                        }
                    });
                }
            }

      return false;
    });
    

    // Button that user clicks to add manual room dimensions.
    MPKitchen.floorplan_add_full_dims.livequery('click', function(event) {
                      
            $.ajax({
                url: "/my-perfect-kitchen/dimensions-ajax.html?editDimensions=1&lid=" + MPKitchen.floorplan_id,
                context: document.body,
                success: function(data) {
                  
                  if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false; }
                  
                  MPKitchen.updateProgressPanel();
                  
                    var jsondata = jQuery.parseJSON(data);
                    if(jsondata) {
                    
                      MPKitchen.floorplan_full_dims_outer.empty();
                    
                      // UserMessage.Message(jsondata.status, jsondata.message);
                      if(jsondata.additional && jsondata.additional.length) {
 
                        var imgEl = $(document.createElement('img'));
                        imgEl.attr('src', '/assets/images/mpk/floorplan'+ MPKitchen.floorplan_id +'_main.png?r=1');
                        imgEl.attr('class', 'dims_inp_img');
                      
                        MPKitchen.floorplan_full_dims_outer.append(imgEl);
                      
                        var floatEl = $(document.createElement('div'));
                        floatEl.attr('id', 'dims_inp_holder');
                      
                        MPKitchen.floorplan_full_dims_outer.append(floatEl);
                      
                        $(jsondata.additional).each(function(ind) {
                          
                          var dat = jsondata.additional[ind];
                          
                          var i = dat.id;
                          var na = dat.title; 
                          if(i && na) {
                          
                            var rowEl = $(document.createElement('div'));
                            rowEl.attr('class', 'input_row');
                          
                            floatEl.append(rowEl);
                          
                            var labelEl = $(document.createElement('label'));
                            labelEl.attr('for', 'dim_' + i);
                            labelEl.html(na + " ");
                            
                            rowEl.append(labelEl);
                          
                            var newEl = $(document.createElement('input'));
                            
                            newEl.attr('type', 'text');
                            newEl.attr('name', 'dims['+ i +']');
                            newEl.attr('id', 'dim_' + i);
                            if(jsondata.mpk && jsondata.mpk.dimensions && jsondata.mpk.dimensions[i]) {
                              newEl.attr('value', jsondata.mpk.dimensions[i]);
                            }
                            newEl.attr('class', 'dim_inp');
                            
                            rowEl.append(newEl);
                            
                          }
                        });
                        
                        var subEl = $(document.createElement('input'));
                    
                      subEl.attr('type', 'image');
subEl.attr('src', '/assets/images/mpk/layout_save_button.png');
                      subEl.attr('id', 'sbmt_dims');
                      subEl.attr('value', 'Save');
                      subEl.attr('class', 'sbmt');
                      
                      floatEl.append(subEl);
                        
                      }
                    }
                    
          MPKitchen.floorplan_dimensions_outer.addClass('hide');
          MPKitchen.shape_holder.removeClass('hide');
          MPKitchen.floorplan_ideas_outer.addClass('hide');
          MPKitchen.floorplan_full_dims_outer.removeClass('hide');
          $('.input_row').append('mm');
                    
                }
            });

      
      return false;    
    });




    $('.init_layout_dims').livequery('click', function(event) {
      
      // console.log('remove hide: ');
      // console.log(MPKitchen.floorplan_dimensions_outer);      
      MPKitchen.floorplan_dimensions_outer.removeClass('hide');
      
      // console.log('remove hide: ');
      //onsole.log(MPKitchen.shape_holder);
      MPKitchen.shape_holder.removeClass('hide');
      
      // console.log('add hide: ');
      // console.log(MPKitchen.floorplan_ideas_outer);
      MPKitchen.floorplan_ideas_outer.addClass('hide');
      
      
      // console.log('add hide: ');
      // console.log(MPKitchen.floorplan_full_dims_outer);
      MPKitchen.floorplan_full_dims_outer.addClass('hide');
      MPKitchen.floorplan_full_dims_outer.empty();
      MPKitchen.floorplan_full_dims_outer.removeClass('hide');
      
      $('#fpi_step4').addClass('hide');
            
      
      return false;    
    });

  
  
  
    // Simple slider for layout ideas
    $('#slider_buttons a').livequery('click', function(event) {
      var myrel = $(this).attr('rel');
      if(myrel) {
        var myrel_parts = myrel.split(':');
        if(myrel_parts && myrel_parts.length == 2) {
          
          var integer = myrel_parts[1];          
          MPKitchen.floorplan_idea_id = myrel_parts[0];
          
          $('#slider_inner').animate({'margin-left':-480*(parseInt(integer)-1)})
          $('#slider_buttons a').each(function(){
          $(this).removeClass('active');
            if($(this).hasClass('button'+integer)){
              $(this).addClass('active')}
          });
          return false;
        }
      }
      return true;
    });
  
  
  
  
    
        $('a.select_dimensions').livequery('click', function(event) {
        
          // console.log('HERE');
        
            var rel_sqm = $(this).attr('rel');
            if(rel_sqm) {
            
              if(rel_sqm !=='') {

                var floorplanId = MPKitchen.floorplan_id;
              
              var myurl = "/my-perfect-kitchen/layout-ideas-ajax.html?editLayoutDimensions=1&returnideas=1&fid=" + floorplanId;
              myurl += "&roomsize=" + rel_sqm;
                            
              $.ajax({
                  url: myurl,
                  context: document.body,
                  success: function(data) {
                  
                    if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false; }
                  
                      var jsondata = jQuery.parseJSON(data);
                      if(jsondata) {
                        UserMessage.Message(jsondata.status, jsondata.message);
                        
                        var txt = "";
                        
                        MPKitchen.updateProgressPanel();
                        
                        if (jsondata.status == 'success' && jsondata.error == false) {
                        
                      MPKitchen.roomsize = rel_sqm;
                      
                      $('.roomsize_updater').html(rel_sqm);
                      $('#lnk_rsize').removeClass('hide');
                        
                          MPKitchen.floorplan_dimensions_outer.addClass('hide');
                          MPKitchen.shape_holder.addClass('hide');
                          MPKitchen.floorplan_ideas_outer.removeClass('hide');
                          MPKitchen.floorplan_full_dims_outer.empty().addClass('hide');
                        
                          if (jsondata.additional && jsondata.additional.length) {
                            
                            $(jsondata.additional).each(function(ind) {
                              txt += jsondata.additional[ind];
                            });
                          }
                          
                        }
                        MPKitchen.floorplan_ideas_outer.html(txt);
                      }

                  }
              });
                
              }
              return false;
            }
            return true;
        });
        

        var doIdeasRequest = function(shapeId,shapeTitle) {
        
          // console.log('doIdeasRequest');
        
            $.ajax({
                url: "/my-perfect-kitchen/layoutajax.html?editLayout=1&fpid=" + shapeId,
                context: document.body,
                success: function(data) {

          if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false; }

          MPKitchen.updateProgressPanel();

                    var jsondata = jQuery.parseJSON(data);
                    if(jsondata) {
                      UserMessage.Message(jsondata.status, jsondata.message);
                    }
                    if (jsondata.status == 'success' && jsondata.error == false) {

                        $(MPKitchen.shape_link).addClass('fp_active');
                        MPKitchen.floorplan_id = shapeId;
                        if(shapeTitle) {
                          MPKitchen.floorplan_title = shapeTitle;
                          $('.shape_updater').html(shapeTitle);
                          $('#lnk_rshape').removeClass('hide');
                          
                        }
                        if (MPKitchen.floorplan_id_hidden) {
                            MPKitchen.floorplan_id_hidden.val(shapeId);
                        }

                        // Now show the distinct sqm links for this shape's floorplan ideas.
                        if (MPKitchen.floorplan_response) {
                            MPKitchen.floorplan_response.removeClass('hide');
                            MPKitchen.floorplan_dimensions_outer.removeClass('hide');
                            MPKitchen.floorplan_ideas_outer.html("&nbsp;");
                            if (jsondata.additional && jsondata.additional.length) {

var tx = "<h2>Step 2: Do you want to add the room dimensions?</h2>";
                                tx += "<p>The dimensions will be added to your downloadable wishlist that you can print out and provide to your designer.</p>";
                                tx += "<a href='' id='add-fulldims' class='select_dimensions nicebutton'>Yes, I'll add them now</a>";
                                tx += "";
                                tx += "<h3>No, just show me layout ideas - my kitchen is...</h3>";
                                tx += "<div id='ideas_holder'>";

                                $(jsondata.additional).each(function(el) {
                                    var ref = jsondata.additional[el].value;

                                    if (ref && ref !== '') {                                        
                                        // livequery will add the click events to these.
                                        var link = "/my-perfect-kitchen/layout.html?fid=" + MPKitchen.floorplan_id;
                                        link += "&roomsize=" + ref;
                                        
                                        tx += "<a href='" + link + "' class='select_dimensions nicebutton' rel='" + ref + "' id='sd_" + el + "'>" + ref + "</a>";
                                    }
                                });

                                tx += "</div>";

                                MPKitchen.floorplan_dimensions.html(tx);
                                MPKitchen.floorplan_dimensions.removeClass('hide');
                            } else {
                                MPKitchen.floorplan_dimensions.html('None Found');
                                MPKitchen.floorplan_dimensions.removeClass('hide');
                            }
                        }

                    }

                }
            });

        }





    stored_btns = false;
        var getIdeaById = function(resourceid) {
        
          // console.log('getIdeaById ' + resourceid);
          if(!resourceid) {
            return false;
          }
        
          
            $.ajax({
            
                url: "/my-perfect-kitchen/layoutajax.html?editLayout=1&rid=" + resourceid,
                context: document.body,
                success: function(data) {
                
                  // console.log('Returned getIdeaById()');
                  // console.log(data);

          MPKitchen.floorplan_response.addClass('hide');

          if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false; }
          MPKitchen.updateProgressPanel();

          var jsondata = jQuery.parseJSON(data);
          if (jsondata.status == 'success' && jsondata.error == false) {
            if(jsondata.additional) {
              var tx = "";
              tx += jsondata.additional;
              // MPKitchen.floorplan_dimensions.html(tx);
              $('#fpi_step4').html(tx);
              MPKitchen.floorplan_ideas_outer.removeClass('hide');
              $('#fpi_step4').removeClass('hide');
              $('#fpi_step1').addClass('hide');
              // stored_btns = MPKitchen.floorplan_dimensions_intro.html();
              MPKitchen.floorplan_response.removeClass('hide');
              MPKitchen.shape_holder.addClass('hide');
            }
          }
                }
            });
            

        }


        // If we have one selected - grab the ideas automatically.
        var hasval = MPKitchen.floorplan_ideas_ids.val();
        if(MPKitchen.floorplan_ideas_ids && hasval && hasval == 1) {          
      MPKitchen.floorplan_response.removeClass('hide');
        } 
        
        if (MPKitchen.floorplan_id_hidden) {          
            var current_floorplan_id = MPKitchen.floorplan_id_hidden.val();
            var current_floorplan_title = MPKitchen.floorplan_title_hidden.val();
            if (current_floorplan_id && current_floorplan_id !== '' && current_floorplan_id !== 0) {
                doIdeasRequest(current_floorplan_id,current_floorplan_title);
            }
        }

        // Use the same function for the click events.
        MPKitchen.pick_shape.click(function(e) {
            var ps = $(this).attr('rel').split(':');
            var shapeId = false;
            if(ps && ps.length == 2) {
              shapeId = ps[0];
              shapeTitle = ps[1];
            }
            // var shapeId = $(this).attr('rel');
            
            if (shapeId) {

                MPKitchen.shape_link = this;

                MPKitchen.pick_shape.removeClass('fp_active');

                MPKitchen.floorplan_response.addClass('hide');

                MPKitchen.floorplan_dimensions.addClass('hide');
                MPKitchen.floorplan_full_dims_outer.empty().addClass('hide');
                
                MPKitchen.floorplan_dimensions.html('&nbsp;');

                doIdeasRequest(shapeId,shapeTitle);
                return false;
            }
            return true;
        });
        
        
        
        
        // Use the same function for the click events.
        
        /*
        MPKitchen.showidea.click(function(e) {
            var rid = $(this).attr('rel');
            getIdeaById(rid);
            return false;
        });
        
		*/        
        
    }
    // End - Select floorplan/shape











    // MPK Budget Range Radios
    /*
    MPKitchen.budget_radios.click(function(e) {
        var budgetId = $(this).val();
        $.ajax({
            url: "/my-perfect-kitchen/budgetajax.html?editBudget=1&bri=" + budgetId,
            context: document.body,
            success: function(data) {
              if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false; }
              
                var jsondata = jQuery.parseJSON(data);
                if(jsondata) {
                  UserMessage.Message(jsondata.status, jsondata.message);
                }
            }
        });
    });
    */
    // End MPK Budget Range Radios



    // Clear MPK links
    if (MPKitchen.clearlinks) {
        MPKitchen.clearlinks.click(function(e) {
            return MPKitchen.clearMyPerfectKitchen();
        });
    }
    // End Clear MPK links



    // ! Basics = Lifestyle
    if (MPKitchen.submit_basics) {
        MPKitchen.submit_basics.click(function(e) {
            // get the form values...
            var fm = $('#frm_editlifestyle');
            if (fm) {
                var par = fm.serialize();
                if (par) {
                    $.ajax({
                        url: "/my-perfect-kitchen/lifestyleajax.html?editLifestyle=1&" + par,
                        context: document.body,
                        success: function(data) {
                          
                          if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false; }
                          
                            var jsondata = jQuery.parseJSON(data);
                        if(jsondata) {
                          UserMessage.Message(jsondata.status, jsondata.message);
                        }
                        
                        MPKitchen.updateProgressPanel();
                        }
                    });
                }
            }
            return false;
        });
    }



	MPKitchen.updateProgressPanel=function() {
	var presp = $('#content-right');
	if(presp) {
		$.ajax({url: "/my-perfect-kitchen/progress-ajax.html",context: document.body,success:function(data){ 
			presp.html(data);}});
		}		

		var pbresp = $('#mpkprogresspercent');if(pbresp){
			$.ajax({
				url:"/my-perfect-kitchen/progress-blocks-ajax.html",
				context: document.body,
				success: function(data){
					// console.log(data);
					pbresp.html(data);
				}
			});
		}
	}



}










// Clear MPK function
MPKitchen.clearMyPerfectKitchen = function(id) {
    $.ajax({
        url: "/mpkrpc.html?sbt_clearmpk=1",
        context: document.body,
        success: function(data) {
            var ur = window.location.href;
            window.location.href = ur;
        }
    });
    return false;
}



/*
This is called when an MPK link is clicked.
It expects a resource ID to add to the users MPKitchen Object.
*/
MPKitchen.addToMyPerfectKitchen = function(id, tid) {

    if (!id || id == "" || !tid || tid == "") {
        return false;
    }

    $.ajax({
        url: "/mpkrpc.html?rid=" + id + "&rtid=" + tid,
        context: document.body,
        success: function(data) {

      // if(!data) { UserMessage.Message('Error', "Website error - please try again"); return false;}
      MPKitchen.updateProgressPanel();

            if (MPKitchen.current) {
                if (data == 1) {
                    MPKitchen.current.addClass("done");
                    
                     UserMessage.Message('Success', "Added to My Perfect Kitchen");
                    
                } else {
                    // Something went wrong - alert the user.
                    UserMessage.Message('Error', "Failed to add to 'My Perfect Kitchen'");
                }
                MPKitchen.current.text(MPKitchen.current_linkcontent);
            }
        }
    });

}






// Off we go...
$(document).ready(function() {
    MPKitchen.initMPK();
    
    $('#mpkchunkybuttons li').click(
    	function(){ 
    		chunklink = $(this).find('p.chunkylink a').attr("href");
    		window.location.href=chunklink;
    	}
    );
    
	
	// Key Retreival validation
    $('#sbmt_key').click(function(e) {
    	kinp = $('#mpkkey');
    	if(kinp) {
	    	var ckey = kinp.val();    	
	    	if(!ckey || ckey == "") {
	    		UserMessage.Message('Error', "Please enter your download key");
	    		e.preventDefault();
	    		return false;    	
	    	}
		    return true;
	    }   
    });
    
});
