﻿///<reference path="../framework/current/scripts/debug.js"/>
///<reference path="../framework/current/scripts/filter.js"/>
///<reference path="../framework/current/scripts/xsl_loader.js"/>

//ELI set framework's debug info.
framework.debug = new DEBUG({
    key_hook: true,
    add_categories: function() {
        return {
            'Calendar': calendar.debug.elapsed,
            'List': list.debug.elapsed,
            'Filter': filter.debug.elapsed
        };
    }
});

////////////////////////////////////////////////////////
// CALENDAR
////////////////////////////////////////////////////////
var args = {
    id: 'div_calendar',
    xsl_url: 'xsl/production_calendar.xsl',
    string_params: function (){ return {
        'js_month': calendar.date.getMonth() + 1,
        'js_year': calendar.date.getFullYear(),
        'js_offset': calendar.offset(),
        'js_cid': get_cid(),
        'js_venue': calendar.args.string_params_array['js_venue'],
        'js_event': calendar.args.string_params_array['js_event'],
        'js_city': calendar.args.string_params_array['js_city'],            
        'js_search_type':get_search_type()
        }
    },
    string_params_array : {
        'js_venue': 'all',
        'js_event': 'all',
        'js_city': 'all' 
    },
    debug: new DEBUG()
};

var calendar = new XSL_LOADER(args);
calendar.date = new Date();
calendar.offset = function() { 
    var d = new Date(); 
    d.setFullYear(calendar.date.getFullYear(), calendar.date.getMonth(), 1); 
    return d.getDay() + 1; 
};

calendar.nextMonth = function() 
{ 
    calendar.date.setMonth(calendar.date.getMonth() + 1); 
    calendar.date.adjust_to_range();
    calendar.apply(); 
};

calendar.prevMonth = function() { 
    calendar.date.setMonth(calendar.date.getMonth() - 1); 
    calendar.date.adjust_to_range();
    calendar.apply(); 
};

calendar.parse_date = function (d_str){
    bound = d_str.indexOf('T');
    d_date = d_str.slice(0, bound).split('-');
    d_time = d_str.slice(bound+1, -1).split(':');
    return new Date(Date.UTC(d_date[0],d_date[1]-1,d_date[2],d_time[0],d_time[1],d_time[2]));
};

calendar.args.complete = function(stats)
{
/// <summary>this function is called once when the XML is loaded and apply() is called.</summary>    
    if(!stats){return;}
    calendar.results = parseFloat(stats.num_of_rows);
    if (calendar.results > 0){

       tabs.toggle('calendar',true);
       var id = cookies.get('current_tab');
       if(id=='calendar')
       {
        tabs.select(id);
       }
       $('div_tabs').style.display = "";
    }
    calendar.date.first_month =calendar.parse_date (stats.first_month);
    calendar.date.last_month = calendar.parse_date (stats.last_month);

    if(!calendar.date.adjusted){
        calendar.date.adjust_to_range();
        calendar.date.adjusted = true;
        calendar.apply();
    }
};

calendar.date.adjust_to_range= function()
{
/// <return>integer - the month in range</return> 
    var date = this;
    if(date.getMonth()>date.last_month.getMonth() || (date.getFullYear()>date.last_month.getFullYear())){
        if((date.getFullYear()>=date.last_month.getFullYear()) ){
            date.setMonth(date.last_month.getMonth());
            date.setFullYear(date.last_month.getFullYear());
            return;
        }
    }
     

    if(date.getMonth() < date.first_month.getMonth() || (date.getFullYear()<date.first_month.getFullYear())){
        if(date.getFullYear()<=date.first_month.getFullYear())
        {
            date.setMonth(date.first_month.getMonth());
            date.setFullYear(date.first_month.getFullYear());
            return;
        }
    } 
};


////////////////////////////////////////////////////////
// LIST
////////////////////////////////////////////////////////
var list = new FILTER({
    id: 'div_list',               //ELI id of the DIV that will contain the ticket list.
    xsl_url: 'xsl/production_list.xsl',  //ELI link to the table template XSL.
    filter_options: {},
    sort_options: {
        'default': { id: 'date', field: 'EventDate', order: 'ascending', type: 'text' },
        'date': { field: 'EventDate', order: 'ascending', type: 'text' }
    },
    string_params: {
        'js_venue': 'all',
        'js_event': 'all',
        'js_city': 'all',
        'js_search_type':get_search_type(),
        'js_cid':get_cid()
    },
    wait_for_zoomer:false,
    debug: new DEBUG()
});


////////////////////////////////////////////////////////
// FILTER
////////////////////////////////////////////////////////
var filter = new XSL_LOADER({
    id: 'div_filter',               //ELI id of the DIV that will contain the ticket list.
    xsl_url: 'xsl/production_filter.xsl',  //ELI link to the table template XSL.
    string_params: {
        'js_search_type':get_search_type()
    },
    debug: new DEBUG()
});

filter.city_change = function(value){
    $('venue_filter').value='all';
    list.args.string_params['js_city']=value;
    list.args.string_params['js_venue']='all';
    list.args.string_params['js_event']='all';
    list.apply({'force':true});

    calendar.date.adjusted=false;
    calendar.args.string_params_array['js_city']=value;
    calendar.args.string_params_array['js_venue']='all';
    calendar.args.string_params_array['js_event']='all';
    calendar.apply({'force':true});
}

filter.venue_change = function(value){
    $('city_filter').value='all';
    list.args.string_params['js_city']='all';
    list.args.string_params['js_venue']=value;
    list.args.string_params['js_event']='all';
    list.apply({'force':true});
    
    calendar.date.adjusted=false;
    calendar.args.string_params_array['js_city']='all';
    calendar.args.string_params_array['js_venue']=value;
    calendar.args.string_params_array['js_event']='all';
    calendar.apply({'force':true});    
}

filter.event_change = function(value){
    list.args.string_params['js_city']='all';
    list.args.string_params['js_venue']='all';
    list.args.string_params['js_event']=value;
    list.apply({'force':true});
    
    calendar.date.adjusted=false;
    calendar.args.string_params_array['js_city']='all';
    calendar.args.string_params_array['js_venue']='all';
    calendar.args.string_params_array['js_event']=value;
    calendar.apply({'force':true});
}

//ELI load xml to all fo the objects.
list.load_xml(get_xml());
filter.load_xml(get_xml());  
calendar.load_xml(get_xml());

//ELI reloads the XSL and XML into object again, and applies filter.
function reload(){
    $('div_calendar').innerHTML='';
    $('div_list').innerHTML='';
    $('div_filter').innerHTML='';
   
    list.download();
    list.load_xml(get_xml());
    list.apply({'force':true});
    
    filter.download();
    filter.load_xml(get_xml());
    filter.apply({'force':true});

    calendar.download();
    calendar.load_xml(get_xml());
    calendar.apply({'force':true});
}

////////////////////////////////////////////////////////
// TABS
////////////////////////////////////////////////////////
var tabs = {};
tabs.current = null;
tabs.toggle = function(id,show)
{
    if(show){
        $('tab_'+id).style.display = "";
    }else{
       $('tab_'+id).style.display = "none";
    }
};

tabs.clear = function()
{
    $('tab_list').removeClassName('SelectedTab');
    $('tab_calendar').removeClassName('SelectedTab');
    $('tab_list').addClassName('DefaultTab');
    $('tab_calendar').addClassName('DefaultTab');
    $('div_list').style.display = "none";
    $('div_calendar').style.display = "none";
    //$('div_grids').style.display = "none";
};

tabs.select = function(id)
{
    //return;
    if (tabs.current == id) { return; }
    tabs.current = id;
    cookies.put("current_tab",id);
    tabs.clear();

    //ELI toggle selected tab
    $('tab_' + id).removeClassName('DefaultTab');
    $('tab_' + id).addClassName('SelectedTab');

    //ELI toggle content visibility
    $('div_' + id).style.display = "";
    
    //ELI hide div_list and show div_grids instead
    if(id=="list")
    {
        //$('div_list').style.display = "none";
        //$('div_grids').style.display = "";        
    }
}

////////////////////////////////////////////////////////
// GENERAL
////////////////////////////////////////////////////////


$j(function() {
    $j("#TextBox1").autocomplete({
	    url: "suggestions.aspx"

		//formatResult: formatResult
    });
});

function suggest(inputString)
{
    if(inputString.length == 0) {
        $('#suggestions').fadeOut(); // Hide the suggestions box
    } else {
        $.post("suggestions.aspx", {queryString: ""+inputString+""}, function(data) { // Do an AJAX call
            $('#suggestions').fadeIn(); // Show the suggestions box
            $('#suggestions').html(data); // Fill the suggestions box
        });
    }
}


var cookies = new CookieJar();

function textbox1_onfocus() 
{
    //document.form1.TextBox1.style.color='#000000';
    if (document.form1.TextBox1.value == "Enter ZipCode, Venue or Event") { document.form1.TextBox1.value = ""; }
};

function search(txt, show, click_sugest, suggest_number, has_shows) {//,title){
    if (has_shows == false) {
        hide_loading_message();
        //BOGDAN using wz_tooltip.js from now on.
        //show_tooltip();
        return;
    }
    if (txt != '') {
        var form = document.getElementById('form1');
        form.clicked_suggest.value = click_sugest;
        form.suggest_number.value = suggest_number;
        form.suggest_result.value = txt;
        form.previous_search.value = document.form1.TextBox1.value;
    }
    submit_form(true);
};



function submit_form(suggest) {
    var form = document.getElementById('form1');
    if (!suggest) {
        form.clicked_suggest.value = '';
        form.suggest_number.value = '';
        form.suggest_result.value = '';
    }
    //alert("Action: " + form.action  );
    //jar.remove('curdate');
    form.submit();
    return false; //IMPORTNAT! must return false otherwise IE will submit the page twice.
}


////ELI make sure to capture the last event
//var last_event;
//function ab(e) { last_event = e; }
//Event.observe(document, 'click', ab);


var hTimer= setInterval('set_focus()',500);
function set_focus()
{
    var t = document.getElementById('TextBox1');
    if(t!=null && t.value=="Enter ZipCode, Venue or Event"){t.focus();clearInterval(hTimer);}
}

function showmap(venue,venue_version){
    var space=15;
    var sw = window_width()-space;
    var sh = window_height()-space;
//TODO do some voodo
//window.location.href = 'Zoomer/show_map.aspx?vid=' + venue + '&eid=' + venue_version + '&status=zoom&height=' +  (ih/ratio) + 'width=' + (iw/ratio);
window.location.href = 'all/show_map.aspx?vid=' + venue + '&eid=' + venue_version + '&height=' + sh + '&width=' +sw;
}

function window_width(){
  var ww = 0;
  d = document;
   if ( typeof window.innerWidth != 'undefined' )
     ww = window.innerWidth;  // NN and Opera version
   else
   {
     if ( d.documentElement
       && typeof d.documentElement.clientWidth!='undefined'
       && d.documentElement.clientWidth != 0 )
       ww = d.documentElement.clientWidth;
     else
       if ( d.body
         && typeof d.body.clientWidth != 'undefined' )
         ww = d.body.clientWidth;
     //else alert ("Can't identify window width - please tell me which browser you are using.")
   }
   return ww;
}

function window_height(){
  var ww = 0;
  d = document;
   if ( typeof window.innerHeight != 'undefined' )
     ww = window.innerHeight;  // NN and Opera version
   else
   {
     if ( d.documentElement
       && typeof d.documentElement.clientHeight!='undefined'
       && d.documentElement.clientHeight != 0 )
       ww = d.documentElement.clientHeight;
     else
       if ( d.body
         && typeof d.body.clientHeight != 'undefined' )
         ww = d.body.clientHeight;
     //else alert ("Can't identify window width - please tell me which browser you are using.")
   }
   return ww;
}

window.onunload=function(){if(top.show_loading_message){top.show_loading_message();}}
window.onbeforeunload=function(){if(top.show_loading_message){top.show_loading_message();}}

////BOGDAN script for changing link to zoomer_api
//function ctrlPressAndLinkClick(event)
//{   
//    //alert(event.ctrlKey)
//    var element = event.element();
//    if(element.innerHTML && element.innerHTML.indexOf("Map Tickets")!=-1)
//    {
//        href = element.getAttribute('href');
//        if(event.ctrlKey)
//        {
//            href = href.replace('Zoomer', 'zoomer_api');
//        } else if(event.shiftKey){
//            href.replace('&tn_only=true', '');
//            href = href + '&tn_only=true';
//        } else {
//            href = href.replace('zoomer_api', 'Zoomer');
//        }   
//        element.setAttribute('href', href);
//    }
//}

//window.dhtmlHistory.create({
//        toJSON: function(o) {
//                return Object.toJSON(o);
//        }
//        , fromJSON: function(s) {
//                return s.evalJSON();
//        }
//});

//var handleHistoryChange = function(newLocation, historyData) 
//{
//	//do something;
//    alert(newLocation);  
//};

//window.onload = function() 
//{
//	dhtmlHistory.initialize();

//	dhtmlHistory.addListener(handleHistoryChange);
//	
//	if(!dhtmlHistory.getCurrentLocation()){dhtmlHistory.add("start",null);}
//	

//};

