/************************/
/* Globals              */
/************************/

//...

/************************/
/* FP Planner           */
/************************/

jQuery(document).ready(function()
{
    jQuery('#planner_fp_search_from').focus(function()
    {
        if(jQuery('#planner_fp_search_from').val() == 'Var åker du ifrån?')
        {
           jQuery('#planner_fp_search_from').val('');
           jQuery('#planner_fp_search_from').css('color', '#555'); 
        }
    });    

    jQuery('#planner_fp_search_to').focus(function()
    {
        if(jQuery('#planner_fp_search_to').val() == 'Vart skall du åka?')
        {
           jQuery('#planner_fp_search_to').val('');
           jQuery('#planner_fp_search_to').css('color', '#555'); 
        }
    });    

    jQuery('#planner_fp_do_search').click(function()
    {
        var l_from = "";
        var l_to = "";
        if(jQuery('#planner_fp_search_from').val() != 'Var åker du ifrån?')
        {
            l_from = jQuery('#planner_fp_search_from').val();
        }
        if(jQuery('#planner_fp_search_to').val() != 'Vart skall du åka?')
        {
            l_to = jQuery('#planner_fp_search_to').val();
        }
        
        //todo: kan ju kolla att man har fyllt i "till" annars klaga
        window.location = "http://www.turistmal.se/i-reseplaneraren.html#search|" + l_from + "|" + l_to;  
        
        //
    });    
    
});

/************************/
/* Item - Show image    */
/************************/

jQuery(document).ready(function()
{     
    //fetch parameter data
    var l_index = urlParams["index"];
    var l_view = urlParams["view"];
    
    //item - handle form    
    if(
       (l_index == 'item3' && l_view == '4') ||
       (l_index == 'item3' && l_view == '5') ||
       (l_index == 'item') ||
       (l_index == 'item_con') ||
       (document.URL.indexOf('rekommendationer.html') != -1)
      )
    {
        var l_ctrl = document.getElementById('lamtsirut');
        if(l_ctrl)
        {
            l_ctrl.value = 27;
        }
    }
    
    //item - handle image
    if(
        (l_index == 'item3' && l_view == '2') ||
        (l_index == 'item_pics')
      )
    {
        //get current image index
        var l_idx = window.location.hash;
        if(!l_idx) { l_idx = 0 ;}

        if(g_img_items_cnt > 0)
        {
            //load all thumbnails
            for(var i_idx = 0; i_idx < g_img_items_cnt; i_idx++)
            {
                var i_class = '';
                if (i_idx == 0) { i_class = ' selected'; }
                jQuery("#img_tn_holder").append('<img id="tn_' + i_idx + '" class="tn_img' + i_class + '" src="/upfile/image.php?src=' + g_img_items[i_idx] + '&amp;width=78&amp;height=60" style="display: none;" />');    
            }
            
            //load first image
            jQuery('#img_big').attr('src', '/upfile/image.php?src=' + g_img_items[0] + '&width=500');
            jQuery('#img_label').html('' + g_img_desc[0]);
                        
            //load big image when clicked
            jQuery('.tn_img').click(function()
            {
                //toggle slected item
                jQuery(this).toggleClass('selected');
                jQuery('#tn_' + g_img_current_item).toggleClass('selected');
                
                //set new current item
                var l_curr_id = "" + jQuery(this).attr('id');
                var l_id_arr = l_curr_id.split('_', 2);
                g_img_current_item = l_id_arr[1];

                //set image and desc
                jQuery('#img_big').attr('src', '/upfile/image.php?src=' + g_img_items[l_id_arr[1]] + '&width=500');
                jQuery('#img_label').html('' + g_img_desc[l_id_arr[1]]);
                
            });
            
            //show images when fully loaded
            jQuery(window).load(function ()
            {
                for(var i_idx = 0; i_idx < g_img_items_cnt; i_idx++)
                {
                    jQuery('#tn_' + i_idx).fadeIn(200);
                }            
            });

            //prev
            jQuery('#img_prev').click(function()
            {
                //get next item, wrap if needed
                var l_next_item = g_img_current_item - 1
                if(g_img_current_item == 0)
                {
                    l_next_item = g_img_items_cnt - 1;   
                }
                
                //toggle slected item
                jQuery('#tn_' + l_next_item).toggleClass('selected');
                jQuery('#tn_' + g_img_current_item).toggleClass('selected');
                
                //set new current item
                g_img_current_item = l_next_item;

                //set image and desc
                jQuery('#img_big').attr('src', '/upfile/image.php?src=' + g_img_items[g_img_current_item] + '&width=500');
                jQuery('#img_label').html('' + g_img_desc[g_img_current_item]);
            });

            //next
            jQuery('#img_next').click(function()
            {
                //get next item, wrap if needed
                var l_next_item = parseInt(g_img_current_item) + 1
                if(g_img_current_item == (g_img_items_cnt - 1))
                {
                    l_next_item = 0;   
                }
                
                //toggle slected item
                jQuery('#tn_' + l_next_item).toggleClass('selected');
                jQuery('#tn_' + g_img_current_item).toggleClass('selected');
                
                //set new current item
                g_img_current_item = l_next_item;

                //set image and desc
                jQuery('#img_big').attr('src', '/upfile/image.php?src=' + g_img_items[g_img_current_item] + '&width=500');
                jQuery('#img_label').html('' + g_img_desc[g_img_current_item]);
            });            
        }
    }
})


/************************/
/* General - Events     */
/************************/

jQuery(document).ready(function()
{  
    //open external links i new window
    jQuery("a[rel*=external]").click(function()
    {
        this.target = "_blank";           
    });
});


/************************/
/* General - Helpers    */
/************************/

/** Get a parameter from query string
*** ?mode=X ==> urlParams["mode"] = x
*/
var urlParams = {};
(function() {
    var e,
    a = /\+/g,  // Regex for replacing addition symbol with a space
    r = /([^&=]+)=?([^&]*)/g,
    d = function(s) { return decodeURIComponent(s.replace(a, " ")); },
    q = window.location.search.substring(1);
    while (e = r.exec(q))
    urlParams[d(e[1])] = d(e[2]);
})();

//save item to own list
function do_save_item(p_item_id, p_caller_element)
{
    jQuery.ajax(
    {
        type: "GET",
        url: "/dynamic/set.item_savetolist.php",
        data: "id=" + p_item_id,
        cache: false,
        //complete: function() { alert("complete"); },
        success: function(l_data)
        {           
            //increase menu counter
            jQuery('#saved_items_cnt').text(parseInt(jQuery('#saved_items_cnt').text()) + 1);
            
            //disable save-link
            jQuery('#href_save_item').text('Annonsen sparad');
            jQuery('#href_save_item').attr('onclick','');
            
            //do planner stuff
            jQuery('#planner_saved_items_cnt').text(parseInt(jQuery('#planner_saved_items_cnt').text()) + 1);
            
            //add to.. g_saved_items (uniquely!)
            if(g_saved_items.indexOf(p_item_id) == -1)
            {
                g_saved_items.push(p_item_id);
            }
            
            //effect!
            //jQuery("planner_tab_saved_items").effect("highlight", {}, 3000);
            //todo highlight using animate instead
        }
    });    
}

//remove item from own list
function do_remove_item(p_item_id, p_caller_element)
{
    jQuery.ajax(
    {
        type: "GET",
        url: "/dynamic/set.item_removefromlist.php",
        data: "id=" + p_item_id,
        cache: false,
        //complete: function() { alert("complete"); },
        success: function(l_data)
        {           
            //increase menu counter
            jQuery('#saved_items_cnt').text(parseInt(jQuery('#saved_items_cnt').text()) - 1);
            
            //disable save-link
            jQuery('#href_save_item').text('Annonsen borttagen');
            jQuery('#href_save_item').attr('onclick','');
            
            //do planner stuff
            jQuery('#planner_saved_items_cnt').text(parseInt(jQuery('#planner_saved_items_cnt').text()) - 1);
            
            //remove from g_saved_items if exists
            var l_idx = g_saved_items.indexOf(p_item_id);
            if(l_idx != -1)
            {
                g_saved_items.splice(l_idx, 1);
            }            
            
            //reload saved items tab if tab is open
            var l_item = jQuery('#planner_saved_items_canvas:visible');
            if(l_item[0])
            {
                jQuery('#planner_tab_saved_items').click();
            }
        }
    });    
}

//logga item event
function do_visit_item(p_id, p_event_type)
{
    jQuery.ajax(
    {
        async: false,
        type: "POST",
        url: "/services/log.item_event.php", //dynamic url to logging action
        data: "id=" + p_id + "&type=" + p_event_type,
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        cache: false
    });    
    return true; 
}

function do_search_searchbox(p_event)
{
    //did you say "enter"?
    if ((p_event.which && p_event.which == 13) || (p_event.keyCode && p_event.keyCode == 13))
    {
              
        //create the index-param                
        if(document.forms[0].index == null)
        {
            currentElement = document.createElement("input");
            currentElement.setAttribute("type", "hidden");
            currentElement.setAttribute("name", "index");
            document.forms[0].appendChild(currentElement);
        }      
        document.forms[0].index.value = 'list';
        
                
        //create the q-param
        if(document.forms[0].q == null)
        {
            currentElement = document.createElement("input");
            currentElement.setAttribute("type", "hidden");
            currentElement.setAttribute("name", "q");
            currentElement.id = "q";
            currentElement.name = "q";
            document.forms[0].appendChild(currentElement);
        }      
        document.forms[0].q.value = document.forms[0].asearchbox.value;      


        //reset other parameters
        if(document.forms[0].cat_id != null)        
        {
            document.forms[0].cat_id.value = "";        
        }
        if(document.forms[0].county_id != null)        
        {
            document.forms[0].county_id.value = "";        
        }
        if(document.forms[0].city_id != null)        
        {
            document.forms[0].city_id.value = "";        
        }
        
        document.forms[0].method = "GET";
        
        //send the query            
        document.forms[0].submit();
        return false;
    }
    else
    {
        return true;
    }  
}

//obsolete?
function clickclear(thisfield, defaulttext)
{
  if (thisfield.value == defaulttext)
  {
    thisfield.value = "";
    thisfield.style.color = "#333333";
  }
}

function clickrecall(thisfield, defaulttext)
{
  if (thisfield.value == "")
  {
    thisfield.value = defaulttext;
    thisfield.style.color = "#cccccc";
  }
}

function callURL()
{
    var xmlHttp2;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp2 = new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp2 = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp2 = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                return false;
            }
        }
    }
    return xmlHttp2;
}

function save_album_desc(p_id, p_desc)
{
    xmlHttp2 = callURL();
    if(xmlHttp2)
    {
        var url="/dynamic/set.album_desc.php";
        url=url+"?id=" + p_id;
        url=url+"&desc=" + encodeURI(p_desc);
        url=url+"&sid=" + Math.random();
        xmlHttp2.onreadystatechange = function() { }
        xmlHttp2.open("GET", url, true);
        xmlHttp2.send(null);
    }
}
