 // Initiate the first step on load
$(document).ready(function() {step_1('1');});
 
 // Variables

/*
var selected_product  = {'id':'153297', 'title':'הזמנות לחתונה', 'layout':'fixed'};
var selected_design   = {'title':'פרחים ופרפרים', 'image_445x500':'/files/custom_designs/graphics/graphic__flowers_butterflies__445x500.png'};
var selected_paper    = {'title':'פרוטרה גבס', 'catalog_number':'15530', 'image_tile':'/files/images/images%20digital/catalog/frotara_geves.jpg'};
var selected_version  = 'משולב'; // For fixed layout products
var client_design_url = ''; // For free layout products
*/

var selected_product  = {'id':'', 'title':'', 'layout':'', 'sides':'', 'size_in_cm':'', 'envelopes_size':'', 'product_paper':'', 'product_sheet':'', 'product_touchups':''};
var selected_design   = {'title':'', 'image_445x500':''};
var selected_paper    = {'title':'', 'catalog_number':'', 'image_tile':''};
var selected_version  = ''; // For fixed layout products
var client_design_url = ''; // For free layout products

var versions_texts   = new Array();

 // Steps Functions

function step_tabs_toggle(step_number) {
     // Toggle off the current tab
    $('.tab_container.on').removeClass('on').addClass('off');
     // Toggle the selected tab, if one was passed
    if (step_number) { $('#step_tab_'+step_number).removeClass('off').addClass('on'); }
} 

function step_loading_animation(step_number, action) {
    if (action == 'on') {
        $('.step_content').hide();
        $('#step_loading_animation').empty();
        $('#step_'+step_number+'_animation').clone().appendTo('#step_loading_animation').show();
        $('#step_loading_animation').fadeIn('normal');
    } else if (action == 'off') {
        $('#step_loading_animation').fadeOut('normal',
            function() {;
                $('#step_'+step_number+'_content').fadeIn('normal');
            }
        );
    }
}

function step_loading_animation_off(step_number, delay) {
     // For AJAX requests the delay should be passed as '1', otherwise just use the default set here
    delay = !delay ? 1500 : delay; 
    setTimeout('step_loading_animation(\''+step_number+'\', \'off\')', delay);
}

function step_1(tab_num) {
    step_tabs_toggle(tab_num);
    step_loading_animation('1','on');
    step_loading_animation_off('1','');
}

function step_2(tab_num) {
    step_tabs_toggle(tab_num);
    step_loading_animation('2','on');
    $.get('/',{'custom_design_graphic_designs':'1','custom_design_product':selected_product.id},
        function(graphic_designs) {
            var designs_per_row = 4; // Only used for calculation of the separators. The numbers of items per row is determined only by the width of the floating divs
            $('#designs_container').html('');
            $('#designs_previews_container').html('');
            
             // Graphic designs thumbs and previews - base_href is a global set in main (late change)
            for (i=0; i < graphic_designs.length; i++) {
                 // Thumbs
                var thumb_bg     = 'background:url('+base_href+graphic_designs[i]['image_130x130']+') no-repeat;';
                var design_title = graphic_designs[i]['title'] ? graphic_designs[i]['title'] : '';
                var preview_id   = 'graphic_design_preview_'+i;
                 // A multiplication of designs_per_row (except i=0) is the last in row  
                last_flag            = (i == 0) || ((i+1) % designs_per_row) ? 'false' : 'true';
                design_thumb_onclick = 'design_preview_show(\''+preview_id+'\', \''+base_href+graphic_designs[i]['image_250x250']+'\', $(this).position(), '+last_flag+')';
                 // The title has almost the same onclick, except it doesn't pass its own position but it's parent container's thumb_border position
                design_title_onclick = 'design_preview_show(\''+preview_id+'\', \''+base_href+graphic_designs[i]['image_250x250']+'\', $(this).parent().find(\'.thumb_border\').position(), '+last_flag+')';
                 // Add the complete design container to the table
                $('#designs_container').append('<div class="graphic_design"><div class="thumb_border" onclick="'+design_thumb_onclick+'"><div class="graphic_design_thumb" style="'+thumb_bg+'"></div></div><div class="graphic_design_title" onclick="'+design_title_onclick+'">'+design_title+'</div></div>');
                 // Add a separator if this is the very first cell or the last in row
                if (!i || ((i+1)%designs_per_row)) {$('#designs_container').append('<div class="designs_separator"></div>');}
                
                 // Previews
                var select_onclick = 'selected_design.title = \''+graphic_designs[i]['title']+'\'; selected_design.image_445x500 = \''+base_href+graphic_designs[i]['image_445x500']+'\'; step_3(\'2\');';
                var cancel_onclick = 'design_preview_hide(\''+preview_id+'\')';
                var preview_container = '<div id="'+preview_id+'" class="graphic_design_preview">\
                        <div class="preview_border" align="center">\
                            <div class="preview_buttons">\
                                <div class="preview_button" style="text-align:right;"><a onclick="'+select_onclick+'"><img src="'+base_href+'images/global/custom_design__v_sign.gif" alt="">בחירה</a></div><div class="preview_button" style="text-align:left;"><a onclick="'+cancel_onclick+'"><img src="'+base_href+'images/global/custom_design__cancel_sign.gif" alt="">ביטול</a></div>\
                            </div>\
                            <img src="'+base_href+'images/global/custom_design__preview_place_holder.png" class="preview_image" alt="'+graphic_designs[i]['title']+'">\
                ';
                 // Preview title
                if (graphic_designs[i]['title']) {
                    preview_container += '<div class="preview_title">'+graphic_designs[i]['title']+'</div>';
                }
                
                preview_container += '\
                        </div>\
                    </div>\
                ';
                 // Add the complete preview to the previews container
                $('#designs_previews_container').append(preview_container);
            }
        }, 'json'
    );
    step_loading_animation_off('2','');
}

function step_3(tab_num) {
    step_tabs_toggle(tab_num);
    step_loading_animation('3','on');
    step_loading_animation_off('3','');
}

function step_4(tab_num) {
    step_tabs_toggle(tab_num);
    step_loading_animation('4','on');
    $.get('/',{'custom_design_product':selected_product.id, 'custom_design_set':selected_design.title, 'paper_tile':selected_paper.image_tile, 'design_image':selected_design.image_445x500},
        function(product) {
             // Set the global variables
            selected_product.layout       		= product.layout;
            selected_product.sides        		= product.sides;
            selected_product.size_in_cm    		= product.size_in_cm;
            selected_product.envelopes_size 	= product.envelopes_size;
			selected_product.product_paper 		= product.product_paper;
			selected_product.product_sheet 		= product.product_sheet;
			selected_product.product_touchups	= product.product_touchups;
             
             // Fixed layout - versions
            if (product.layout == 'fixed') {
                 // Some reset actions in case the user went back a step
                $('#free_edit_container').hide(); 
                $('#free_description').hide();
                $('#versions_links').html('');
                $('#version_sample').html('');
                selected_version = '';
                versions_texts = new Array();
                
                $('#fixed_description span').html(' <span>'+selected_product.title+'</span>:').show();
                $('#fixed_description').show();
                $('#version_sample').html('<img src="'+product.sample_image+'" alt="'+selected_product.title+'" title="'+selected_product.title+'">');
                $('#versions_container').show();
                
                 // Versions links
                for (i=0; i < product.versions.length; i++) {
                    var separator       = i != (product.versions.length-1) ? '<div class="version_separator">|</div>' : '';
                    var version_num     = i;
                    var version_link_id = 'version_link_'+version_num;
                    var version_onclick = 'selected_version = \''+product.versions[i]['title']+'\'; version_select(\''+version_num+'\', versions_texts);';
                     // Add the version's link 
                    $('#versions_links').append('<div id="'+version_link_id+'" class="version_link" onclick="'+version_onclick+'">'+product.versions[i]['title']+'</div>'+separator);
                     // Globally store the version's text
                    versions_texts[i] = product.versions[i]['text'];
                }   
                 // Initiate the first version
                $('#version_link_0').click();
            
             // Free layout - editor popover
            } else if (product.layout == 'free') {
                 // Some reset actions in case the user went back a step
                $('#versions_container').hide();
                $('#fixed_description').hide();
                $('#editor_popover').html('');
                $('#save_and_finish_enabled').hide(); $('#save_and_finish_disabled').show();
                $('#product_sample').html('');
                
                 // Write the returned iframe code to the popover
                $('#editor_popover').html(product.popover_content);
                 // Force the iframe to be transparent in IE
                if ($.browser.msie) { setTimeout('document.getElementById(\'editors_iframe\').setAttribute(\'allowTransparency\',\'true\');document.getElementById(\'editors_iframe\').style.backgroundColor = \'transparent\';', 1000); }
                
                $('#free_description span').html(' <span>'+selected_product.title+'</span>:');
                $('#free_description').show();
                $('#product_sample').html('<img src="'+product.sample_image+'" alt="'+selected_product.title+'" title="'+selected_product.title+'">');
                $('#free_edit_container').show();
                
                $('#popout_button').attr('href',product.popout_url);
            }            
            
            step_loading_animation_off('4','');
        }, 'json'
    );
}

function step_5(tab_num) {
    step_tabs_toggle(tab_num);
    step_loading_animation('5','on');
    
    if (selected_product.layout == 'fixed') {
         // Update the selected customer values
        $('#selected_product_value').html(selected_product.title);
        $('#selected_design_value').html(selected_design.title);
        $('#selected_paper_value').html(selected_paper.title);
        $('#selected_version_value').html(selected_version);
        $('#selected_version_row').show();
        step_loading_animation_off('5','');
    
    } else if (selected_product.layout == 'free') {
         // Post the user's design to the server
        $.post('<?=href('/')?>', { 'custom_design_client_source':$('#custom_design_buffer', top.document).html() },
            function (design_url) {
                client_design_url = design_url;
                 // Update the selected customer values
                $('#selected_product_value').html(selected_product.title);
                $('#selected_design_value').html(selected_design.title);
                $('#selected_paper_value').html(selected_paper.title);
                $('#client_design_link').attr('href',client_design_url);
                $('#client_design_link_row').show();
                step_loading_animation_off('5','');
            }, 'html'
        );
    }
}

function step_6(tab_num) {
    var mandatory_filled = true; 
    $('.mandatory_field').each( function() {mandatory_filled = jQuery.trim($(this).val()) ? true : false; return mandatory_filled; /* breaks the iteration when false */} );
    if (!mandatory_filled) {
        alert('נא למלא את שדות החובה המסומנים בכוכבית.');
    } else {
        step_tabs_toggle(''); // Currently, this step has no tab. Passing it empty turns off all tabs
        step_loading_animation('6','on')
        
         // Client contact Details
        var client_details    = {'name':$('#c_name').val(),'address':$('#c_address').val(),'city':$('#c_city').val(),'zip':$('#c_zip').val(),'cellphone':$('#c_cell').val(),'phone':$('#c_phone').val(),'email':$('#c_email').val()}; 
         // Product, graphics, paper, version, custom content
        var client_selection   = {'product':object_encodeURI(selected_product),'design':object_encodeURI(selected_design),'paper':object_encodeURI(selected_paper),'version':encodeURI(selected_version),'client_design_url':client_design_url,'quantity':$('#p_quantity').val()};
         // Prefernces and addition
        var client_preferences = {'arrive_to_confirm':radio_val('p_arrive'),'envelopes':radio_val('p_envelopes'),'envelopes_quantity':$('#p_envelopes_quantity').val(),'quote_by':radio_val('p_quote_by'),'call_hours':radio_val('p_call_hours'),'shipping':radio_val('p_shipping'),'shipping_destination':$('#p_shipping_destination').val()};  
       
        var order_details = {'client_details':object_encodeURI(client_details),'client_selection':client_selection,'client_preferences':object_encodeURI(client_preferences)};
        
        $.post('/', {'custom_design_order':'1','order_details':JSON.stringify(order_details)},
            function(data) {
                step_loading_animation_off('6','');
            }
        );
    }
}


 // Editor functions

function popover_toggle(action, popover_id) {
    if (action == 'on') {
        $('#'+popover_id).height($(document).height()).fadeIn('slow',
            function() { 
                 // Fix IE's distorted text after the fade
                ie_cleartype_fix(this);
                 // Scroll to the top of the popover
                $(document).scrollTo('#editor_popover', 800);
                 // Adjust the height of all the semi-transparent overlays to the height of their respective editors 
                setTimeout('$(\'#editors_iframe\').contents().find(\'.editor_overlay\').each(function() { $(this).height($(this).parent().height()) });', 100); 
            }
        );
    }
}

 // General functions

/*function toggle_dialog(dialog_id) {
    $('#'+dialog_id).toggle('slide', {direction:'left'}, 250);
}*/

function ie_cleartype_fix(element) {
    if ($.browser.msie) element.style.removeAttribute('filter');
}

function design_preview_show(preview_id, preview_src, clicked_element_position, last_flag) {
     // If the same element has been clicked again, hide it and break the operation
    if ($('#'+preview_id).is(':visible')) { paper_preview_hide(preview_id); return; }
    
    // Position the preview box at the top right corner of the clicked element
     // All but IE and it's not the last element in row 
    if (!$.browser.msie && !last_flag) {
        var preview_top  = clicked_element_position.top;
        var preview_left = clicked_element_position.left - 130; 
     // IE only and it's not the last element in row
    } else if ($.browser.msie && !last_flag) {
        var preview_top  = clicked_element_position.top;
        var preview_left = clicked_element_position.left - 130;
        
     // All but IE and it is the last element in row
    } else if (!$.browser.msie && last_flag) {
        var preview_top  = clicked_element_position.top;
        var preview_left = 0;
     // IE only and it is last the last element in row
    } else if ($.browser.msie && last_flag) {
        var preview_top  = clicked_element_position.top;
        var preview_left = 0;
    }

     // The direction of the element determines the direction to which it would expand and detract using show() and hide()
     // An LTR element would expand from the top-left corner to the bottom-right, and the other way around when detracting
     // An RTL element would expand from the top-right corner to the bottom-left, and the other way around when detracting
     // All elements but the last have enough room to expand RTL, but the last has to expand LTR to stay inside the 610px container
    if (last_flag) {
        $('.step_2 .previews_container').css({'direction':'ltr'});
    } else {
        $('.step_2 .previews_container').css({'direction':'rtl'});
    }
    
    $('.graphic_design_preview').hide();
    $('.step_2 .previews_container').css({'top':preview_top, 'left':preview_left});
    $('#'+preview_id+' .preview_image').attr('src',preview_src);
    $('#'+preview_id).show('normal');
}

function design_preview_hide(preview_id) {
    $('#'+preview_id).hide('normal');
}

function paper_preview_show(preview_id, preview_src, clicked_element_position, last_flag) {
     // If the same element has been clicked again, hide it and break the operation
    if ($('#'+preview_id).is(':visible')) { paper_preview_hide(preview_id); return; }

     // Position the preview box at the top right corner of the clicked element
     // IE was buggy at first, but it may have been due to caching. To be on the safe side, I kept the separate conditions, though they're currently unnecessary
     
     // All but IE and it's not the last element in row 
    if (!$.browser.msie && !last_flag) {
        var preview_top  = clicked_element_position.top + 10;
        var preview_left = clicked_element_position.left - 150; 
     // IE only and it's not the last element in row
    } else if ($.browser.msie && !last_flag) {
        var preview_top  = clicked_element_position.top + 10;
        var preview_left = clicked_element_position.left - 150;
        
     // All but IE and it is the last element in row
    } else if (!$.browser.msie && last_flag) {
        var preview_top  = clicked_element_position.top + 10;
        var preview_left = 0;
     // IE only and it is last the last element in row
    } else if ($.browser.msie && last_flag) {
        var preview_top  = clicked_element_position.top + 10;
        var preview_left = 0;
    }

     // The direction of the element determines the direction to which it would expand and detract using show() and hide()
     // An LTR element would expand from the top-left corner to the bottom-right, and the other way around when detracting
     // An RTL element would expand from the top-right corner to the bottom-left, and the other way around when detracting
     // All elements but the last have enough room to expand RTL, but the last has to expand LTR to stay inside the 610px container
    if (last_flag) {
        $('.step_3 .previews_container').css({'direction':'ltr'});
    } else {
        $('.step_3 .previews_container').css({'direction':'rtl'});
    }

    $('.step_3 .previews_container').css({'top':preview_top, 'left':preview_left});
    $('.paper_preview').hide();
    $('#'+preview_id+' .preview_image').css({'background-image':'url('+preview_src+')'});
    $('#'+preview_id).show('normal');
}

function paper_preview_hide(preview_id) {
    $('#'+preview_id).hide('normal');
}

function version_select(version_num, versions_texts) {
    var version_link_id = 'version_link_'+version_num;
     // Check this is not the current selected version
    if (!$('#'+version_link_id).hasClass('selected')) {
         // Toggle off all links
        $('.version_link').removeClass('selected');
         // Toggle on the clicked link
        $('#'+version_link_id).addClass('selected');
         // Change to the selected version's text
        $('#version_text_container').hide().html(versions_texts[version_num]).fadeIn(700);
    }
}


 // Uses animate() as an alternative for slideUp() - this is a quick fix for the annoying flicker in IE
 // Credit: http://siderite.blogspot.com/2009/08/jquery-slideup-flickers-in-internet.html
function slideup_alt(jquery_object) {
    var h = jquery_object.height();
    jquery_object.animate ({ height: '1px' }, 'fast',
        function() { 
            jquery_object.hide();
            jquery_object.height(h);
        } 
    );
}

function form_element_toggle(action, element_id) {
    if (action == 'on') {
        $('#'+element_id).slideDown('fast');
    } else if (action == 'off' && $('#'+element_id+':visible').attr('id')) {
        slideup_alt($('#'+element_id));
    }
}

function form_field_numeric_only(e) {
    var keynum;
    var keystr;
    var keychar;
    var numcheck;
    var allowed_keys = '|7|8|9|16|35|37|39|45|46|48|49|50|51|52|53|54|55|56|57|58|96|97|98|99|100|101|102|103|104|105|';
    
    if(window.event) {
        keynum = e.keyCode;
    }
    else if(e.which) {
        keynum = e.which;
    }
    
    var keystr = new RegExp('/\|'+keynum.toString()+'\|/');
    if (allowed_keys.search(keystr) != '-1') {
        return true;
    } else {
        return false;
    }
}

function radio_val(var_name) {
    return $('[name='+var_name+']:checked').val();
}

function object_encodeURI (obj) {
    jQuery.each(obj, function(i) { obj[i] = encodeURI(obj[i]); });
    return obj;
}
