var translation_dia;
var clip_dia_xsl;


var GEO_TAB = false;
var map;
var gp_form =  null;
var gp_grid = undefined;
var gp_grid2 = undefined;
function showClip3(cid) {
    /*
    var s1 = new SWFObject('/js/player/player.swf','player','426','285','9');
    s1.addParam('allowfullscreen','true');
    s1.addParam('allowscriptaccess','always');
    s1.write('preview');
    */
    $.ajax({
        type     : "POST",
        url      : "/get-clip-xml",
        dataType : "xml",
        data     : {
            cid : cid
        },
        success  : function(xml_data) {
            var URL = null;
            var type;
            jQuery("/data/urls/item", xml_data).each(function(){ 
                type = jQuery('source-type-alias', $(this)).text();
                URL = jQuery('url', $(this)).text();
                
            });
            if(URL != null) {
                switch(type) {
                    case 'flv': 
                        var s1 = new SWFObject('/js/player/player.swf','player','586','350','9');
                        s1.addParam('allowfullscreen','true');
                        s1.addParam('allowscriptaccess','always');
                        s1.write('preview');
 
                        s1.addParam('flashvars','file=' + URL + '&image=/cache/' + cid + '-cpw.jpg');
                        s1.write('preview');
                        break;
                    case 'pureswf': 
                        var s1 = new SWFObject(URL,'player','586','350','9');
                        s1.write('preview');
                        break;
                    case 'av':
                        //alert("AV клип стартует здесь");
                        mplugin_url = URL;
                        mplugin_bgimage = '/cache/'+ cid + '-cpw.jpg';
                        var av_div = document.getElementById("preview");
                        gogoAvPlugin(av_div);
                        break;
                }
            }

       },
        error:on_response_error
    });            
}
function showClip2(cid) {
    var s1 = new SWFObject('/js/player/player.swf','player','586','350','9');
    s1.addParam('allowfullscreen','true');
    s1.addParam('allowscriptaccess','always');
    s1.write('preview');
    
    $.ajax({
        type     : "POST",
        url      : "/get-clip-xml",
        dataType : "xml",
        data     : {
            cid : cid
        },
        success  : function(xml_data) {
            var URL = null;
            jQuery("/data/urls/item", xml_data).each(function(){ 
                var type = jQuery('source-type-alias', $(this)).text();
                if(type == 'flv')
                    URL = jQuery('url', $(this)).text();
            });
            if(URL != null) {
                s1.addParam('flashvars','file=' + URL + '&image=/cache/' + cid + '-cpw.jpg');
                s1.write('preview');
            }

       },
        error:on_response_error
    });            
}


function showClip(cid) {
    $.ajax({
        type     : "POST",
        url      : "/get-clip-xml",
        dataType : "xml",
        data     : {
            cid : cid
        },
        success  : function(data) {
            $('#dia_clip').empty();
            var empty_xml = parseXMLFromString("<data/>", 'application/xml');
            transform_xml_doc(clip_dia_xsl, data, document.getElementById("dia_clip"));
            translation_dia = $("#dia_clip").dialog({
                resizable   : false,  
                width:"35em", 
                height:"29em", 
                /*modal:true,
                buttons     : {
                    'Установить' : function() {
                    },
                    'Отменить' : function() {
                        translation_dia.dialog('close');
                    }
                },*/
                close : function (){
                    //$('#dia_clip').empty();
                    //translation_dia.dialog('destroy');
                }
            });
            translation_dia.dialog('open');
       },
        error:on_response_error
    });            
}



$(document).ready( function() {

    clip_dia_xsl = load_xml_doc('/xml/ajax-clip.xsl');
/*    function ImgControl() {
    }

    ImgControl.prototype = new GControl();
// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
    ImgControl.prototype.initialize = function(map1) {
        var container = document.createElement("div");
        container.style.display = 'inline';
        var imgbar = document.createElement("div");
        this.setImgBarStyle_(imgbar);
        container.appendChild(imgbar);
        var i2 = $('<img src="/img/avlog4.jpg"/>');
        $(i2).click( function (ev) {
            window.location='/';
        }).appendTo( imgbar );
        map.getContainer().appendChild(container);
        return container;
    }

    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    ImgControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50, 7));
    }

    ImgControl.prototype.setImgBarStyle_ = function(button) {
        button.style.padding = "2px";
        button.style.marginBottom = "3px";
        button.style.textAlign = "left";
        button.style.width = "auto";
        button.style.cursor = "pointer";
    }
*/
    function TextualZoomControl() {
    }


// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object

    TextualZoomControl.prototype = new GControl();
// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
    TextualZoomControl.prototype.initialize = function(map1) {
        var container = document.createElement("div");
        container.style.display = 'inline';
        var toolbarDiv = document.createElement("div");
        this.setButtonStyle_(toolbarDiv);
        container.appendChild(toolbarDiv);
        var i1 = $('<input type="button" class="enter ml05m" value=""/>');
        var myself = this;
        $(i1).click( function (ev) {
            if(map.getCurrentMapType() == G_HYBRID_MAP ) {
                map.setMapType( G_NORMAL_MAP );
            } else {
                map.setMapType( G_HYBRID_MAP );
            }
            myself.updateMapType();
        }).appendTo( toolbarDiv );
        this.typeButton = i1;
        myself.updateMapType(map1.getCurrentMapType());
        /*
        var i3 = $('<input type="button" class="enter ml05m" value="Справочник"/>');
        $(i3).click( function (ev) {
            toggle_geo_pane();
        }).appendTo( toolbarDiv );
        */
        map.getContainer().appendChild(container);
        return container;
    }

    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    TextualZoomControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
    }

    TextualZoomControl.prototype.updateMapType = function(s) {
       var tp = null;
        if( s == undefined )
      	    tp = map.getCurrentMapType();
        else
  	        tp = s;

        switch( tp ) {
  	        case G_NORMAL_MAP:
		        $(this.typeButton).val('Гибрид');
		        break;
  	        case G_HYBRID_MAP:
		        $(this.typeButton).val('Нормал');
		        break;
        }
    }
    // Sets the proper CSS for the given button element.
    TextualZoomControl.prototype.setButtonStyle_ = function(button) {
        button.style.textDecoration = "none";
        button.style.color = "#0000cc";
        button.style.backgroundColor = "transparent";
        button.style.font = "small Arial";
        button.style.border = "none";
        button.style.padding = "2px";
        button.style.marginBottom = "3px";
        button.style.textAlign = "right";
        button.style.width = "auto";
        button.style.cursor = "pointer";
    }

    function toggle_geo_pane() {
	    if ( !GEO_TAB ) {
		    $('#geo_left').css('width','70%');
            //$('#geo_right').css('width','30%');
		    $('#geo_right').css('width','500px');
		    $('#geo_tab').show();
		    GEO_TAB = true;
	    } 
        else {
		    $('#geo_left').css('width','100%');
		    $('#geo_right').css('width','0%');
		    $('#geo_tab').hide();
		    GEO_TAB = false;
	    }
    }

    toggle_geo_pane();

    function load_map() {
        map = new GMap2(document.getElementById("gmap"));
        mcoo = new GLatLng(55.76944933, 37.63724383);
        map.setCenter(mcoo, 13);
        map.addControl(new GSmallMapControl());
        map.addControl(new TextualZoomControl(map));
//        map.addControl(new ImgControl(map));
        //map.addControl(new TextualZoomControl(map), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7,7)));
        map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,20)));
    }

    load_map();
    function clips_rows_update() {
        clips_grid.gpArray.draw_markers();
        $('.clip_ref').click(function(ev) {
            var cid = this.id.match(/\w(\d+)$/)[1];
            var e = clips_grid.gpArray.grid_data[cid];
            if(e != undefined && e.lat != "" && e.lng != "") {
                clips_grid.gpArray.draw_marker(cid);
            } 
        });
    }
    var clips_grid = new GeoPointGrid({
        xsl_file  : '/xml/ajax-clip-grid.xsl',
        tag_id    : 'clips_phgrid',
        url       : '/get-clips-xml',
        pager     : new PhenoPager({tag_id : 'clip_grid_pager', xml_data_root : '/data', pager_sets : PAGER_DEFAULT}),
        filters   : new PhenoFilter({
            args  : ['sel_tag', 'sel_channel'],
            progress_bar_id : 'pb_clips_grid'}),
        row_callbacks : clips_rows_update,
        map       : map
    });

    var block_change = false;

    $('#sel_tag').change(function(ev) {
        //alert('TAG: ' + block_change);
        if(block_change == false) {
            block_change = true;
            $('#sel_channel').val('');
            $('#sel_channel').change();
            clips_grid.filters.fetchVals();
            clips_grid.pager.currentPage = 0;
            clips_grid.get();
            block_change = false;
        }
        //return false;
    });

    $('#sel_channel').change(function(ev) {
        //alert('CHANNEL: ' + block_change);
        if(block_change == false) {
            block_change = true;
            $('#sel_tag').val('');
            $('#sel_tag').change();
            clips_grid.filters.fetchVals();
            clips_grid.pager.currentPage = 0;
            clips_grid.get();
            block_change = false;
        }
        //return false;
    });
function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}
var h = getClientHeight() -75;
    $('#gmap').css('height', h);
    $('#geo_tab').css('height', h);


//    $('#gmap').css('height', window.innerHeight-10-75);
//    $('#geo_tab').css('height', window.innerHeight-10-75);

    clips_grid.get();
    //alert(window.outerHeight);
});


