//Bespoke js 

function loadBtnImages()
{
    var numElements=document.getElementsByTagName('img').length;
    var eIndex, fElement;
    var img=new Object();
    //Enumerate elements and check required elements are filled in and display message if not
    for(eIndex=0; eIndex < numElements ; eIndex++)
    {
        fElement=document.getElementsByTagName('img')[eIndex];
        if(fElement.id.substring(0,3)=='btn')
        {
            img["img"+eIndex]=new Image();
            img["img"+eIndex].src=fElement.src.replace(/\.png/,"Over.png");
        }
    }
}

function randomPicture(filter,page,search)
{  //the id and type is passed for the comments to be displayed via Ajax
    var t2 = Math.random(); //Fixes an IE caching issue
    new Ajax.Updater('slideshow', '_picture_slideshow.ajax.php', { method: 'get', parameters: { f: filter, p: page, search: search, s: t2 } });
    setTimeout('randomPicture('+filter+','+page+',"'+search+'")',3000);
    return true;
    
}

//Below are the functions that can be called from the flash
function ajaxCommentSubmit(button, idField)
{
    //Change the submit button to send via Ajax and call the correct JS function.
    //Used on pages getting comment via Ajax.  e.g. ms_sdrr.php
    var validatorResult;
    validatorResult=formValidator(button.form);
    
    if(validatorResult)
    {  //Submit the form data

     var url = '_comments.inc.ajax.php';
     var pars = 'iF_comment='+escape($('iF_comment').value);
     pars = pars + '&iF_rating='+escape($('iF_rating').value);
     pars = pars + '&iF_'+idField+'='+escape($('iF_'+idField).value);
     pars = pars + '&iF_userid='+escape($('iF_userid').value);
     pars = pars + '&type='+escape($('type').value);
     pars = pars + '&t='+escape($('t').value);
     pars = pars + "&iFbtn=Save";
     pars = pars + "";
     var target = 'comments';
     var myAjax = new Ajax.Updater(target, url, {method: 'post', postBody:  pars });
    }
   
    return false;  //Go nowhere!
}
    
function showComments(itemId, itemType)
{  //the id and type is passed for the comments to be displayed via Ajax
    var t2 = Math.random(); //Fixes an IE caching issue
    $('comments').innerHTML= "<div  style='position: absolute; margin-left: 30px; z-index: 99; background: white;'><img src='cms/images/indicator.gif' alt='loading' /> Loading...</div>"+$('comments').innerHTML;
    new Ajax.Updater('comments', '_comments.inc.ajax.php', 
        { method: 'get', 
        parameters: { t: itemId, type: itemType, s: t2 }
        });
    return false;
}


function hideComments()
{  //the SDRR flash uses this to hide comments when the tip is closed
    $('comments').innerHTML= "";
    return false;
}

    
function ratingUpdate(rate, itemId, itemType)
{
    //Function to store the rating vote and update the screen via Ajax
    var votes=readCookie("votes");
    if(!votes) votes="";
    if(votes!="")
    {  //Check you can only vote once
        if(votes.indexOf(itemType+"_"+itemId+",")!=-1)
        {
            alert("You have already rated this item.");
            return false
        }
    }
    var t2 = Math.random(); //Fixes an IE caching issue
    $('rating'+itemId).innerHTML= "<div  style='position: absolute; margin-left: 30px; z-index: 99; background: white;'><img src='cms/images/indicator.gif' alt='loading' /> Loading...</div>"+$('rating'+itemId).innerHTML;
    new Ajax.Updater('rating'+itemId, '_rating.inc.ajax.php', { method: 'get', parameters: { r: rate, i: itemId, t: itemType, s: t2 } });
    createCookie("votes",votes+itemType+"_"+itemId+",",1);
    //alert("Thank you for rating this item.");
    return false;
}

function emailContact(itemId, itemType, action)
{   //Click in SDRR flash to report a tip or send to a friend
    document.location.href="contact.php?t="+itemType+"&a="+action+"&i="+itemId;
}

function showHelp(helpId)
{  //Function to fetch and display help text
    var t2 = Math.random(); //Fixes an IE caching issue
    //$('popup_help_text_content').innerHTML= "<div  style='position: absolute; margin-left: 30px; z-index: 99; background: white;'><img src='cms/images/indicator.gif' alt='loading' /> Loading...</div>"+$('popup_help_text').innerHTML;
    new Ajax.Updater('popup_help_text_content', '/_helptext.ajax.php',
        
        { method: 'get',
        onComplete: function()
            { 
              $('popup_help_text').style.width="";
              $('popup_help_text').style.display="block";
              if(typeof(window.mouseX)!='undefined')
              {
                $('popup_help_text').style.top=window.mouseY+5+"px";
                $('popup_help_text').style.left="";
                $('popup_help_text').style.right=(pageWidth()-window.mouseX)-5+"px";
              }
            }, 
        parameters: { h: helpId, s: t2 }
        });
    return false;
}

function showProfilePic(url)
{
      $('popup_help_text_content').innerHTML="<img src='"+url+"' onload='stretchParent(this);'/>";
      $('popup_help_text').style.display="block";
      if(typeof(window.mouseX)!='undefined')
      {
        $('popup_help_text').style.top=window.mouseY+5+"px";
        $('popup_help_text').style.left="";
        $('popup_help_text').style.right=(pageWidth()-window.mouseX)-5+"px";
      }
}

function stretchParent(elem)
{ 
    elem.parentNode.parentNode.style.width=elem.width+"px";
    $('popup_help_text').style.right=((pageWidth()/2)-(elem.width/2))+"px";
    top=window.mouseY-(elem.height/2);
    if(top<1) top=1;
    $('popup_help_text').style.top=top+"px";
}

/*Cookie Functions*/
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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function zoomIn(element)
{ //This makes the zoom in div visible, and loads the correct image
    // You need to pass the element containing the original small image, the name of the src is then "munged" to get the large image name.
    var thePic=document.getElementById(element).src;
    var xOffset, yOffset;
    var temp=new Image();
    temp.src=$('zoompic').src;  //Fixes an IE bug.  IE can't find the image width from an image directly, only if declared as an image object
    //xOffset=Math.round(posLeft()+((pageWidth()-temp.width)/2));
    yOffset=Math.round(posTop()+((pageHeight()-temp.height)/2));
    xOffset=Math.round(posLeft()+((996-temp.width)/2));
    document.getElementById("zoom").style.display="block";
    document.getElementById("zoom").style.top=yOffset+10+"px";
    document.getElementById("zoom").style.left=xOffset+"px";
    //document.getElementById("zoompic").src="./theme/indicator.gif";
    //document.getElementById("zoompic").src=thePic.replace(/_medium/,"");
} 
function newPopUp()
{
    if(typeof(window.newPopUpShown)=='undefined')  //Check to see if we have show the message already
    {
        window.newPopUpShown=1;
        var popup=document.getElementById('new');
        var yOffset=Math.round((pageHeight()-300)/2);
        var xOffset=Math.round((pageWidth()-500)/2);
        popup.style.padding=5+"px";
        popup.style.width=500+"px";
        //popup.style.height=125+5+"px";
        popup.style.display='block';
        popup.style.top=yOffset+100+"px";
        popup.style.left=xOffset+"px";
        popup.onclick=function() { this.style.display='none';};
        //popup.onmouseover=function() {this.style.cursor='pointer';};
    }
}

function countDown(elem, max)
{//Function to count the content number of chars in an input element
//It reduces a count in a span tag as well.  e.g. (<span id='iF_tiptextcnt'>1000</span> Chars Left)
//where the span id is the field name plus 'cnt'
    if($(elem.id+'cnt')!=null && max>0) $(elem.id+'cnt').innerHTML=max-elem.value.length;
    if(elem.value.length>max)
    {  
        elem.value=elem.value.substring(0,(max));
        $(elem.id+'cnt').innerHTML=max-elem.value.length;
        elem.scrollTop = elem.scrollHeight;
        elem.scrollRight = elem.scrollWidth;

        alert("You have reached the "+max+" character limit.");
    }
}

function ajaxUpdateRegion(country, formField, type)
{   //Function to update the selectable region after the country has changed
    var dir="";
    if(document.location.host=="dev") dir="/duo";  //So it works on the dev sys
    new Ajax.Request(dir+'/_regionchoice.ajax.php', 
    {
        method: 'get',
        parameters: {country: country, type: type},
        onSuccess: function(transport)
        {
            //The ajax page returns a pipe delimited string e.g. 1|Aberdeen|2|Anglesey|3|Angus
            var response = transport.responseText || "|Error:- Unable to find county options.";
            var opts=response.split("|");  //Split into an array.  Even indexes contain values, odd contain names
            var i,j=0;
            var currentSelection=$(formField).value;
            $(formField).options.length=0;
            //Loop through the coutries creating the options for the drop down list box
            for(i=0;i<opts.length;i=i+2)
            { 
                $(formField).options[j]=new Option(opts[i+1],opts[i]);
                if(currentSelection==opts[i]) $(formField).options[j].selected=true;
                j++;
            }
        }
    });
}

function insertAtCursor(myField, myValue)
{
    //IE support
    if(document.selection)
    {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //MOZILLA/NETSCAPE support
    else if(myField.selectionStart || myField.selectionStart == '0')
    {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue
        + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

