/*** Note: the strings[] JS array is located in main.inc.php ***/

 // Variables 
var radio_ordered_from = '';
var radio_product    = '';
var radio_color      = '';
var checkboxes_parts = {};
var global_timeout;
 
 // Functions
function onchange_country(selected_country, language_prefix) {
     // A valid country option has been selected
    if (selected_country != '') {
         // State field
        if (selected_country == 'usa') { field_enable('states_list'); } else { field_disable('states_list'); field_reset_select('states_list'); }
         // Ordered from fields
        update_retailers_list('retailers_list', selected_country, language_prefix);
        /*$('#retailers_radio .radio_button').removeClass('disabled');
        /*$('#retailers_radio .radio_button:first').click();*/
        field_enable('retailers_list');
        radio_ordered_from = 'Retailer';
         // Category field
        field_enable('parts_request_categories_list');
        
     // The dummy 'select a country' option has been selected
    } else {
         // Disable the state field
        field_disable('states_list'); field_reset_select('states_list');
         // Disabled and reset the ordered from fields
        field_disable('retailers_list'); field_reset_select('retailers_list');
        $('#retailers_radio .radio_button').addClass('disabled');
        toggle_radio('#retailers_radio', $('#retailers_radio .selected').attr('id'), 'uncheck');
        radio_ordered_from = '';
         // disable the category_field
        field_disable('parts_request_categories_list'); field_reset_select('parts_request_categories_list');
    }
}

function update_retailers_list(list_id, selected_country, language_prefix) {
    $.get('/', {'retailers_list':'1', 'country':selected_country, 'language-prefix':language_prefix},
        function(retailers) {
            //var options  = '<option value=""></option>';
			var options = '<option value="">'+$('#'+list_id+' option:first-child').html()+'</option>';
            var selected = '';
            for (i=0; i < retailers.length; i++) {
                options += '<option value="'+retailers[i]+'">'+retailers[i]+'</option>';
            }
            $('#'+list_id).html(options);
        }, 'json'
    )
}

function onclick_radio(radio_container, clicked_radio, custom_event) {
     // Check this button is not disabled and not currently selected
    if (!$('#'+clicked_radio).hasClass('disabled') && !$('#'+clicked_radio).hasClass('selected')) {
        toggle_radio(radio_container, clicked_radio, 'check');
         // Run the custom event, if one is set
        if (custom_event) { eval(custom_event); }
         // Return the value of the radio button, i.e the title value
        return ($('#'+clicked_radio).attr('title'));
    }
}

function toggle_radio(radio_container, radio_button, action) {
     // Check a radio button
    if (action == 'check') {
        toggle_radio(radio_container, $('#'+radio_container+' .selected').attr('id'), 'uncheck');
         // Check the clicked radio button
        $('#radio_button_dot').clone().prependTo('#'+radio_button);
         // The dot is preloaded with display:none, so we need to display:block the clone
        $('#'+radio_button+' img').css({'display':'block'});
         // Mark the clicked radio button as selected
        $('#'+radio_button).addClass('selected');
     
     // Uncheck a radio button
    } else if (action == 'uncheck') {
        $('#'+radio_button+' img').remove();
        $('#'+radio_button).removeClass('selected');
    }
}

function onclick_checkbox(checkbox_button, custom_event) {
    if (!$('#'+checkbox_button).hasClass('selected')) {
        toggle_checkbox(checkbox_button, 'check');
         // Run the custom event, if one is set
        if (custom_event) { eval(custom_event); }
         // Mark the clicked checkbox as selected
        $('#'+checkbox_button).addClass('selected');
         // Return the new status of the checkbox
        return true;
    } else {
        toggle_checkbox(checkbox_button, 'uncheck');
         // Run the custom event, if one is set
        if (custom_event) { eval(custom_event); }
         // Remove the selected label from the checkbox
        $('#'+checkbox_button).removeClass('selected');
         // Return the new status of the checkbox
        return false;
    }
}

function toggle_checkbox(checkbox_button, action) {
    if (action == 'check') {
         // Check the clicked checkbox
        $('#checkbox_button_vsign').clone().prependTo('#'+checkbox_button);
         // The v-sign is preloaded with display:none, so we need to display:block the clone
        $('#'+checkbox_button+' img').css({'display':'block'});
    } else if (action == 'uncheck') {
         // Uncheck the checkbox
        $('#'+checkbox_button+' img').remove();
    }
}

function toggle_details_fields(part_id) {
    var qty_field    = $('#qty_field_'+part_id);
    var reason_field = $('#reason_field_'+part_id);
    if (qty_field.attr('class') == 'disabled' && reason_field.attr('class') == 'disabled') {
        field_enable(qty_field.attr('id'));
        field_enable(reason_field.attr('id'));
    } else {
        field_disable(qty_field.attr('id'));
        field_reset_text(qty_field.attr('id'));
        field_disable(reason_field.attr('id'));
        field_reset_select(reason_field.attr('id'));
    }
}

/* ## */

/* // Adds the "go back" behavior to recnetly active tabs 
function step_tab_click_bind(step_number) {
     // Toggle the tab and display its relevant content container
    $('#step_'+step_number+'_off').click(
        function() {
            step_toggle_tab(step_number);
            $('.step_content').hide();
            $('#step_'+step_number+'_content').show();
            step_continue_click_bind(step_number);
        }
    ).css({'cursor':'pointer'});
}

function step_tab_click_unbind_all() {
    $('.p_tab_off').unbind('click').css({'cursor':'auto'});
}*/

function step_toggle_tab(step_number) {
    var tab_prefix = 'step_'+step_number+'_';
     // Toggle off all tabs
    $('#steps_container .p_tab_on').hide();
    $('#steps_container .p_tab_off').show();
     // Toggle on a specific tab if a step was passed
    if (step_number) {
        $('#'+tab_prefix+'off').hide();
        $('#'+tab_prefix+'on').show();
    }
}

function step_initiate(step_number, data) {
    $('#error_container').fadeOut();
     // Initiating step 1
    if (step_number == '1') {
		eval('step_'+step_number+'(\''+data+'\');');
	 // Initiating all other steps - validating first
    } else {
        var previous_step = Number(step_number) - 1;
        var step_is_valid = eval('step_'+previous_step+'_validate();');
        if (step_is_valid) {
            eval('step_'+step_number+'('+data+');');
        } else {
            if (previous_step == 4 && !/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($('#step_4_content #email_3').val())) {
				$('#error_container div').text(strings['step_4__invalid_email']);
			} else {
				$('#error_container div').text(strings['step_'+previous_step]);
			}
            $('#error_container').toggle('slide', {direction:'left'});
        }
    }
}

function step_toggle_loading_animation(step_number, action) {
    if (action == 'on') {
        //$('#step_'+step_number+'_content').hide();
        $('.step_content').hide();
        $('#btm_button_bar').hide();
        $('#step_'+step_number+'_loading_animation').show('normal');
    } else if (action == 'off') {
        $('#step_'+step_number+'_loading_animation').hide('normal', function() {$('#step_'+step_number+'_content').show('normal', function(){if ($.browser.msie) {this.style.removeAttribute('filter');}});});
        $('#btm_button_bar').show();
		if (step_number == 5) {
			$('#step_continue_button').hide('slide', {direction:'right'});
		} else {
			$('#step_continue_button').show();
		}
    }
}

/*function step_continue_click_bind(step_number) {
    $('#step_continue_button').unbind('click');
    switch (step_number) {
        case '1': $('#step_continue_button').click(function() {step_initiate('2','\''+radio_product.sku+'\'');});
        case '2': $('#step_continue_button').click(function() {step_initiate('3','{\'product\':\''+radio_product.sku+'\',\'color\':\''+radio_color+'\'}');});
        case '3': $('#step_continue_button').click(function() {step_initiate('4','');});
    }
}*/

function step_continue_action(step_number) {
    switch (step_number) {
        case '1': return 'step_initiate(\'2\',radio_product.sku)'; break;
        case '2': return 'step_initiate(\'3\',\'{\\\'product\\\':\\\''+radio_product.sku+'\\\',\\\'color\\\':\\\''+radio_color+'\\\'}\')'; break;
    }
}

function step_browse_action(clicked_step_number) {
    // Determine the current step
    var current_step_content = $('.step_content:visible');
    var current_step_number  = current_step_content.attr('step');
    var current_step_id      = current_step_content.attr('id');
    /*
    if (clicked_step_number == '3') {
		alert(current_step_number);
	}
    */
    if (clicked_step_number == '2' && current_step_number == '1' && step_1_validate()) {
        // Going forward from 1 to 2
        eval(step_continue_action('1'));
    } else if (clicked_step_number == '1') {
        // Going back from 2 to 1 OR from 3 to 1
        step_toggle_tab(current_step_number);
        step_toggle_tab('1');
        $('#step_continue_button').unbind('click');
        $('#step_continue_button').click(function() {eval(step_continue_action('1'))});
        $('#step_'+current_step_number+'_content').hide('normal', function() {$('#step_1_content').show('normal', function(){if ($.browser.msie) {this.style.removeAttribute('filter');}});});
    } else if (clicked_step_number == '3' && current_step_number == '2' && step_2_validate('2')) {
        // Going forward from 2 to 3
        eval(step_continue_action('2'));
    } else if (clicked_step_number == '2' && current_step_number == '3') {
        // Going back from 3 to 2
        step_toggle_tab('3');
        step_toggle_tab('2');
        $('#step_continue_button').unbind('click');
        $('#step_continue_button').click(function() {eval(step_continue_action('2'))});
        $('#step_3_content').hide('normal', function() {$('#step_2_content').show('normal', function(){if ($.browser.msie) {this.style.removeAttribute('filter');}});});
    } else if (clicked_step_number == '3' && current_step_number == '4') {
        // Going back from 4 to 3
        step_toggle_tab('3');
        $('#step_continue_button').unbind('click');
        $('#step_continue_button').click(function() {step_initiate('4','');});
        $('#step_4_content').hide('normal', function() {$('#step_3_content').show('normal', function(){if ($.browser.msie) {this.style.removeAttribute('filter');}});});
    } else if (clicked_step_number == '2' && current_step_number == '4') {
        // Going back from 4 to 2
        step_toggle_tab('2');
        $('#step_continue_button').unbind('click');
        $('#step_continue_button').click(function() {eval(step_continue_action('2'))});
        $('#step_3_content').hide('normal', function() {$('#step_2_content').show('normal', function(){if ($.browser.msie) {this.style.removeAttribute('filter');}});});
    } else if (clicked_step_number == '1' && current_step_number == '4') {
        // Going back from 4 to 1
        step_toggle_tab('1');
        $('#step_continue_button').unbind('click');
        $('#step_continue_button').click(function() {eval(step_continue_action('1'))});
        $('#step_'+current_step_number+'_content').hide('normal', function() {$('#step_1_content').show('normal', function(){if ($.browser.msie) {this.style.removeAttribute('filter');}});});
    }
    
}

/* Step 1 */

function step_1_product(sku,id,title) {
    this.sku   = sku;
    this.id    = id;
    this.title = title;
}

function step_1_validate() {
    if (($('#step_1_content .radio_button.selected').length)) {return true;} else {return false;};
}

function step_1(categories) {
    var categories_array = [];
	categories_array = categories.split('-');
	var selected_category = categories_array[1];
	
	 // Hide any active step_content / loading animation, in case they're visible from previous user actions
    clearTimeout(global_timeout);
    $('.step_content, .step_content_loading').hide();

    step_toggle_tab('1');
    $('#steps_container').show();
    step_toggle_loading_animation('1','on');
    
    $('#step_continue_button').unbind('click');
    $('#step_continue_button').click(function() {step_initiate('2','\''+radio_product.sku+'\'');});
    
     // Tabs handling
     // We could be restarting the selection process, unbind any onclick events 
    //step_tab_click_unbind_all();
    
    $.get('/', {'products_list_with_thumbs':'1','category':selected_category},
        function(products) {
            var num_containers = (Math.ceil(products.length/3))*3; // Number of rows *times* 3 products per row
            var p_elements     = '<div style="padding:0 1px 0 1px">';
            
            for (x=0; x < num_containers; x++) {
                if (typeof products[x] != 'undefined') {
                    var product = products[x];
                    var onclick = 'onclick_radio(\'step_1_content\',\'radio_'+product.id+'\',\'\'); radio_product = new step_1_product(\''+product.sku+'\', \''+product.id+'\', \''+escape(product.title)+'\');';
                    var border_subclass = (x % 3 == 0) ? ' first_in_row' : '';
            
                    p_elements += '\
                        <div id="product_container_'+product.id+'" class="product_container">\
                            <div class="thumb_container" align="center">\
                                <table cellpadding="0" cellspacing="0">\
                                    <tr>\
                                        <td><img src="'+product.thumb+'" onclick="'+onclick+'" alt="'+product.sku+'" title="'+product.sku+'">\
                                    </tr>\
                                </table>\
                            </div>\
                            <div class="title_container" title="'+product.sku+'">\
                                <div class="title_border'+border_subclass+'">\
                                    <div id="radio_'+product.id+'" class="radio_button" title="'+product.sku+'" onclick="'+onclick+'"></div>\
                                    <div class="title_text" onclick="'+onclick+'">'+product.title+'</div>\
                                </div>\
                            </div>\
                        </div>\
                    ';
                } else {
                    p_elements += '\
                        <div class="product_container">\
                            <div class="thumb_container"></div>\
                            <div class="title_container">\
                                <div class="title_border"><div class="title_text"></div></div>\
                            </div>\
                        </div>\
                    ';
                }
            }
            p_elements += '</div>';
            $('#step_1_content').html(p_elements);
            global_timeout = setTimeout('step_toggle_loading_animation(\'1\',\'off\');', 1500);
        }, 'json'
    )
}

/* Step 2 */

function step_2_validate() {
    if (($('#step_2_content .radio_button.selected').length)) {return true;} else {return false;};
}

function step_2(selected_sku) {
    //$('#steps_container').hide();
    $('#step_1_content').hide();
    step_toggle_tab('2');
    step_toggle_loading_animation('2','on');
    
    $('#step_continue_button').unbind('click');
    $('#step_continue_button').click(function() {step_initiate('3','{\'product\':\''+radio_product.sku+'\',\'color\':\''+radio_color+'\'}');});
    
     // Tabs handling
     // Enable going back to step_1 and back again to level_2 
    //step_tab_click_bind('1');
    //step_tab_click_bind('2');
    
    //alert(selected_sku);
    
    $.get('/', {'product_colors_list':'1','product_sku':selected_sku},
        function(colors) {
            if (colors) {
	            var c_elements = '';
	            for (x=0; x < colors.length; x++) {
	                var color = colors[x];
	                var onclick = 'radio_color = onclick_radio(\'step_2_content\',\'radio_'+color.title_safe+'\',\'\');';
	                var container_subclass = x%5 == 0 ? ' first_in_row' : '';
	                
	                var open_div  = x%5     == 0 ? '<div style="overflow:hidden;zoom:100%">' : '';
	                var close_div = (x+1)%5 == 0 ? '</div>' : '';
	                
	                c_elements += open_div;
	                c_elements += '\
	                    <div class="color_container'+container_subclass+'">\
	                        <div id="radio_'+color.title_safe+'" class="radio_button" onclick="'+onclick+'" title="'+color.title+'"></div>\
	                        <div><img src="'+general_path+'parts_request__box__dotted_delimiter.gif" alt=""></div>\
	                        <div class="thumb_container"><img src="'+color.thumb+'" alt="'+color.title+'" title="'+color.title+'" onclick="'+onclick+'"></div>\
	                    </div>\
	                ';
	                c_elements += close_div;
	            }
	            $('#step_2_content').html(c_elements);
	            global_timeout = setTimeout('step_toggle_loading_animation(\'2\',\'off\');', 1500);
			} else {
				alert('Error: No colors found for this product');
			}
        }, 'json'
    );
}

/* Step 3 */

function step_3_part(sku,id,title,status) {
    this.sku      = sku;
    this.id       = id;
    this.title    = title;
    this.quantity = 0;
    this.reason   = '';
    this.status   = false;
}

function step_3_validate() {
    if (($('#step_3_content .checkbox_button.selected').length)) {return true;} else {return false;};
}

function step_3(selected_vars) {
    //$('#steps_container').hide();
    $('#step_2_content').hide();
    step_toggle_tab('3');
    step_toggle_loading_animation('3','on');
    
    $('#step_continue_button').unbind('click');
    $('#step_continue_button').click(function() {step_initiate('4','');});
    
     // Tabs handling
     // Going back to steps 1 and 2 is already enabled 
    //step_tab_click_bind('3');
    
	// The radio_color has the pattern of "Beige / Green", therefore we need to transform it back to the "safe" pattern
	var parent_product_color = selected_vars.color.replace(/ \/ /g,'-');
	parent_product_color = parent_product_color.replace(' ','_');
	//alert(selected_vars.color+"\n"+parent_product_color);
	
	$.get('/', {'product_parts_list':'1','product_sku':selected_vars.product, 'parent_product_color':parent_product_color},
        function (parts) {
            var pa_elements = '';
            var num_containers = (Math.ceil(parts.length/3))*3; // Number of rows *times* 3 parts per row
            var pa_elements     = '<div style="padding:0">';
            
            checkboxes_parts = {};
            for (x = 0; x < num_containers; x++) {
                if (typeof parts[x] != 'undefined') {
                    var part            = parts[x];
                    checkboxes_parts[x] = new step_3_part(part.sku,part.id,part.title);
                    var onclick         = 'checkboxes_parts['+x+'].status = onclick_checkbox(\'checkbox_'+part.id+'\',\'toggle_details_fields(\\\''+part.id+'\\\')\')';
                    var border_subclass = (x % 3 == 0) ? ' first_in_row' : '';
                   
                    if (x >= 3) {
						var first = (x % 3 == 0) ? ' first_fix' : '';
					} else {
						var first = (x % 3 == 0) ? ' first' : '';
					}
                    
                    var last = (!(x % 3) && x != 0) ? ' last' : '';
                    
                    pa_elements += (!(x % 3) && x != 0) ? '<div class="row_spacer"></div>' : '';
                    
                    pa_elements += '\
                        <div class="part_container'+first+last+'">\
                            <div class="thumb_container" align="center">\
                                <table cellpadding="0" cellspacing="0">\
                                    <tr>\
                                        <td><img src="'+part.thumb+'" onclick="'+onclick+'" alt="'+part.sku+'" title="'+part.sku+' | '+part.id+'">\
										</td>\
                                    </tr>\
                                </table>\
                            </div>\
                            <div class="title_container" title="'+part.sku+'">\
                                <div class="title_border'+border_subclass+'" align="center">\
                                    <table cellspacing="0" cellpadding="0">\
										<tr>\
											<td>\
												<div id="checkbox_'+part.id+'" class="checkbox_button" onclick="'+onclick+'"></div>\
											</td>\
											<td>\
												<div class="title_text" onclick="'+onclick+'">'+part.title+' - '+part.sku+'</div>\
											</td>\
										</tr>\
									</table>\
                                </div>\
                            </div>\
                            <div class="details_container">\
                                <div class="details_border'+border_subclass+'">\
                                    <div style="height:73px" align="center">\
                                        <div style="padding-top:12px">\
                                        <table cellpadding="0" cellspacing="0">\
                                            <tr>\
                                                <td>'+strings['qty']+'<td>\
                                                <td><input type="text" value="" id="qty_field_'+part.id+'" onkeydown="return field_numeric_only(event)" onblur="checkboxes_parts['+x+'].quantity=$(this).val();" disabled="disabled" class="disabled" maxlength="3"></td>\
                                            </tr>\
                                        </table>\
                                        </div>\
                                        <div style="padding-top:8px">\
                                            <select id="reason_field_'+part.id+'" onchange="checkboxes_parts['+x+'].reason=$(this).val();" class="disabled" disabled="disabled">\
                                                <option value="">'+strings['reason-for-request']+'</option>\
                                                <option>'+strings['broken-in-assembly']+'</option>\
                                                <option>'+strings['difficult-to-assemble']+'</option>\
                                                <option>'+strings['missing-parts']+'</option>\
                                                <option>'+strings['purchasing-extras']+'</option>\
                                                <option>'+strings['broken-in-packaging']+'</option>\
                                                <option>'+strings['wind-damage']+'</option>\
                                                <option>'+strings['warp-bend']+'</option>\
                                                <option>'+strings['leak']+'</option>\
                                            </select>\
                                        </div>\
                                    </div>\
                                </div>\
                            </div>\
                        </div>\
                    ';
                    /*
                    if (x == 3) {
						alert(part.sku);
					}
                    */
                } else {
                    pa_elements += '\
                        <div class="part_container">\
                            <div class="thumb_container"></div>\
                            <div class="title_container">\
                                <div class="title_border"><div class="title_text"></div></div>\
                            </div>\
                            <div class="details_container">\
                                <div class="details_border'+border_subclass+'">\
                                    <div style="height:73px">\
                                    </div>\
                                </div>\
                            </div>\
                        </div>\
                    ';
                }
            }
            pa_elements += '</div>';
            
            $('#step_3_content').html(pa_elements);
            global_timeout = setTimeout('step_toggle_loading_animation(\'3\',\'off\');', 1500);
        }, 'json'
    );
}

/* Step 4 */

function step_4_validate() {
    if ($('#step_4_content .mandatory[value=]').length == 0) {
		return true;
	} else {
		return false;
	}
}

function step_4() {
    $('#step_3_content').hide();
    step_toggle_tab('');
    step_toggle_loading_animation('4','on');
    
    $('#step_continue_button').unbind('click');
    $('#step_continue_button').click(function() {step_initiate('5','');});
    
    var user_selection = '\
        <div class="selection_value"><span>'+strings['product']+':</span> '+unescape(radio_product.title)+'</div>\
        <div class="selection_value"><span>'+strings['color']+':</span> '+radio_color+'</div>\
        <div class="selection_value"><span>'+strings['parts']+':</span>\
    ';
	var part;
	var delimiter = '';
	for (var i in checkboxes_parts) {
        part      = checkboxes_parts[i];
        if (part.status === true) {
            user_selection += delimiter+part.title+' x '+part.quantity;
			if (delimiter == '') {
				delimiter = ', ';
			}
        }
    }
    user_selection += '</div>';
    
    $('#step_4_user_selection').html(user_selection);
    global_timeout = setTimeout('step_toggle_loading_animation(\'4\',\'off\');', 1500);
}

function step_5() {
    $('#step_4_content').hide();
    step_toggle_tab('');
    step_toggle_loading_animation('5','on');
    
    $('#step_continue_button').unbind('click');
	
     // Gathering user parts selection
    var product_parts = {};
    var j = 0;
    for (var x in checkboxes_parts) {var part = checkboxes_parts[x]; if (part.status) {product_parts[j] = part; j++}}
    product_parts = $.toJSON(product_parts);
 
 	var product_categories = [];
 	product_categories = $('#parts_request_categories_list').val().split('-');
    var product_parent_category_id = product_categories[0];
	var product_category_id = product_categories[1]
    var product_category_title = $('#parts_request_categories_list option[value=\''+product_category_id+'\']').html();   
    
    var ordered_from     = radio_ordered_from == 'Retailer' ? $('#retailers_list').val() : radio_ordered_from;
    
     // Gathering contact details
    var contact_details = {};
    $('#contact_details_form .text_field, #contact_details_form textarea').each(function() {contact_details[$(this).attr('name')] = $(this).val();});
    contact_details   = $.toJSON(contact_details);
    
    $.get('/', {'parts_request':1, 'product_sku':radio_product.sku, 'product_title':radio_product.title, 'product_color':radio_color, 'product_category_id':product_category_id, 'product_parent_category_id':product_parent_category_id, 'product_category':product_category_title, 'ordered_from':ordered_from, 'product_parts':product_parts, 'contact_details':contact_details, 'contact_country':$('#countries_list').val(), 'contact_state':$('#states_list').val()},
        function(data) {
            global_timeout = setTimeout(function () {
				//alert(data);
				step_toggle_loading_animation('5','off');
			}, 1500);
        }, 'json'
    );
}
