// Common.js
// ---------
// 
// For EP UDC (Urban Design Compendium)
// Requires jQuery 1.1.2 or higher
// Initial code, Martin Paton, Developer, Amaze
// 13/08/2007

// Currently only handles popup image functionality with no function signature.

// Var to store interval ID
var intervalId = 0;
var inputButtonRolloverClass = "buttonRollover";


$(document).ready(function(){

    $("#tweetsDiv").getTwitter({
        userName: "hitchinbid",
        numTweets: 4,
        loaderText: "Loading tweets...",
        slideIn: false,
        showHeading: false,
        headingText: "Latest Tweets",
        showProfileLink: false
    });
	/*var currentURL = window.location.href;
	var startPos = currentURL.lastIndexOf("/");
	var endPos = currentURL.lastIndexOf(".");
	var subURL = currentURL.substring(startPos + 1,endPos);
	var urlArr  = currentURL.split("/");
	var currentFolderIndex = urlArr.length - 2;
	var currentFolder = urlArr[currentFolderIndex];
	var currentSection = urlArr[currentFolderIndex];
	
	$("a#" + subURL).addClass("selected");
	$("li:has(a#" + subURL + ":parent)").addClass("selectedChildren");
	//alert("div#menu ul:has(li#"+ currentFolder +"Section:child)");
	$("div#menu ul:has(li#"+ currentFolder +"Section:child)").addClass("selectedSection");
	
	switch(currentSection){
		case: "overview"
			$("div#menu li#overviewSection").html("<a class=\"selectedSection\" href=\"/overview/index.php\">Overview</a>");
			break;
		case: "proposals"
			$("div#menu li#proposalsSection").html("<a class=\"selectedSection\" href=\"/proposals/index.php\">Proposals</a>");
			break;
		case: "details"
			$("div#menu li#detailsSection").html("<a class=\"selectedSection\" href=\"/details/index.php\">Details</a>");
			break;
		case: "about_us"
			$("div#menu li#about_usSection").html("<a class=\"selectedSection\" href=\"/about_us/index.php\">About Us</a>");
			break;
		case: "documents"
			$("div#menu li#documentsSection").html("<a class=\"selectedSection\" href=\"/documents/index.php\">Overview</a>");
			break;
		case: "news_events"
			$("div#menu li#news_eventsSection").html("<a class=\"selectedSection\" href=\"/news_events/index.php\">Latest</a>");
			break;
		case: "contact"
			$("div#menu li#contactSection").html("<a class=\"selectedSection\" href=\"/contact/index.php\">Contact</a>");
			break;
		default
	}*/
	
	/*//if(crumbCurrentFolder.indexOf("hitchinbid") == -1){
	$("div#breadcrumb").html("
	<dl>
		<dt>You are here: </dt>
			<dd>
            	<a href=\"../home.php\">Home</a>
           	</dd>
  			<dd><a href=\"/index\">" + crumbCurrentFolder + "</a></dd>
			<dd>" + crumbSubURL + "</dd>
	</dl>
	");*/
	
	
    //New Method to render tooltips for social networking bookmarks
    //prepareTooltips();
    addTableColours();
    addFontSizeCss();
    

    $("a.helper").focus(function() {
        $(this).addClass("focus");    
    });

    $("a.helper").blur(function() {
        $(this).removeClass("focus");    
    });
    
    try {
        document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {}
    
    $("#Submit").hover(function(){
        $(this).addClass(inputButtonRolloverClass);
    },function(){
    
        $(this).removeClass(inputButtonRolloverClass);
    });
    
    $("#btnSubmit").hover(function(){
        $(this).addClass(inputButtonRolloverClass);
    },function(){
    
        $(this).removeClass(inputButtonRolloverClass);
    });
    
    $("input.searchbutton").hover(function(){
   
        $(this).addClass(inputButtonRolloverClass);
    },function(){
    
        $(this).removeClass(inputButtonRolloverClass);
    });
    
    $("#printcasestudy").html("<a href='#' onclick='javascript:window.print();return false;'>Print Case Study</a>");

    $("a", "#linkstable").click(function() {
    
        if ($(this).attr("href") == "#skipnav") return true;
        return popURL($(this).attr("href"), 'LINK');
    });
    
    $("a", "li.externallink").click(function() {
        return popURL($(this).attr("href"), 'LINK');
    });   
    
    
    // Inject link and magnifying glass
    var enlarge = "<span class=\"enlarge\"><a class=\"thickbox\" href=\"%1s\">Click to enlarge <img src=\"/img/mglass.gif\" border=\"0\"/></a></span>";    
    $("a.thickbox", "div.imageright").each(function(i) {    
        var href = $(this).attr("href");
        $(this).after($.sprintf(enlarge, href));
    });
    
    $("a.thickbox", "div.imageleft").each(function(i) {    
        var href = $(this).attr("href");
        $(this).after($.sprintf(enlarge, href));
    });

    /*$('#voteWinDiv').click(function(){
        window.location.href = $(this).attr('rel');
    });*/
    
    //Set max and Min size
    var max_level = '20';
    var min_level = '13';
      
    // Initiate Google check
    //intervalId = setInterval("googleCheck()", 500);
    
 });
 
 
 /*Table Colours*/
 function addTableColours()
 {
 //alert("hl-rows");
    $("table.hl-rows tr:nth-child(even)").addClass("h-light");
 }
 

/*----------------------------
*
*Tootltip Functionality
*
----------------------------*/

/*function prepareTooltips()
{

//alert("TTip");
   
    $("ul#socialbookmarks li a.tipme").tooltip({
     
    bodyHandler: function() { 
        return $(this).html(); 
    }, 
    showURL: false 
});

}*/

 // Code to check that Google scripts are available
/*function googleCheck()
{
    if (urchinTracker)
    {       
        clearInterval(intervalId);
        
        // ---------------------------------------------------------
        // Google Analytics - track downloads & search
        $("a").click(function() {
                //urchinTracker ('/downloads/map');
                var url = $(this).attr("href");
                categoriseType(url);
        });       
        
        $("#searchsite").click(function() {    
                callTracker('/internal search/' + $("#searchterm").attr("value"));
        });   
        
        $("#gobody").click(function() {
                callTracker('/internal search/' + $("#searchtermbody").attr("value"));
        }); 
        // ---------------------------------------------------------        
    }
}*/

 
 
 /*// Actually instigate tracking call
function callTracker(pageview) 
{
       //alert("lll");
       urchinTracker(pageview);
}*/
   
  function categoriseType(s) {

    var c = '';
    if (s.indexOf('http://') > -1) {
        c = '/url clicked/';
    } else if (s.indexOf('public/documents/') > -1) {
        c = '/document viewed/';
    }
    
    if (c != '') {
        //$("#searchterm").val(c + adjustPath(s));
        callTracker(c + adjustPath(s));
    }
}

 function adjustPath(s) {
    
    if (s.indexOf('public/documents/') > -1) {
        s = s.replace('public/documents/','');
    }
    return s;
}

 function popURL (href, type) {      
    var url = href;      
    var w = window.open(url, type ,'');     
    w.focus();
           
    return false;
}

 function resize() {
 
     if (navigator.appVersion.match(/MSIE [0-6]\./)) {
        var currentSize = document.body.clientWidth;
                
        if (currentSize <= 830) 
        {            
            $("#sitecontainer").css("width", "700px");
        } else if ((currentSize > 830) && (currentSize <= 950)) {
            $("#sitecontainer").css("width", "85%");
        } else if (currentSize > 950) {
            $("#sitecontainer").css("width", "72%");
        }               
    }
 }
 
//addEvent(window, "load", resize);
//addEvent(window, "resize", resize);  

function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}

// ------------------------------------------------------------------------------
//
// Validation Functionality.
//
// ------------------------------------------------------------------------------

 function checkTitle(source, args)
 {
    // Check that something is selected other than the "Please select" bit
    args.IsValid = ($("#TitlePrefix").children("[@selected]").val() != "");
 }
 
  function checkSector(source, args)
 {
    // Check that something is selected other than the "Please select" bit
    // If other, check other box
    var val = $("#RequestorSector").children("[@selected]").val();    
    if (val == "") 
    {
        args.IsValid = false;
    }
    else if (val == "xx") 
    {
        args.IsValid = ($("#OtherSector").val() != "");
    }   
    else 
    {
        args.IsValid = true;
    }   
 }
 
function checkUDCOption(source, args)
{
    args.IsValid = (($("#UDC1").attr("checked")) || ($("#UDC2").attr("checked")));    
}

function checkProtectionOption(source, args)
{
    args.IsValid = (($("#NoRetain").attr("checked")) || ($("#RetainDetails").attr("checked")) || ($("#RetainUpdate").attr("checked")));    
}

function checkPhone(source, args)
{
    var tel = $("#ContactTelephone").val();
   // var fax = $("#ContactFax").val();
  
      args.IsValid = (checkNumber(tel));  
      
    /*if ((tel == "") && (fax == "")) {
        args.IsValid = false;
    } else if (checkNumber(tel)) {
        args.IsValid = true;
    } else {
        if (tel == "") {
            args.IsValid = true;
        } else {
            args.IsValid = false;
        }
    }  */      
}

function checkFax(source, args)
{
    var tel = $("#ContactTelephone").val();
    var fax = $("#ContactFax").val();
    var pattern = /\d{1}[\d|\s]*/;    
    
    if ((tel == "") && (fax == "")) {
        args.IsValid = false;
    } else if (checkNumber(fax)) {
        args.IsValid = true;
    } else {
        if (fax == "") {
            args.IsValid = true;
        } else {
            args.IsValid = false;
        }
    }        
}

function checkNumber(s) {
      var pattern = /\d{1}[\d|\s]*/;    
      return (s.search(pattern) > -1);
}      

 function doClear(theText) 
{
     if (theText.value == theText.defaultValue)
 {
         theText.value = ""
     }
 }
 
//Create Cookie persist for a year
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
	
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    
    return null;
}

//Increase the font by percentage
function increaseFont(){
	
   var size = readCookie("style");
   switch (size) {
      case 'A--' :
         switchStylestyle('A-');
         break;
      case 'A-' :
         switchStylestyle('A');
         break;
      case 'A' :
         switchStylestyle('A+');
         break;
      case 'A+' :
         switchStylestyle('A++');
         break;
      case 'A++' :
         break;
      default :
         switchStylestyle('A');
         break;
   }
}

function decreaseFont(){
	
	   var size = readCookie("style");
   switch (size) {
      case 'A++' :
         switchStylestyle('A+');
         break;
      case 'A+' :
         switchStylestyle('A');
         break;
      case 'A' :
         switchStylestyle('A-');
         break;
      case 'A-' :
         switchStylestyle('A--');
         break;
      case 'A--' :
         break;
      default :
         switchStylestyle('A--');
         break;
   }
}

function switchStylestyle(styleName)
{
   $('link[@rel*=style][@title]').each(function(i)
   {
          this.disabled = true;
          if (this.getAttribute('title') == styleName) {
            this.disabled = false;        
            }
   });   
   createCookie('style', styleName, 365);
}

function addFontSizeCss()
{
   var size = readCookie("style");
   var title = size ? size : "A";
   switchStylestyle(title);
}

function showImg(divId)
	{
		document.getElementById(divId).style.visibility="visible";

	}
function hideImg(divId)
	{
		document.getElementById(divId).style.visibility="hidden";
	
	}


