var j = jQuery.noConflict();
var flashMovie = null;

j(document).ready(function() {
    if (typeof(retailer) != 'undefined') {
        j.ajax({
            url: '/wp-content/themes/tv-elements/resellers.json',
            dataType: "json",
            success: function(data) {
                
                var formatedData = j.map(data, function(reseller) {
                    return {
                        value: reseller.name + ", " + reseller.zipcode + " " + reseller.city,
                        name: reseller.name,
                        street: reseller.street,
                        zipcode: reseller.zipcode,
                        city: reseller.city,
                        phone: reseller.phone
                    }
                });
                //console.log(formatedData);
                j("#search-text").autocomplete({
                    source: formatedData,
                    minLength: 1,
                    select: function(event, ui) {
                        j('#retailer').css('display','block');
                        j('#retailer .namn').text(ui.item.name);
                        j('#retailer .adress label').text('Adress:');
                        j('#retailer .adress p').text(ui.item.street);
                        j('#retailer .postadress label').text('Postadress:');
                        j('#retailer .postadress p').text(ui.item.zipcode + ', ' + ui.item.city);
                        j('#retailer .telefon label').text('Telefonnr:');
                        j('#retailer .telefon p').text(ui.item.phone);
                    }
                });
            }
        });
    }

    var wordsLeft;
    var maxLength;
    j('#motivation').keyup(function() {
        var $textarea = j(this);
        var val = $textarea.val();
        wordsLeft = 20 - (val.split(' ')).length;
        if (wordsLeft <= 0) {
            if (!maxLength) {
                maxLength = val.length;
            }
            $textarea.val(val.slice(0, maxLength));
            wordsLeft = 0;
        }
        
        if ($textarea.val() == '') wordsLeft = 20;
        j('.words-left').text(wordsLeft + ' ord kvar');
    });

});

j(document).ready(function () {
    flashMovie = j('#flash-content');

    flashMovie.flash({
        swf: 'wp-content/themes/tv-elements/conti-video.swf',
        width: 960,
        height: 430,
        wmode: 'transparent'
    });

    j('#frame-container').find('.show-contest-terms').fancybox({
        padding: 0
    });

    var timer;

    j('#frame-container').find('.start').click(function(e) {

        j('#intro').fadeOut(350);
        playVideo();
        
        timer = setTimeout(function() {
            pauseVideo();
            j('#pre-contest').fadeIn(350);
        }, 17000);
        
        e.preventDefault();
    });
    
    j('#pre-contest').find('.button').click(function(e) {
        j('#pre-contest').fadeOut(350, function() {
            j('#contest').fadeIn(350);
        });
        e.preventDefault(); 
    });
    
    j('#contest').find('.button').click(function(e) {
        var error = false;
        
        if (!j("input[name=q1]:checked").val()) {
            j('#q1').fadeOut(100, function() {
               j(this).fadeIn(100, function() {
                    j('#q1').fadeOut(100, function() {
                       j(this).fadeIn(100, function() {

                       }); 
                    });                   
               }); 
            });
            error = true;
        }
        if (!j("input[name=q2]:checked").val()) {
            j('#q2').fadeOut(100, function() {
               j(this).fadeIn(100, function() {
                    j('#q2').fadeOut(100, function() {
                       j(this).fadeIn(100); 
                    });                   
               }); 
            });
            error = true;
        }
        
        if (!error){
            j('#contest').fadeOut(350, function() {
                j('#submit').fadeIn(350);
            });
        }
       e.preventDefault();
    });

    j('#name').data('defaultText', j('#name').val());
    j('#email').data('defaultText', j('#email').val());
    j('#address').data('defaultText', j('#address').val());
    j('#city').data('defaultText', j('#city').val());
    j('#zipcode').data('defaultText', j('#zipcode').val());
    j('#phone').data('defaultText', j('#phone').val());
    
    j('#submit').find('input').focus(function() {
        if ( j(this).val() == j(this).data('defaultText')) {
            j(this).val('').removeClass('inactive');
        }
    }).blur(function() {
        var val = j(this).val();
        if (val == '') {
            j(this).val(j(this).data('defaultText')).addClass('inactive');
        }
    });


    j('#submit').find('.submit').click(function(e) {

        var $name = j('#name').val();
        var $email = j('#email').val();
        var $address = j('#address').val();
        var $city = j('#city').val();
        var $zipcode = j('#zipcode').val();
        var $phone = j('#phone').val();
        var $motivation = j('#motivation').val();
        var $question_1 = j('input[name=q1]:checked').val()
        var $question_2 = j('input[name=q2]:checked').val();
        var $accept = j('#accept-terms:checked').val();

        j.ajax({
            url: 'wp-content/themes/tv-elements/ajax.php',
            data: 'action=submit_result&name=' + $name + '&address=' + $address + '&zipcode=' + $zipcode + '&city=' + $city + '&phone=' + $phone + '&email=' + $email + '&motivation=' + $motivation + '&question_1=' + $question_1 + '&question_2=' + $question_2 + '&accept=' + $accept,
            type: 'post',
            success: function(data) {
                if (data === 'error-db') {
                    j('#submit').find('.response').text('Databasfel. Var vänlig försök igen.').fadeIn(150);
                } else if (data === 'error-data') {
                    j('#submit').find('.response').text('Alla fält är obligatoriska.').fadeIn(150);
                } else if (data === 'error-email') {
                    j('#submit').find('.response').text('E-postadressen du angav är ogiltlig.').fadeIn(150);
                } else if (data === 'success') {
                    j('#submit').find('*').fadeOut(350);
                    j('#submit').find('.response').appendTo('#submit').css({'top': '160px', 'left': '300px'}).text('Tack! Ditt svar har registrerats').fadeIn(150);
                } else {
                    j('#submit').find('.response').text('Något gick fel. Försök igen senare.').fadeIn(150);
                }
            },
            error: function() {
                console.log('error');
            }
        });
        e.preventDefault();
    });


});




/**************** Functions *****************/

function parseXml(xml) {
    if (jQuery.browser.msie && jQuery.browser.version.toString().substring(0,1) == "6"){
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(xml);
        xml = xmlDoc;
    }
    return xml;
}

function playVideo() {
    flashMovie.flash(function() {
        this.playVideo();
    });
}

function pauseVideo() {
    flashMovie.flash(function() {
        this.pauseVideo();
    });
}


/* IE PNG fix multiple filters */
(function (j) {
    if (!j) return;
    j.fn.extend({
        fixPNG: function(sizingMethod, forceBG) {
            if (!(j.browser.msie)) return this;
            var emptyimg = "empty.gif"; //Path to empty 1x1px GIF goes here
            sizingMethod = sizingMethod || "scale"; //sizingMethod, defaults to scale (matches image dimensions)
            this.each(function() {
                var isImg = (forceBG) ? false : jQuery.nodeName(this, "img"),
                imgname = (isImg) ? this.src : this.currentStyle.backgroundImage,
                src = (isImg) ? imgname : imgname.substring(5,imgname.length-2);
                this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + sizingMethod + "')";
                if (isImg) this.src = emptyimg;
                else this.style.backgroundImage = "url(" + emptyimg + ")";
            });
            return this;
        }
    });
})(jQuery);


