﻿/*
File:		viewingoptions.js
Created:	24.08.2010
Author:		[hardin] via http: //www.shopdev.co.uk/blog/font-resize.html#

Notes:
Here's the links that would drive font resizing by an end user: 
<a href="#" class="increaseFont">Increase</a>
<br /><a href="#" class="decreaseFont">Decrease</a>
<br /><a href="#" class="resetFont">Reset</a>
*/
$ektron(document).ready(function() {

    // [hardin] Assign the correct css class based on the end characters in the href attribute
    // Doing these first will help reduce header calls performed via displayDownloadIcon()
    // Apply CSS class to all A links that end in .pdf, .doc etc
    $ektron("a[href$='.pdf']").addClass("pdf_download");
    $ektron("a[href$='.doc']").addClass("doc_download");
    $ektron("a[href$='.xls']").addClass("xls_download");
    $ektron("a[href$='.ppt']").addClass("ppt_download");
    $ektron("a[href$='.jpg']").addClass("img_download");
    $ektron("a[href$='.gif']").addClass("img_download");
    $ektron("a[href$='.png']").addClass("img_download");
    $ektron("a[href$='.bmp']").addClass("img_download");

    //Apply CSS class to all A links that start with mailto:
    $ektron("a[href^='mailto:']").addClass("eml_link");

    // Look up head requests for all main page content - excluding the utility top/footer, main menus, breadcrumbs to save unnecessary overheads
    $ektron("div.content_left a").each(function(index) {

        var linkText = $ektron(this).text();
        var css = $ektron(this).attr("class");
        //alert("linkText: " + linkText + ", css: " + css);

        if ((undefined == css) || (-1 == css.indexOf("ExcludeIconLookup"))) {
            var url = $ektron(this).attr('href');
            //alert("linkText: " + linkText + ", css: " + css + ", url: " + url);
            displayDownloadIcon(url, $ektron(this));
        }
    });
    
    // Look up head request for all links in the rhs - excluding the menu links to save unnecessary overheads
    $ektron("div.content_right div.highlight a").each(function(index) {
        var linkText = $ektron(this).text();

        if (0 < linkText.length) { //alert('each a: ' + linkText);
        }

        var url = $ektron(this).attr('href');
        displayDownloadIcon(url, $ektron(this));
    });

    //Apply CSS class to all A links that start with http://
    $ektron("a[href^='http://']")
        .click(function() {
            // Open external links in a new window
            window.open($(this).attr('href'));

            return false;
        })
        .addClass("ext_link");

    //Remove CSS class to all A links that start with http://www.YOURDOMAINHERE.co.uk
    $ektron("a[href^='http://www.iffim.org']").removeClass("ext_link");

    // [hardin] 2011/02/11 Only embellish links with a download size via their css class assignment. Selectors: $ = ends with, * = contains
    $ektron("a[class*='pdf_download']").each(function(index) {
        var url = $ektron(this).attr('href');
        displayDownloadSize(url, $ektron(this));
    });
    $ektron("a[class*='doc_download']").each(function(index) {
        var url = $ektron(this).attr('href');
        displayDownloadSize(url, $ektron(this));
    });
    $ektron("a[class*='xls_download']").each(function(index) {
        var url = $ektron(this).attr('href');
        displayDownloadSize(url, $ektron(this));
    });
    $ektron("a[class*='ppt_download']").each(function(index) {
        var url = $ektron(this).attr('href');
        displayDownloadSize(url, $ektron(this));
    });
});

function displayDownloadIcon(url, linkObject) {
    // If linkObject contains an image don't run
    if (null != linkObject.find("img").html()) return;
    
    // [hardin] TBD: http might be an issue as Ektron is introducign the domain name into the links
    // Http check is done as ajax calls cannot be made to other domains / urls
    if ((undefined != url) && (-1 == url.indexOf('http')) && ('#' != url.toString().charAt(0))) {
        
        // Don't perform a Header call if the css class is already in place
        var cssAlreadyAssigned = linkObject.attr('class');        
        if 
        (
            (cssAlreadyAssigned == undefined)
            ||
            (
                (-1 == cssAlreadyAssigned.indexOf("pdf_download")) 
                && (-1 == cssAlreadyAssigned.indexOf("doc_download"))
                && (-1 == cssAlreadyAssigned.indexOf("xls_download"))
                && (-1 == cssAlreadyAssigned.indexOf("ppt_download"))
                && (-1 == cssAlreadyAssigned.indexOf("img_download"))
                && (-1 == cssAlreadyAssigned.indexOf("ext_link"))
                && (-1 == cssAlreadyAssigned.indexOf("eml_link")) 
            )                           
        ) {
                
            //alert('make the request: ' + url);
            var request = createRequest();
            if (request) {    
                request.open("HEAD", url, true); // light weight, no document returned                      
                request.onreadystatechange = function() {
                    //State  Description
                    //0      The request is not initialized
                    //1      The request has been set up
                    //2      The request has been sent
                    //3      The request is in process
                    //3      Tells you that the server's response has started to come in
                    //But when you're using the XMLHttpRequest object from a web page there's almost nothing(*) you can do with that readyState3 information, 
                    //since you don't have access to the extended properties that allow you to read the partial data
                    //4      The request is complete
                    //readyState 4 is the only one that holds any meaning
                    if (request.readyState == 4) {                        
                        if (request.status == 200) {                        
                            
                            // Assign css classes 
                            var contentType = request.getResponseHeader("Content-Disposition");
                            if (null != contentType)
                            {          
                                //alert('contentType: ' + contentType);                 
                                //alert(contentType.indexOf(".pdf"));
                            
                                if (-1 < contentType.indexOf(".pdf"))
                                {
                                    linkObject.addClass("pdf_download"); 
                                }
                                if (-1 < contentType.indexOf(".doc"))
                                {
                                    linkObject.addClass("doc_download"); 
                                }
                                if (-1 < contentType.indexOf(".xls"))
                                {
                                    linkObject.addClass("xls_download"); 
                                } 
                                if (-1 < contentType.indexOf(".ppt"))
                                {
                                    linkObject.addClass("ppt_download"); 
                                } 
                                if (-1 < contentType.indexOf(".jpg"))
                                {
                                    linkObject.addClass("img_download"); 
                                }
                                if (-1 < contentType.indexOf(".gif"))
                                {
                                    linkObject.addClass("img_download"); 
                                }
                                if (-1 < contentType.indexOf(".png"))
                                {
                                    linkObject.addClass("img_download"); 
                                } 
                                if (-1 < contentType.indexOf(".bmp"))
                                {
                                    linkObject.addClass("img_download"); 
                                }                     
                            }                 

                        } else if (request.status == 404) {
                            //alert("Requested URL is not found: " + url);
                        } else if (request.status == 403) {
                            //alert("Access denied: " + url);
                        } else {
                            //alert(url + ". Status is " + request.status);
                        }
                    }
                    else {
                        //alert(url + ' not ready: ' + request.readyState);
                    }

                };  //.onreadstate end of function declaration
                try {
                    request.send(null);
                }
                catch (failed) {
                   //alert('do not continue:' + url);
                }
            }   // end of if (request)
        }       // Don't do a get call if the css class is already in place             
    }           //   -1 == url.indexOf("http")
}

function displayDownloadSize(url, linkObject) {
    // for now just return until we have a robust solution
    return;
    
    // If linkObject contains an image don't run
    if (null != linkObject.find("img").html()) return;

    // ajax calls cannot be made to other domains / urls
    if ((undefined != url) && (-1 == url.indexOf('http')) && ('#' != url.toString().charAt(0))) {
        var request = createRequest();
        if (request) { 
            try {      
                request.open("HEAD", url, true); // leight weight not document returned       
                request.onreadystatechange = function() {

                    if (request.readyState == 4) {                    
                        if (request.status == 200) {                       
                     
                            var sizeContentLength = request.getResponseHeader("Content-Length");
                            //if (0 < sizeContentLength.length) 
                            if (sizeContentLength  && 0 < sizeContentLength.length)
                            {
                                var size = Math.round(sizeContentLength / 1024); 

                                var unit = ' KB';
                                if (1024 < size) {
                                    size = size / 1024
                                    unit = ' MB';
                                }
                                var displaySize = ' (' + size + unit + ')';

                                linkObject.text(linkObject.html() + displaySize);
                            }
                            else
                            {
                                 //alert("Content-Length is Zero: ");
                            }

                        } else if (request.status == 404) {
                            //alert("Requested URL is not found: " + url);
                        } else if (request.status == 403) {
                            //alert("Access denied: " + url);
                        } else {
                            //alert(url + ". Status is " + request.status);
                        }
                    }
                    else {
                        //alert(url + ' not ready: ' + request.readyState);
                    }

                };  //.onreadstate end of function declaration
                try {
                    request.send(null);
                }
                catch (failed) {
                   //alert('do not continue:' + url);
                }
			}	
            catch (failed) {
                // Like occurred due to an attempt to call an external URL. Do nothing
            }
        }   // end of if (request)
            
    }   //  -1 == url.indexOf("http")
}

// [hardin] Excellent link on http requests: http://www.yaldex.com/wAjax/AcloserlookatHTTPstatuscodes.html
function createRequest() {
    var varRequest;
    try {
        varRequest = new XMLHttpRequest();
    } 
    catch (trymicrosoft) {
        try {
            alert('in here - trymicrosoft');
            varRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (othermicrosoft) {
            try {
                varRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (failed) {
                //alert('in here - othermicrosoft');
                varRequest = false;
            }
        }
    }

    if (!varRequest) {
        //alert("Error initializing XMLHttpRequest!");
    }
    return varRequest;
}

