var WizardParams = {
    channel_user_id: null,
    media_format: null,
    region: null,
    tqry: '',
    feed_type: 'now'
};
var Translation = {
    now_feed_type: 'Now in cinemas',
    coming_feed_type: 'Coming to cinemas',
    newest_feed_type: 'Latest trailers',
    search_feed_type: 'Search by:'
};
var TranslationFeeds = {
    now_feed_type: 'Now in cinemas',
    coming_feed_type: 'Coming to cinemas',
    newest_feed_type: 'Latest trailers',
    search_feed_type: 'Search by:'
};
var timeout = null;

$(document).ready(function(){
    if (WizardParams.channel_user_id != null && WizardParams.media_format != null){
        
    }

    $('#i_movie_search_string').focus(function(){
        $(this).select();
    });


    $('#user_id').focus(function() {
        WizardParams.tqry = $(this).val();
        $(this).select();
    //if (WizardParams.channel_user_id == null) $(this).val('');
    //else $(this).val(WizardParams.channel_user_id.channel_user_id);
       
    });
    $('#user_id').blur(function() {
        //if ($(this).val().length == 0 || $(this).val() ==  WizardParams.tqry) $(this).val(WizardParams.tqry);
        });

    $("#user_id").keyup(function(){
        WizardParams.channel_user_id = null;
        $("#user_id").css({
            'color': '#444751'
        });
        
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout ( function(){
            $.post("/v2.0/index.php", {
                action: "chuid_vldt",
                chuid: $("#user_id").val()
            }, function(response){
                if (response.success == 1){
                    $("#user_id").css({
                        'color': '#20B12C'
                    });
                    WizardParams.channel_user_id = response.CHUID;
                }else{
                    $("#user_id").css({
                        'color': '#444751'
                    });
                }

                
            }, "json");
        }, 1000);
    });

    $('#i_gsd_btn').click(function(){
        if(WizardParams.channel_user_id != null){
            $.post("/v2.0/index.php", {
                action: "intro",
                chuid: $("#user_id").val(),
                media: $("#product_type").val()
            }, function(response){
                if (response.success == 1){
                    
                }else{
                //
                }
                location.replace('/v2.0/');

            }, "json");
        //$('#fade , .popup_block').fadeOut();
            
        }
    });

    $('#product_select_center a').click(function(){
        $.post("/v2.0/index.php", {
            action: "changemf",
            media: $(this).attr('rel'),
            messages: TranslationFeeds
        }, function(response){
            if (response.success == 1){
                WizardParams.media_format = response.MediaFormat;
                $('#product_select_center a').attr('class', 'default');
                $('#product_select_center a[rel="'+ WizardParams.media_format.name +'"]').attr('class', 'active');
                applyTranslation(response.trMsgs);
            }else{
                    
        }
        }, "json");
        return false;
    });

    $('#country_selector a').click(function(){
        $.post("/v2.0/index.php", {
            action: "changectry",
            region: $(this).attr('rel'),
            messages: Translation
        }, function(response){
            if (response.success == 1){
                WizardParams.region = response.Region;
                $('#i_ctry_img').attr('src', '/v2.0/images/' + WizardParams.region.alias_name + '.png');
                applyTranslation(response.trMsgs);
            }else{

        }
        }, "json");


        return false;
    });

    $('#now_in_cinemas').change(function(){
        if($(this).attr('checked')){
            WizardParams.feed_type = 'now';
            $('#i_movie_search_string').attr('disabled', 'disabled');
        }
    });
    $('#coming_to_cinemas').change(function(){
        if($(this).attr('checked')){
            WizardParams.feed_type = 'coming';
            $('#i_movie_search_string').attr('disabled', 'disabled');
        }
    });
    $('#latest_trailers').change(function(){
        if($(this).attr('checked')){
            WizardParams.feed_type = 'newest';
            $('#i_movie_search_string').attr('disabled', 'disabled');
        }
    });
    $('#search_movies_by').change(function(){
        if($(this).attr('checked')){
            WizardParams.feed_type = 'search';
            $('#i_movie_search_string').attr('disabled', '').focus().select();
        }
    });
    $('#i_load_movies').click(function(){
        //if ($('#table_wrapper').is(":hidden")){
        $.post("/v2.0/index.php", {
            action: "getmovies",
            limit: $('#i_movie_qty').val(),
            feed_type: WizardParams.feed_type,
            params: grabOptions()
        }, function(response){
            if (response.success == 1){
                $('#table_wrapper').html(response.respHTML).show();
                $('#movie_list input[type="checkbox"]').click(function(){
                        
                    if ($(this).attr('checked')){
                        if ($('#i_feed_movies').length > 0){
                            var vv = $('#i_feed_movies').val();
                            vv = vv + '|' + $(this).val();
                            $('#i_feed_movies').val(vv);
                        }else $('#container').append('<input id="i_feed_movies" type="hidden" name="movies" value="'+ $(this).val() +'">');
                    }else{
                        if ($('#i_feed_movies').length > 0){
                            var vv = $('#i_feed_movies').val();
                            var chboxVal = $(this).val();
                            var arr = new Array();
                            var mvs = vv.split('|');
                            $.each(mvs, function(index, value){
                                if (chboxVal != value){
                                    arr.push(value);
                                }
                            });
                                
                            if (arr.length == 0) $('#i_feed_movies').remove();
                            else $('#i_feed_movies').val(arr.join('|'));
                        }
                    }
                });
            }else{
                $('#table_wrapper').html('').hide();
                $('#i_feed_movies').remove();
            }
        }, "json");
    //}else {
    //    $('#table_wrapper').html('').hide();
    //    $('.feed_movies').remove();
    //}
    });


    $('#i_pwidth_btnp, #i_pwidth_btnm').click(function(){
        if ($('#aspect_ratio').attr('checked')){
            var el = $(this);
            var res = new Number($('#player_width').val());
            res = (el.attr('id') == 'i_pwidth_btnp') ? Math.round((res + 1)*9/16) : Math.round((res - 1)*9/16);
            if (res <= 0) res = 1;
            $('#player_height').val(res);
        }

       
		
    });
    $('#i_pheight_btnp, #i_pheight_btnm').click(function(){
        if ($('#aspect_ratio').attr('checked')){
            var el = $(this);
            var res = new Number($('#player_height').val());
            res = (el.attr('id') == 'i_pheight_btnp') ? Math.round((res + 1)*16/9) : Math.round((res - 1)*16/9);
            if (res <= 0) res = 1;
            $('#player_width').val(res);
        }
		
    });

    $('#i_vast_url').focus(function(){
        $(this).select();
    });

    $('#bar_link').click(function(){
        //console.debug($(this));
        });

    $('#i_preview, #i_preview1, #i_preview2, #i_preview3').click(function(){
        var pParams = grabOptions();
        $.post("/v2.0/index.php", {
            action: "code",
            params: pParams,
            escape: 0
        }, function(response){
            if (response.success == 1){
                $('#i_player_preview').html(response.respHTML);

                $('#i_player_preview').fadeIn().prepend('<a href="#" class="close"></a>');

                var popMargTop = ($('#i_player_preview').height() + 80) / 2;
                var popMargLeft = ($('#i_player_preview').width() + 80) / 2;

                    
                $('#i_player_preview').css({
                    'margin-top' : -popMargTop,
                    'margin-left' : -popMargLeft
                });

                    
                $('body').append('<div id="fade"></div>');
                $('#fade').css({
                    'filter' : 'alpha(opacity=80)'
                }).fadeIn();

                $('a.close, #fade').live('click', function() {
                    $('#fade , .popup_block').fadeOut(function() {
                        $('#fade, a.close').remove();
                    });
                    return false;
                });
            }else{

        }
        }, "json");
    });

    $('#tab1 input').change(function(){
        if (!$('#table_wrapper').is(":hidden")){
            $('#i_load_movies').trigger('click');
        }
    });

    $("#player_width").keyup(function(){
        if ($('#aspect_ratio').attr('checked')){
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout ( function(){
                var res = new Number($('#player_width').val());
                res = Math.round(res*9/16);
                if (res <= 0) res = 1;
                $('#player_height').val(res);

            }, 100);
        }
       
    });
    $("#player_height").keyup(function(){
        if ($('#aspect_ratio').attr('checked')){
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout ( function(){
                var res = new Number($('#player_height').val());
                res = Math.round(res*16/9);
                if (res <= 0) res = 1;
                $('#player_width').val(res);

            }, 100);
        }
        
    });

    $('#i_copy_code').click(function(){
        SelectText('link_wrapper');
    });


    $('#i_movie_search_string').autocomplete({
        serviceUrl:'/v2.0/',
        post: true,
        minChars:2,
        delimiter: /(,|;)\s*/,
        maxHeight:400,
        width:300,
        zIndex: 9999,
        deferRequestBy: 300,
        params: {
            action:'search',
            params: {feed_type: function(){return WizardParams.feed_type;}, feed_type_limit: function(){return $('#i_movie_qty').val();},
                        movie_search: function() {return $('select[name="movie_search"]').val();},
                        movie_search_string: function(){return $('#i_movie_search_string').val();}
                    }
            },
        onSelect: function(value, data)
        {
            /*
            var mData = data.split(':');
            var mtypes = mData[1].split('_');
            enableMediaFormat(mtypes[0], mtypes[1], mtypes[2]);
            $('#i_mod_new').val(mData[0]);
            */
            //$('#i_mod_new').val(data);
            //enableSubmit();

        }
    });



    getTranslationMessages();
    
    doTranslate();
    
});


function getTranslationMessages(){
    $('.trion').each(function(){
        var trMsg = $(this).attr('title');
        var trTr = '';
        if ($(this)[0].tagName == 'INPUT'){
            trTr = $(this).val();
        }else{
            trTr = $(this).text();
        }
        Translation[trMsg] = trTr;
    });
}

function doTranslate(){
    $.post("/v2.0/index.php", {
        action: "gettranslation",
        messages: Translation
    }, function(response){
        if (response.success == 1){
            applyTranslation(response.trMsgs);
        }else{

    }
    }, "json");
}

function applyTranslation(trMsgs){
    $.each(trMsgs, function(a){
        var el = $('[title="'+ a +'"].trion');
        if (el.length){

            if (el[0].tagName == 'INPUT'){
                el.val(trMsgs[a]);
            }else{
                el.html(trMsgs[a]);
            }

            
        //console.debug('[title="'+ a +'"].trion');
        //console.debug($('[title="'+ a +'"].trion').get(0).tagName);
        }
        
        
    });
}

function getPlayerCode(){
    $.post("/v2.0/index.php", {
        action: "code",
        params: grabOptions()
    }, function(response){
        if (response.success == 1){

            var codeHTML = response.respHTML;
            codeHTML = '&lt;!-- START: PREVIEWNETWORKS.COM FLASH PLAYER version 4.0 --&gt;<br/>' + codeHTML + '<br/>&lt;br/&gt;&lt;a style="font-family: verdana; color:cccccc; font-size: 8pt; text-decoration:none" alt="previewnetworks.com" target="_blank" href="http://www.previewnetworks.com/"&gt;Powered by Preview Networks&lt;/a&gt;<br/>&lt;!-- END: PREVIEWNETWORKS.COM FLASH PLAYER version 4.0 --&gt;';
            $('#link_wrapper').html(codeHTML);
            $('#html5_wrapper').html(response.html5HTML);
            $('#stream_wrapper').html(response.streamHTML);
        }else{

    }
    }, "json");
}


function grabOptions(){
    var options = {};
    $('input, select').each(function(){
        var el = $(this);
        if (el.is(':radio')){
            if (el.attr('checked')) options[el.attr('name')] = el.val();
        }else if(el.is(':checkbox')){
            options[el.attr('name')] = (el.attr('checked')) ? el.val() : '0';
        }else options[el.attr('name')] = el.val();
    });
    
    return options;
}

function SelectText(element) {
    var text = document.getElementById(element);
    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}

