// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function check_all_elements(class_name, checked) {
    //    document.getElementsByClassName( class_name).each(function(item) {
    //        item.checked = checked;
    //    });
    $$('.' + class_name).each(function(item) {
        item.checked = checked;
    });
}

function change_order_count( select_index) {
    //    document.getElementsByClassName( 'order_count').each(function(item) {
    //        item.selectedIndex = select_index;
    //    });
    $$('.order_count').each(function(item) {
        item.selectedIndex = select_index;
    });
}

function check_order_count() {
    var is_selected = false;
    //    document.getElementsByClassName( 'order_count').each(function(item) {
    //        if (item.selectedIndex > 0)
    //        {
    //            is_selected = true;
    //        }
    //    });
    $$('.order_count').each(function(item) {
        if (item.selectedIndex > 0){
            is_selected = true;
        }
    });
    if (is_selected == false)
    {
        alert("Please select the quantity of the item you want to buy at first.");
        return false;
    } else {
        return true;
    }
}

//-------------------------
// Clear email subscription field
//-------------------------
function clearEmailField(field) {
    if(field.value == 'Enter Your Email Here...' || field.value == 'Entrer votre courriel ici..') {
        field.value = '';
    }
}

//-------------------------
// Reset email subscription field
//-------------------------
function resetEmailField(field) {
    if(field.value.blank()) {
        field.value = 'Enter Your Email Here...';
    }
}

//-------------------------
// Clear Search field
//-------------------------
function clearSearchField(field) {
    if(field.value == 'Search by name or model...' || field.value == 'Recherche par nom ou modèle..') {
        field.value = '';
    }
}

//-------------------------
// Reset email subscription field
//-------------------------
function resetSearchField(field, words) {
    if(field.value.blank()) {
        field.value = words;
    }
}

//-------------------------
// Check search input
//-------------------------
function checkInkFinderInput() {
    var err_message = '';
  
    if($F('search_printer_brand') == '0') {
        err_message = 'Please select a printer brand to start';
    } else if($F('search_printer_model') == '0' && $F('search_cartridge') == '0') {
        err_message = 'Please select a printer # or cartridge # to start';
    }
  
    if(err_message.blank()) {
        return true;
    } else {
        alert(err_message);
        return false;
    }
}

//-------------------------
// Check search input
//-------------------------
function checkSearchInput() {
    var q = $F('search_q');
    if(q.blank() || q.strip().length < 3) {
        alert("Please input at least 3 characters as the keyword");
        return false;
    } else {
        return true;
    } 
}

//-------------------------
// Change the sub menu
//-------------------------
function changeGuideTab(name) {
    $$('li.current').each(
        function(menu) {
            menu.className = '';
        }
        );
  
    $$('div.guide_tab_body').each(
        function(sub_menu) {
            if(sub_menu.style.display != 'none') {
                sub_menu.hide();
            }
        }
        );
  
    $('guide_menu_' + name).className = 'current';
    $('guide_tab_' + name).show();
}

//SCM
//check new scm transfer items
function check_transfer_items(){
    var inputs = $$('td > input')
    var reg = /^\d+$/
    for(var i=0;i<inputs.length;i++){
        if(!reg.test(inputs[i].value)){
            alert("Qty must be number and can not be negative,please check!")
            return false
        }
    }
    return true
}

//check new transfer
function check_transfer(){
    if($('scm_transfer_from_scm_distribution_center_id').value == $('scm_transfer_to_scm_distribution_center_id').value){
        alert("Origin Distribution Center(From) and Destination Distribution Center(To) can't be same,please check!")
        return false
    }
    return true
}

//check new/edit inquiry case template
function check_inquiry_case_template(){
    if($('inquiry_case_template_title').value == ''){
        alert("Template Title can not empty!")
        return false
    }
    if($('inquiry_case_template_content').value == ''){
        alert('Template Body can not empty!')
        return false
    }
    return true
}

// add image file for product
function add_image_file(source){
    var btn = $(source)
    new Insertion.Before(btn.id,'<div><input type="file" name="product[image_files_attributes][][image]"> <a href="#" onclick="$(this).up(0).remove();return false;">remove</a></div>')
}

function toggle_special_field(element,value){
    if(value == 'PrinterProduct'){
        $('product_images_container').hide()
        $('product_categories_container').hide()
        $('product_specification_container').hide()
        $('product_warranty_container').hide()
        $('product_introduction_container').hide()
        $('product_is_oem_container').show()

        $('product_brand_id').up(0).hide()
        $('product_brand_id').disable()
        $('product_printer_brand_id').up(0).show()
        $('product_printer_brand_id').enable()

        $('printer_product_fields').show()
    }else{
        $('product_is_oem_container').hide()
        $('product_images_container').show()
        $('product_categories_container').show()
        $('product_specification_container').show()
        $('product_warranty_container').show()
        $('product_introduction_container').show()

        $('product_brand_id').up(0).show()
        $('product_brand_id').enable()
        $('product_printer_brand_id').up(0).hide()
        $('product_printer_brand_id').disable()

        $('printer_product_fields').hide()
    }
}

function switch_product_tags(name){
    var tags = $('right_area').childElements()
    for(var i=2;i<tags.length;i++){
        tags[i].hide()
    }
    var list = $('product_info_tag_list').childElements()
    for(var k=0;k<list.length;k++){
        list[k].removeClassName('current')
    }
    $(name).show()
    $(name + '_tag').addClassName('current')
}

function create_answer(source,question_id){
    var btn = $(source)
    var form_html = $('new_answer').innerHTML
    new Insertion.Top('question_' + question_id + '_answer_container',form_html.replace('##',question_id))
    btn.disable()
}

function switch_image(source){
    var e = $(source)
    var src = e.down(0).src
    $('product_image').src = src.replace('thumb','medium')
}

// revies stars
function stars_over(source){
    var stars = $('reviews_stars').childElements()
    var current_star = $(source).readAttribute('stars')
    for(var i=0;i<stars.length;i++){
        var s = stars[i].readAttribute('stars')
        if(parseInt(current_star) >= parseInt(s)){
            stars[i].down(0).src = "/images/star_1.png"
        }else{
            stars[i].down(0).src = "/images/star_0.png"
        }
    }
}
function stars_out(source){
    var stars = $('reviews_stars').childElements()
    for(var i=0;i<stars.length;i++){
        var s = stars[i].readAttribute('stars')
        var current = $('review[stars]').value
        if(parseInt(current) >= parseInt(s)){
            stars[i].down(0).src = "/images/star_1.png"
        }
        else{
            stars[i].down(0).src = "/images/star_0.png"
        }
    }
}
function set_stars(source){
    var stars = $('reviews_stars').childElements()
    var current_star = $(source).readAttribute('stars')
    for(var i=0;i<stars.length;i++){
        var s = stars[i].readAttribute('stars')
        if(parseInt(current_star) >= parseInt(s)){
            stars[i].down(0).src = "/images/star_1.png"
            $('review[stars]').value = current_star
        }else{
            stars[i].down(0).src = "/images/star_0.png"
        }
    }
}

function set_products_search_options(option){
    var options = ['product_type','brand_id','category_id','query_word']
    var values = ['All','0','0','']
    for(var i=0;i<options.length;i++){
        if(options[i] != option){
            $(options[i]).value = values[i]
        }
    }
}

function all_use_store_credit(element){
    if($(element).checked){
        $('order_pre_use_credit').value = $('order_pre_use_credit').readAttribute('store_credit');
    }else {
        $('order_pre_use_credit').value = '';
    }
}

function mouse_over_color(row) {
    row.style.backgroundColor = '#FFFCDF';//'#ef9e47'
    row.childElements().each(function(e){
        e.style.backgroundColor = '#FFFCDF';
    });
}

function mouse_out_color(row) {
    row.style.backgroundColor = '#ffffff';
    row.childElements().each(function(e){
        e.style.backgroundColor = '#ffffff';
    });
}

/* member avatar */
function onEndCrop( coords, dimensions ) {
    $( 'x1' ).value = coords.x1;
    $( 'y1' ).value = coords.y1;
    $( 'width' ).value = dimensions.width;
    $( 'height' ).value = dimensions.height;
    $('show_width').innerHTML = dimensions.width;
    $('show_height').innerHTML = dimensions.height;
}
function init_image_editor() {
    if($('photo')){
        new Cropper.ImgWithPreview('photo',{
            minWidth: 50,
            minHeight: 50,
            ratioDim: {
                x:125,
                y: 125
            },
            displayOnInit: true,
            onEndCrop: onEndCrop,
            previewWrap: 'preview'
        })
    }
}

/* home promotions Christmas countdown*/
function promotions_christmas_countdown(){
    var end_time = new Date("2011/12/22,00:01:00");
    var now_time = new Date();
    var start_time = new Date("2011/12/21,00:00:00");
    var leftsecond = parseInt((end_time.getTime() - now_time.getTime())/1000);
    var h = parseInt((leftsecond/3600)%24);
    var m = parseInt((leftsecond/60)%60);
    var s = parseInt(leftsecond%60);

    $('christmas_hours').innerHTML = h;
    $('christmas_minues').innerHTML = m;
    $('christmas_seconds').innerHTML = s;
    if((now_time.getTime() - start_time.getTime()) < 0){
        $('christmas_timer_box').hide();
    }else if($('christmas_timer_box').style.display == 'none'){
        $('christmas_timer_box').show();
    }
    if(leftsecond <= 0){
        $('christmas_timer_box').hide();
        // define christmas_timer on _home_promotions.html.erb
        clearInterval(christmas_timer);
    }

}

function increase_count_on_shopping_cart(){
    if(!isNaN($('shopping_cart_count').getValue())){
        $('shopping_cart_count').setValue(parseInt($('shopping_cart_count').getValue()) + 1);
    }
}

function reduce_count_on_shopping_cart(){
    if(!isNaN($('shopping_cart_count').getValue()) && parseInt($('shopping_cart_count').getValue()) > 1){
        $('shopping_cart_count').setValue(parseInt($('shopping_cart_count').getValue()) - 1);
    }
}

function increase_count_on_product_list(id){
    if(!isNaN($(id).getValue())){
        $(id).setValue(parseInt($(id).getValue()) + 1);
    }
}

function reduce_count_on_product_list(id){
    if(!isNaN($(id).getValue()) && parseInt($(id).getValue()) > 1){
        $(id).setValue(parseInt($(id).getValue()) - 1);
    }
}

var google_initialized = false;
function google_auto_translate() {
    if(google_initialized) {
        $$('.goog-te-gadget-link').each(function(item) {
            if( document.createEvent ) {
                var evObj = document.createEvent('MouseEvents');
                evObj.initEvent('click', true, false );
                item.dispatchEvent(evObj);
            } else if( document.createEventObject ) {
                item.fireEvent('onclick');
            }
        });
    } else if((typeof google) != 'undefined' && google.translate) {
        google_initialized = true;
        setTimeout(google_auto_translate, 1100);
    } else
        setTimeout(google_auto_translate, 100);
}

function product_tab (element) {
    var tabs = $$("div.tab2 > ul > li > a");

    var current_tab_id = element.readAttribute("tab");

    if(current_tab_id == 'information'){
        tabs.each(function(e){
            e.up().removeClassName("selected");
            var tab_id = e.readAttribute("tab");
            if($(tab_id).down('h3')){
                $(tab_id).down('h3').show();
            }
            if(tab_id != 'information'){
                $(tab_id).addClassName("box5");
            }
            $(tab_id).show();
        });
    }else{
        tabs.each(function(e){
            e.up().removeClassName("selected");
            var tab_id = e.readAttribute("tab");
            $(tab_id).hide();
        });

        $(current_tab_id).removeClassName("box5");
        if($(current_tab_id).down('h3')){
            $(current_tab_id).down('h3').hide();
        }
    }
    element.up().addClassName("selected");
    $(current_tab_id).show();
}

function continue_add_to_cart(element){
    element.up().hide();
    element.up().next().show();
    element.up().next(1).show();
}

function sub_slide_products_prev(element){
    var current_group = parseInt($(element).readAttribute('x-show-group'));
    if(current_group > 0){
        var previous_group = current_group - 1;
        $(element).writeAttribute('x-show-group',previous_group);
        $('sub-slide-products-next-button').writeAttribute('x-show-group',previous_group);

        $$('dl[x-group="' + current_group + '"]').each(function(e){
            e.hide();
        });
        $$('dl[x-group="' + previous_group + '"]').each(function(e){
            e.show();
        });
    }
}

function sub_slide_products_next(element){
    var current_group = parseInt($(element).readAttribute('x-show-group'));
    var max_group = parseInt($(element).readAttribute('x-max-group'));
    if(current_group < max_group){
        var next_group = current_group + 1;
        $(element).writeAttribute('x-show-group',next_group);
        $('sub-slide-products-prev-button').writeAttribute('x-show-group',next_group)

        $$('dl[x-group="' + current_group + '"]').each(function(e){
            e.hide();
        });
        $$('dl[x-group="' + next_group + '"]').each(function(e){
            e.show();
        });
    }
}

// init page
function load() {
    // your account event
    /*
    if($("your-account")){
        $("your-account").observe('mouseover',
            function () {
                this.childElements()[1].show();
            });
        $("your-account").observe('mouseout',
            function () {
                this.childElements()[1].hide();
            });
    }
    */
    // nav
    /*
    if($("global-nav")){
        $("global-nav").observe('mouseover',
            function () {
                this.removeClassName("global-nav-hide");
            });
        $("global-nav").observe('mouseout',
            function () {
                this.addClassName("global-nav-hide");
            });
    }
    if($("global-nav-list")){
        $("global-nav-list").childElements().each(function(e){
            e.observe('mouseover',
                function () {
                    this.addClassName("hover");
                });
            e.observe('mouseout',
                function () {
                    this.removeClassName("hover");
                });
        });
    }
    */
    // product tabs
    /*
    $$("div.tab2 > ul > li > a").each(function(e){
        e.observe('click',
            function () {
                var tabs = $$("div.tab2 > ul > li > a");
                    
                var current_tab_id = this.readAttribute("tab");

                if(current_tab_id == 'information'){
                    tabs.each(function(e){
                        e.up().removeClassName("selected");
                        var tab_id = e.readAttribute("tab");
                        if($(tab_id).down('h3')){
                            $(tab_id).down('h3').show();
                        }
                        if(tab_id != 'information'){
                            $(tab_id).addClassName("box5");
                        }
                        $(tab_id).show();
                    });
                }else{
                    tabs.each(function(e){
                        e.up().removeClassName("selected");
                        var tab_id = e.readAttribute("tab");
                        $(tab_id).hide();
                    });

                    $(current_tab_id).removeClassName("box5");
                    if($(current_tab_id).down('h3')){
                        $(current_tab_id).down('h3').hide();
                    }
                }
                this.up().addClassName("selected");
                $(current_tab_id).show();
            });
    });
    */

    /*
    if($$("div.home-page-top-side").size() > 0){
        $("search-by-printer").down().setStyle({
            cursor: 'pointer'
        });
        $("search-by-printer").down().observe('click',function(e){
            $("search-by-printer").down().next().toggle();
            $("why-me").down().next().toggle();
        });
        $("why-me").down().setStyle({
            cursor: 'pointer'
        });
        $("why-me").down().observe('click',function(e){
            $("why-me").down().next().toggle();
            $("search-by-printer").down().next().toggle();
        });
    }
    */

    if($("slider")){
        var slider = new ProtoSlider("slider", {
            navigation:		true,
            navId:			'slider-navigation',
            effect:			'corner:o:b',
            //random:			"straight:och:seat[0.15] straight:ocw:seat[0.5]",
            //random:			"straight:oc swirl:ohl grid:ovt",
            duration:		1000,
            columns:		9, //9
            rows:			5, // 5
            seat:			0.35,
            speedup:		1,
            fps:			50,
            interval:		3000
        });
        slider._start();
    }

    /*
    if($("sub-slide-products-prev-button") && $("sub-slide-products-next-button")){
        $('sub-slide-products-prev-button').observe('click',function(e){
            var current_group = parseInt($(this).readAttribute('x-show-group'));
            if(current_group <= 0){
                return false;
            }
            var previous_group = current_group - 1;
            $(this).writeAttribute('x-show-group',previous_group);
            $('sub-slide-products-next-button').writeAttribute('x-show-group',previous_group);

            $$('dl[x-group="' + current_group + '"]').each(function(e){
                e.hide();
            });
            $$('dl[x-group="' + previous_group + '"]').each(function(e){
                e.show();
            });
        //$$('div[x-group=' + previous_group + ']').fadeIn(1000);
        });

        $('sub-slide-products-next-button').observe('click',function(e){
            var current_group = parseInt($(this).readAttribute('x-show-group'));
            var max_group = parseInt($(this).readAttribute('x-max-group'));
            if(current_group >= max_group){
                return false;
            }
            var next_group = current_group + 1;
            $(this).writeAttribute('x-show-group',next_group);
            $('sub-slide-products-prev-button').writeAttribute('x-show-group',next_group)

            $$('dl[x-group="' + current_group + '"]').each(function(e){
                e.hide();
            });
            $$('dl[x-group="' + next_group + '"]').each(function(e){
                e.show();
            });
        //$('div[x-group=' + next_group + ']').fadeIn(1000);
        });
    }
    */

    // translate
    if((typeof website_lang) != 'undefined' && website_lang == 'fr'){
        google_auto_translate();
    }
}

window.onload = load;

