$(function(){
    initGallery();
    initPage();
    initTabs();
    initOpenClose();
    cloneProduct();
    initClearForms();
});
function initClearForms(){
    $('.contact-form').each(function(){
        var form = $(this);
        var resetBtn = form.find('.btn-clear');
        resetBtn.click(function(){
            form.trigger('reset');
            return false;
        });
    });
}
function cloneProduct(){
    $('.add-box').each(function(){
                var counter = 1;
        var _this = $(this);
        var row = _this.find('.add-row');
        var addHolder = _this.find('.add-holder');
        var addBtn = _this.find('a.add');
        addBtn.click(function(){
            var clone = addHolder.clone();
            clone.find('label').hide();
            clone.find('#description').removeAttr('value').removeAttr('name').attr('name',"part_no_"+counter);
                        clone.find('#quantity').removeAttr('value').removeAttr('name').attr('name',"quantity_"+counter);
            row.append(clone);
                        $("#no_of_parts").attr('value',counter)
                        counter = counter + 1
            return false;
        });
    });
}
// initGallery
function initGallery(){
    $('div.main-gallery').fadeGallery({
        slideElements:'li.cont',
        scrollElParent: 'ul.list',
        pagerLinks:'div.swicher li',
        switchTime:3000,
        slideNum:'div.swicher',
        autoRotation:true,
        pauseOnHover: false
    });
}
//init initPage
function initPage()
{
    clearFormFields({
        clearInputs: true,
        clearTextareas: true,
        passwordFieldText: true,
        addClassFocus: "focus",
        filterClass: "default"
    });
}
function clearFormFields(o)
{
    if (o.clearInputs == null) o.clearInputs = true;
    if (o.clearTextareas == null) o.clearTextareas = true;
    if (o.passwordFieldText == null) o.passwordFieldText = false;
    if (o.addClassFocus == null) o.addClassFocus = false;
    if (!o.filterClass) o.filterClass = "default";
    if(o.clearInputs) {
        var inputs = document.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++ ) {
            if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
                inputs[i].valueHtml = inputs[i].value;
                inputs[i].onfocus = function ()    {
                    if(this.valueHtml == this.value) this.value = "";
                    if(this.fake) {
                        inputsSwap(this, this.previousSibling);
                        this.previousSibling.focus();
                    }
                    if(o.addClassFocus && !this.fake) {
                        this.className += " " + o.addClassFocus;
                        this.parentNode.className += " parent-" + o.addClassFocus;
                    }
                }
                inputs[i].onblur = function () {
                    if(this.value == "") {
                        this.value = this.valueHtml;
                        //if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
                    }
                    if(o.addClassFocus) {
                        this.className = this.className.replace(o.addClassFocus, "");
                        this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
                    }
                }
//                if(o.passwordFieldText && inputs[i].type == "password") {
//                    var fakeInput = document.createElement("input");
//                    fakeInput.type = "text";
//                    fakeInput.value = inputs[i].value;
//                    fakeInput.className = inputs[i].className;
//                    fakeInput.fake = true;
//                    inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
//                    inputsSwap(inputs[i], null);
//                }
            }
        }
    }
    if(o.clearTextareas) {
        var textareas = document.getElementsByTagName("textarea");
        for(var i=0; i<textareas.length; i++) {
            if(textareas[i].className.indexOf(o.filterClass)) {
                textareas[i].valueHtml = textareas[i].value;
                textareas[i].onfocus = function() {
                    if(this.value == this.valueHtml) this.value = "";
                    if(o.addClassFocus) {
                        this.className += " " + o.addClassFocus;
                        this.parentNode.className += " parent-" + o.addClassFocus;
                    }
                }
                textareas[i].onblur = function() {
                    if(this.value == "") this.value = this.valueHtml;
                    if(o.addClassFocus) {
                        this.className = this.className.replace(o.addClassFocus, "");
                        this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
                    }
                }
            }
        }
    }
    function inputsSwap(el, el2) {
        if(el) el.style.display = "none";
        if(el2) el2.style.display = "inline";
    }
}

$(document).ready(initPage);
/*
if (window.addEventListener)
    window.addEventListener("load", initPage, false);
else if (window.attachEvent)
    window.attachEvent("onload", initPage);
*/


function selectTab(l, noLink) {
    l = $(l);
    var c = null;
    var rel = l.attr("rel");
    if (rel) {
        c = $("." + rel);
    }
    if (c.length > 0) {
        $(l.data("tabs")).each(function(idx, tab) {
            if (tab[0] == l[0]) {
                tab.addClass("active");
                c.css("display", "block");
            } else {
                tab.removeClass("active");
                var tabC = $("." + tab.attr("rel"));
                if (tabC) {
                    tabC.css("display", "none");
                }
            }
        });

        if (!noLink) {
            // make the url bookmarkable
            window.location.href = getCleanUrl() + "#" + encodeURIComponent(rel);
        }
    }
}

//init tabs
function initTabs() {
    var hash = getUrlHashArg();
    var ref = hash;
    var refIdx = 0;
    if (hash && (refIdx = hash.indexOf('_')) != -1) {
        hash = hash.substr(0, refIdx);
    }

    var sets = $("ul.tabset");
    sets.each(function(i, v) {
        var noLink = $(v).hasClass("no-link");
        var tabs = [];
        var links = $("a.tab", v);
        links.each(function(j, l) {
            var l = $(l);
            tabs.push(l);
            l.data("tabs", tabs);

            var c = null;
            var rel = l.attr("rel");
            if (rel) {
                c = $("." + rel);
            }
            if (c.length > 0) {
                // if there is a hash in the URL, try to select the requested tab
                if ((!noLink && hash && hash == rel) || ((noLink || !hash) && l.hasClass("active"))) {
                    l.addClass("active");
                    c.css("display", "block");
                } else {
                    l.removeClass("active");
                    c.css("display", "none");
                }
            }

            l.click(function() {
                selectTab(this, noLink);
                return false;
            });
        });
    });
}

function initTabLinks() {
    $("a").each(function(i, v) {
        v = $(v);
        var href = v.attr("href");
        if (href) {
            var pos = href.indexOf("#");
            if (pos != -1) {
                var tabStr = href.substr(pos + 1);
                if (tabStr.length > 0) {
                    var l = $("a.tab[rel=" + tabStr + "]");
                    if (l.length > 0) {
                        v.click(function() {
                            selectTab(l[0], false);
                            return false;
                        });
                    }
                }
            }
        }
    });
}

function getCleanUrl() {
    var uri = "";
    var hashPosition = window.location.href.indexOf('#');
    if (hashPosition != -1) {
        uri = window.location.href.substr(0, hashPosition);
    } else {
        uri = window.location.href;
    }
    return uri;
}

function getUrlHashArg() {
    var hash = "";
    var hashPosition = window.location.href.indexOf('#');
    if (hashPosition != -1) {
        hash = window.location.href.substr(hashPosition + 1);
    } else {
        hash = null;
    }

    return hash;
}


$(document).ready(function() {
    initTabs();
    initTabLinks();
});

/*
if (window.addEventListener)
    window.addEventListener("load", initTabs, false);
else if (window.attachEvent && !window.opera)
    window.attachEvent("onload", initTabs);
*/

/*
 * jQuery galleryScroll v1.5.2
 */

/*
    ************* OPTIONS ************************************** default ****************
    btPrev         - link for previos [selector]        btPrev: 'a.link-prev'
    btNext         - link for next [selector]        btNext: 'a.link-next'
    holderList     - image list holder [Tag name]        holderList: 'div'
    scrollElParent - list [Tag name]            scrollElParent: 'ul'
    scrollEl       - list element [Tag name]        scrollEl: 'li'
    slideNum       - view slide numbers [boolean]        slideNum: false
    duration       - duration slide [1000 - 1sec]        duration : 1000
    step           - slide step [int]            step: false
    circleSlide    - slide circle [boolean]            circleSlide: true
    disableClass   - class for disable link    [string]     disableClass: 'disable'
    funcOnclick    - callback function            funcOnclick: null
    innerMargin    - inner margin, use width step [px]      innerMargin:0
    autoSlide      - auto slide [1000 - 1sec]               autoSlide:false
    *************************************************************************************
*/
// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
    var _options = jQuery.extend({
        slideElements:'div.frame > ul > li',
        pagerLinks:'div.pager a',
        btnNext:'a.link-next',
        btnPrev:'a.link-prev',
        btnPlayPause:false,
        btnPlay:false,
        btnPause:false,
        pausedClass:false,
        disabledClass:false,
        playClass:false,
        activeClass:'active',
        currentNum:false,
        allNum:false,
        startSlide:null,
        noCircle:false,
        pauseOnHover:true,
        autoRotation:false,
        autoHeight:false,
        onChange:false,
        switchTime:3000,
        duration:$.browser.msie && $.browser.version < 9 ? 0 : 650, 
        event:'click'
    },_options);

    return this.each(function(){
        // gallery options
        var _this = jQuery(this);
        var _slides = jQuery(_options.slideElements, _this);
        var _pagerLinks = jQuery(_options.pagerLinks, _this);
        var _btnPrev = jQuery(_options.btnPrev, _this);
        var _btnNext = jQuery(_options.btnNext, _this);
        var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
        var _btnPause = jQuery(_options.btnPause, _this);
        var _btnPlay = jQuery(_options.btnPlay, _this);
        var _pauseOnHover = _options.pauseOnHover;
        var _autoRotation = _options.autoRotation;
        var _activeClass = _options.activeClass;
        var _disabledClass = _options.disabledClass;
        var _pausedClass = _options.pausedClass;
        var _playClass = _options.playClass;
        var _autoHeight = _options.autoHeight;
        var _duration = _options.duration;
        var _switchTime = _options.switchTime;
        var _controlEvent = _options.event;
        var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
        var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
        var _startSlide = _options.startSlide;
        var _noCycle = _options.noCircle;
        var _onChange = _options.onChange;

        // gallery init
        var _hover = false;
        var _prevIndex = 0;
        var _currentIndex = 0;
        var _slideCount = _slides.length;
        var _timer;
        if(_slideCount < 2) return;

        _prevIndex = _slides.index(_slides.filter('.'+_activeClass));
        if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
        else _currentIndex = _prevIndex;
        if(_startSlide != null) {
            if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
            else _prevIndex = _currentIndex = parseInt(_startSlide);
        }
        _slides.hide().eq(_currentIndex).show();
        if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
        else _this.removeClass(_playClass).addClass(_pausedClass);

        // gallery control
        if(_btnPrev.length) {
            _btnPrev.bind(_controlEvent,function(){
                prevSlide();
                return false;
            });
        }
        if(_btnNext.length) {
            _btnNext.bind(_controlEvent,function(){
                nextSlide();
                return false;
            });
        }
        if(_pagerLinks.length) {
            _pagerLinks.each(function(_ind){
                jQuery(this).bind(_controlEvent,function(){
                    if(_currentIndex != _ind) {
                        _prevIndex = _currentIndex;
                        _currentIndex = _ind;
                        switchSlide();
                    }
                    return false;
                });
            });
        }

        // play pause section
        if(_btnPlayPause.length) {
            _btnPlayPause.bind(_controlEvent,function(){
                if(_this.hasClass(_pausedClass)) {
                    _this.removeClass(_pausedClass).addClass(_playClass);
                    _autoRotation = true;
                    autoSlide();
                } else {
                    _autoRotation = false;
                    if(_timer) clearTimeout(_timer);
                    _this.removeClass(_playClass).addClass(_pausedClass);
                }
                return false;
            });
        }
        if(_btnPlay.length) {
            _btnPlay.bind(_controlEvent,function(){
                _this.removeClass(_pausedClass).addClass(_playClass);
                _autoRotation = true;
                autoSlide();
                return false;
            });
        }
        if(_btnPause.length) {
            _btnPause.bind(_controlEvent,function(){
                _autoRotation = false;
                if(_timer) clearTimeout(_timer);
                _this.removeClass(_playClass).addClass(_pausedClass);
                return false;
            });
        }

        // gallery animation
        function prevSlide() {
            _prevIndex = _currentIndex;
            if(_currentIndex > 0) _currentIndex--;
            else {
                if(_noCycle) return;
                else _currentIndex = _slideCount-1;
            }
            switchSlide();
        }
        function nextSlide() {
            _prevIndex = _currentIndex;
            if(_currentIndex < _slideCount-1) _currentIndex++;
            else {
                if(_noCycle) return;
                else _currentIndex = 0;
            }
            switchSlide();
        }
        function refreshStatus() {
            if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
            if(_currentNum) _currentNum.text(_currentIndex+1);
            if(_allNum) _allNum.text(_slideCount);
            _slides.eq(_prevIndex).removeClass(_activeClass);
            _slides.eq(_currentIndex).addClass(_activeClass);
            if(_noCycle) {
                if(_btnPrev.length) {
                    if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
                    else _btnPrev.removeClass(_disabledClass);
                }
                if(_btnNext.length) {
                    if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
                    else _btnNext.removeClass(_disabledClass);
                }
            }
            if(typeof _onChange === 'function') {
                _onChange(_this, _currentIndex);
            }
        }
        function switchSlide() {
            _slides.eq(_prevIndex).fadeOut(_duration);
            _slides.eq(_currentIndex).fadeIn(_duration);
            if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
            refreshStatus();
            autoSlide();
        }

        // autoslide function
        function autoSlide() {
            if(!_autoRotation || _hover) return;
            if(_timer) clearTimeout(_timer);
            _timer = setTimeout(nextSlide,_switchTime+_duration);
        }
        if(_pauseOnHover) {
            _this.hover(function(){
                _hover = true;
                if(_timer) clearTimeout(_timer);
            },function(){
                _hover = false;
                autoSlide();
            });
        }
        refreshStatus();
        autoSlide();
    });
}

// open-close init
function initOpenClose() {
    jQuery('div.slide-block').OpenClose({
        activeClass:'active',
        opener:'a.open-close',
        slider:'div.block',
        effect:'slide',
        animSpeed:1000
    });
}

// open-close plugin
jQuery.fn.OpenClose = function(_options){
    // default options
    var _options = jQuery.extend({
        activeClass:'active',
        opener:'.opener',
        slider:'.slide',
        animSpeed: 500,
        animStart:false,
        animEnd:false,
        effect:'fade',
        event:'click'
    },_options);

    return this.each(function(){
        // options
        var _holder = jQuery(this);
        var _slideSpeed = _options.animSpeed;
        var _activeClass = _options.activeClass;
        var _opener = jQuery(_options.opener, _holder);
        var _slider = jQuery(_options.slider, _holder);
        var _animStart = _options.animStart;
        var _animEnd = _options.animEnd;
        var _effect = _options.effect;
        var _event = _options.event;
        if(_slider.length) {
            _opener.bind(_event,function(){
                if(!_slider.is(':animated')) {
                    if(typeof _animStart === 'function') _animStart();
                    if(_holder.hasClass(_activeClass)) {
                        _slider[_effect=='fade' ? 'fadeOut' : 'slideUp'](_slideSpeed,function(){
                            if(typeof _animEnd === 'function') _animEnd();
                        });
                        _holder.removeClass(_activeClass);
                    } else {
                        _holder.addClass(_activeClass);
                        _slider[_effect=='fade' ? 'fadeIn' : 'slideDown'](_slideSpeed,function(){
                            if(typeof _animEnd === 'function') _animEnd();
                        });
                    }
                }
                return false;
            });
            if(_holder.hasClass(_activeClass)) _slider.show();
            else _slider.hide();
        }
    });
}

